aoptx86.pas 703 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  46. how many instructions away that Next is from Current is.
  47. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  48. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  49. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  50. potentially allowing further optimisation (although it might need to know if
  51. it crossed a conditional jump. }
  52. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  53. {
  54. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  55. the use of a register by allocs/dealloc, so it can ignore calls.
  56. In the following example, GetNextInstructionUsingReg will return the second movq,
  57. GetNextInstructionUsingRegTrackingUse won't.
  58. movq %rdi,%rax
  59. # Register rdi released
  60. # Register rdi allocated
  61. movq %rax,%rdi
  62. While in this example:
  63. movq %rdi,%rax
  64. call proc
  65. movq %rdi,%rax
  66. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  67. won't.
  68. }
  69. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  70. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  71. private
  72. function SkipSimpleInstructions(var hp1: tai): Boolean;
  73. protected
  74. class function IsMOVZXAcceptable: Boolean; static; inline;
  75. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  76. { Attempts to allocate a volatile integer register for use between p and hp,
  77. using AUsedRegs for the current register usage information. Returns NR_NO
  78. if no free register could be found }
  79. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  80. { Attempts to allocate a volatile MM register for use between p and hp,
  81. using AUsedRegs for the current register usage information. Returns NR_NO
  82. if no free register could be found }
  83. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  84. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  85. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  86. { checks whether reading the value in reg1 depends on the value of reg2. This
  87. is very similar to SuperRegisterEquals, except it takes into account that
  88. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  89. depend on the value in AH). }
  90. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  91. { Replaces all references to AOldReg in a memory reference to ANewReg }
  92. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  93. { Replaces all references to AOldReg in an operand to ANewReg }
  94. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  95. { Replaces all references to AOldReg in an instruction to ANewReg,
  96. except where the register is being written }
  97. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  98. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  99. or writes to a global symbol }
  100. class function IsRefSafe(const ref: PReference): Boolean; static;
  101. { Returns true if the given MOV instruction can be safely converted to CMOV }
  102. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  103. { Like UpdateUsedRegs, but ignores deallocations }
  104. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  105. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  106. class function IsBTXAcceptable(p : tai) : boolean; static;
  107. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  108. conversion was successful }
  109. function ConvertLEA(const p : taicpu): Boolean;
  110. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  111. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  112. procedure DebugMsg(const s : string; p : tai);inline;
  113. class function IsExitCode(p : tai) : boolean; static;
  114. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  115. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  116. procedure RemoveLastDeallocForFuncRes(p : tai);
  117. function DoArithCombineOpt(var p : tai) : Boolean;
  118. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  119. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  120. function PrePeepholeOptSxx(var p : tai) : boolean;
  121. function PrePeepholeOptIMUL(var p : tai) : boolean;
  122. function PrePeepholeOptAND(var p : tai) : boolean;
  123. function OptPass1Test(var p: tai): boolean;
  124. function OptPass1Add(var p: tai): boolean;
  125. function OptPass1AND(var p : tai) : boolean;
  126. function OptPass1_V_MOVAP(var p : tai) : boolean;
  127. function OptPass1VOP(var p : tai) : boolean;
  128. function OptPass1MOV(var p : tai) : boolean;
  129. function OptPass1Movx(var p : tai) : boolean;
  130. function OptPass1MOVXX(var p : tai) : boolean;
  131. function OptPass1OP(var p : tai) : boolean;
  132. function OptPass1LEA(var p : tai) : boolean;
  133. function OptPass1Sub(var p : tai) : boolean;
  134. function OptPass1SHLSAL(var p : tai) : boolean;
  135. function OptPass1SHR(var p : tai) : boolean;
  136. function OptPass1FSTP(var p : tai) : boolean;
  137. function OptPass1FLD(var p : tai) : boolean;
  138. function OptPass1Cmp(var p : tai) : boolean;
  139. function OptPass1PXor(var p : tai) : boolean;
  140. function OptPass1VPXor(var p: tai): boolean;
  141. function OptPass1Imul(var p : tai) : boolean;
  142. function OptPass1Jcc(var p : tai) : boolean;
  143. function OptPass1SHXX(var p: tai): boolean;
  144. function OptPass1VMOVDQ(var p: tai): Boolean;
  145. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  146. function OptPass2Movx(var p : tai): Boolean;
  147. function OptPass2MOV(var p : tai) : boolean;
  148. function OptPass2Imul(var p : tai) : boolean;
  149. function OptPass2Jmp(var p : tai) : boolean;
  150. function OptPass2Jcc(var p : tai) : boolean;
  151. function OptPass2Lea(var p: tai): Boolean;
  152. function OptPass2SUB(var p: tai): Boolean;
  153. function OptPass2ADD(var p : tai): Boolean;
  154. function OptPass2SETcc(var p : tai) : boolean;
  155. function OptPass2Cmp(var p: tai): Boolean;
  156. function OptPass2Test(var p: tai): Boolean;
  157. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  158. function PostPeepholeOptMov(var p : tai) : Boolean;
  159. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  160. function PostPeepholeOptXor(var p : tai) : Boolean;
  161. function PostPeepholeOptAnd(var p : tai) : boolean;
  162. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  163. function PostPeepholeOptCmp(var p : tai) : Boolean;
  164. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  165. function PostPeepholeOptCall(var p : tai) : Boolean;
  166. function PostPeepholeOptLea(var p : tai) : Boolean;
  167. function PostPeepholeOptPush(var p: tai): Boolean;
  168. function PostPeepholeOptShr(var p : tai) : boolean;
  169. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  170. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  171. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  172. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  173. function TrySwapMovOp(var p, hp1: tai): Boolean;
  174. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  175. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  176. { Processor-dependent reference optimisation }
  177. class procedure OptimizeRefs(var p: taicpu); static;
  178. end;
  179. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  180. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  181. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  182. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  183. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  184. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  185. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  186. {$if max_operands>2}
  187. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  188. {$endif max_operands>2}
  189. function RefsEqual(const r1, r2: treference): boolean;
  190. { Note that Result is set to True if the references COULD overlap but the
  191. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  192. might still overlap because %reg2 could be equal to %reg1-4 }
  193. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  194. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  195. { returns true, if ref is a reference using only the registers passed as base and index
  196. and having an offset }
  197. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  198. implementation
  199. uses
  200. cutils,verbose,
  201. systems,
  202. globals,
  203. cpuinfo,
  204. procinfo,
  205. paramgr,
  206. aasmbase,
  207. aoptbase,aoptutils,
  208. symconst,symsym,
  209. cgx86,
  210. itcpugas;
  211. {$ifndef 8086}
  212. const
  213. MAX_CMOV_INSTRUCTIONS = 4;
  214. MAX_CMOV_REGISTERS = 8;
  215. type
  216. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  217. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  218. tsProcessed);
  219. { For OptPass2Jcc }
  220. TCMOVTracking = object
  221. private
  222. CMOVScore, ConstCount: LongInt;
  223. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  224. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  225. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  226. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  227. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  228. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  229. fOptimizer: TX86AsmOptimizer;
  230. fLabel: TAsmSymbol;
  231. fInsertionPoint,
  232. fCondition,
  233. fInitialJump,
  234. fFirstMovBlock,
  235. fFirstMovBlockStop,
  236. fSecondJump,
  237. fThirdJump,
  238. fSecondMovBlock,
  239. fSecondMovBlockStop,
  240. fMidLabel,
  241. fEndLabel,
  242. fAllocationRange: tai;
  243. fState: TCMovTrackingState;
  244. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  245. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  246. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  247. public
  248. RegisterTracking: TAllUsedRegs;
  249. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  250. destructor Done;
  251. procedure Process(out new_p: tai);
  252. property State: TCMovTrackingState read fState;
  253. end;
  254. PCMOVTracking = ^TCMOVTracking;
  255. {$endif 8086}
  256. {$ifdef DEBUG_AOPTCPU}
  257. const
  258. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  259. {$else DEBUG_AOPTCPU}
  260. { Empty strings help the optimizer to remove string concatenations that won't
  261. ever appear to the user on release builds. [Kit] }
  262. const
  263. SPeepholeOptimization = '';
  264. {$endif DEBUG_AOPTCPU}
  265. LIST_STEP_SIZE = 4;
  266. type
  267. TJumpTrackingItem = class(TLinkedListItem)
  268. private
  269. FSymbol: TAsmSymbol;
  270. FRefs: LongInt;
  271. public
  272. constructor Create(ASymbol: TAsmSymbol);
  273. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  274. property Symbol: TAsmSymbol read FSymbol;
  275. property Refs: LongInt read FRefs;
  276. end;
  277. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  278. begin
  279. inherited Create;
  280. FSymbol := ASymbol;
  281. FRefs := 0;
  282. end;
  283. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  284. begin
  285. Inc(FRefs);
  286. end;
  287. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  288. begin
  289. result :=
  290. (instr.typ = ait_instruction) and
  291. (taicpu(instr).opcode = op) and
  292. ((opsize = []) or (taicpu(instr).opsize in opsize));
  293. end;
  294. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  295. begin
  296. result :=
  297. (instr.typ = ait_instruction) and
  298. ((taicpu(instr).opcode = op1) or
  299. (taicpu(instr).opcode = op2)
  300. ) and
  301. ((opsize = []) or (taicpu(instr).opsize in opsize));
  302. end;
  303. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  304. begin
  305. result :=
  306. (instr.typ = ait_instruction) and
  307. ((taicpu(instr).opcode = op1) or
  308. (taicpu(instr).opcode = op2) or
  309. (taicpu(instr).opcode = op3)
  310. ) and
  311. ((opsize = []) or (taicpu(instr).opsize in opsize));
  312. end;
  313. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  314. const opsize : topsizes) : boolean;
  315. var
  316. op : TAsmOp;
  317. begin
  318. result:=false;
  319. if (instr.typ <> ait_instruction) or
  320. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  321. exit;
  322. for op in ops do
  323. begin
  324. if taicpu(instr).opcode = op then
  325. begin
  326. result:=true;
  327. exit;
  328. end;
  329. end;
  330. end;
  331. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  332. begin
  333. result := (oper.typ = top_reg) and (oper.reg = reg);
  334. end;
  335. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  336. begin
  337. result := (oper.typ = top_const) and (oper.val = a);
  338. end;
  339. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  340. begin
  341. result := oper1.typ = oper2.typ;
  342. if result then
  343. case oper1.typ of
  344. top_const:
  345. Result:=oper1.val = oper2.val;
  346. top_reg:
  347. Result:=oper1.reg = oper2.reg;
  348. top_ref:
  349. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  350. else
  351. internalerror(2013102801);
  352. end
  353. end;
  354. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  355. begin
  356. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  357. if result then
  358. case oper1.typ of
  359. top_const:
  360. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  361. top_reg:
  362. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  363. top_ref:
  364. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  365. else
  366. internalerror(2020052401);
  367. end
  368. end;
  369. function RefsEqual(const r1, r2: treference): boolean;
  370. begin
  371. RefsEqual :=
  372. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  373. (r1.relsymbol = r2.relsymbol) and
  374. (r1.segment = r2.segment) and (r1.base = r2.base) and
  375. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  376. (r1.offset = r2.offset) and
  377. (r1.volatility + r2.volatility = []);
  378. end;
  379. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  380. begin
  381. if (r1.symbol<>r2.symbol) then
  382. { If the index registers are different, there's a chance one could
  383. be set so it equals the other symbol }
  384. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  385. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  386. (r1.relsymbol = r2.relsymbol) and
  387. (r1.segment = r2.segment) and (r1.base = r2.base) and
  388. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  389. (r1.volatility + r2.volatility = []) then
  390. { In this case, it all depends on the offsets }
  391. Exit(abs(r1.offset - r2.offset) < Range);
  392. { There's a chance things MIGHT overlap, so take no chances }
  393. Result := True;
  394. end;
  395. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  396. begin
  397. Result:=(ref.offset=0) and
  398. (ref.scalefactor in [0,1]) and
  399. (ref.segment=NR_NO) and
  400. (ref.symbol=nil) and
  401. (ref.relsymbol=nil) and
  402. ((base=NR_INVALID) or
  403. (ref.base=base)) and
  404. ((index=NR_INVALID) or
  405. (ref.index=index)) and
  406. (ref.volatility=[]);
  407. end;
  408. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  409. begin
  410. Result:=(ref.scalefactor in [0,1]) and
  411. (ref.segment=NR_NO) and
  412. (ref.symbol=nil) and
  413. (ref.relsymbol=nil) and
  414. ((base=NR_INVALID) or
  415. (ref.base=base)) and
  416. ((index=NR_INVALID) or
  417. (ref.index=index)) and
  418. (ref.volatility=[]);
  419. end;
  420. function InstrReadsFlags(p: tai): boolean;
  421. begin
  422. InstrReadsFlags := true;
  423. case p.typ of
  424. ait_instruction:
  425. if InsProp[taicpu(p).opcode].Ch*
  426. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  427. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  428. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  429. exit;
  430. ait_label:
  431. exit;
  432. else
  433. ;
  434. end;
  435. InstrReadsFlags := false;
  436. end;
  437. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  438. begin
  439. Next:=Current;
  440. repeat
  441. Result:=GetNextInstruction(Next,Next);
  442. until not (Result) or
  443. not(cs_opt_level3 in current_settings.optimizerswitches) or
  444. (Next.typ<>ait_instruction) or
  445. RegInInstruction(reg,Next) or
  446. is_calljmp(taicpu(Next).opcode);
  447. end;
  448. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  449. var
  450. GetNextResult: Boolean;
  451. begin
  452. Result:=0;
  453. Next:=Current;
  454. repeat
  455. GetNextResult := GetNextInstruction(Next,Next);
  456. if GetNextResult then
  457. Inc(Result)
  458. else
  459. { Must return zero upon hitting the end of the linked list without a match }
  460. Result := 0;
  461. until not (GetNextResult) or
  462. not(cs_opt_level3 in current_settings.optimizerswitches) or
  463. (Next.typ<>ait_instruction) or
  464. RegInInstruction(reg,Next) or
  465. is_calljmp(taicpu(Next).opcode);
  466. end;
  467. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  468. procedure TrackJump(Symbol: TAsmSymbol);
  469. var
  470. Search: TJumpTrackingItem;
  471. begin
  472. { See if an entry already exists in our jump tracking list
  473. (faster to search backwards due to the higher chance of
  474. matching destinations) }
  475. Search := TJumpTrackingItem(JumpTracking.Last);
  476. while Assigned(Search) do
  477. begin
  478. if Search.Symbol = Symbol then
  479. begin
  480. { Found it - remove it so it can be pushed to the front }
  481. JumpTracking.Remove(Search);
  482. Break;
  483. end;
  484. Search := TJumpTrackingItem(Search.Previous);
  485. end;
  486. if not Assigned(Search) then
  487. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  488. JumpTracking.Concat(Search);
  489. Search.IncRefs;
  490. end;
  491. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  492. var
  493. Search: TJumpTrackingItem;
  494. begin
  495. Result := False;
  496. { See if this label appears in the tracking list }
  497. Search := TJumpTrackingItem(JumpTracking.Last);
  498. while Assigned(Search) do
  499. begin
  500. if Search.Symbol = Symbol then
  501. begin
  502. { Found it - let's see what we can discover }
  503. if Search.Symbol.getrefs = Search.Refs then
  504. begin
  505. { Success - all the references are accounted for }
  506. JumpTracking.Remove(Search);
  507. Search.Free;
  508. { It is logically impossible for CrossJump to be false here
  509. because we must have run into a conditional jump for
  510. this label at some point }
  511. if not CrossJump then
  512. InternalError(2022041710);
  513. if JumpTracking.First = nil then
  514. { Tracking list is now empty - no more cross jumps }
  515. CrossJump := False;
  516. Result := True;
  517. Exit;
  518. end;
  519. { If the references don't match, it's possible to enter
  520. this label through other means, so drop out }
  521. Exit;
  522. end;
  523. Search := TJumpTrackingItem(Search.Previous);
  524. end;
  525. end;
  526. var
  527. Next_Label: tai;
  528. begin
  529. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  530. Next := Current;
  531. repeat
  532. Result := GetNextInstruction(Next,Next);
  533. if not Result then
  534. Break;
  535. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  536. if is_calljmpuncondret(taicpu(Next).opcode) then
  537. begin
  538. if (taicpu(Next).opcode = A_JMP) and
  539. { Remove dead code now to save time }
  540. RemoveDeadCodeAfterJump(taicpu(Next)) then
  541. { A jump was removed, but not the current instruction, and
  542. Result doesn't necessarily translate into an optimisation
  543. routine's Result, so use the "Force New Iteration" flag so
  544. mark a new pass }
  545. Include(OptsToCheck, aoc_ForceNewIteration);
  546. if not Assigned(JumpTracking) then
  547. begin
  548. { Cross-label optimisations often causes other optimisations
  549. to perform worse because they're not given the chance to
  550. optimise locally. In this case, don't do the cross-label
  551. optimisations yet, but flag them as a potential possibility
  552. for the next iteration of Pass 1 }
  553. if not NotFirstIteration then
  554. Include(OptsToCheck, aoc_ForceNewIteration);
  555. end
  556. else if IsJumpToLabel(taicpu(Next)) and
  557. GetNextInstruction(Next, Next_Label) then
  558. begin
  559. { If we have JMP .lbl, and the label after it has all of its
  560. references tracked, then this is probably an if-else style of
  561. block and we can keep tracking. If the label for this jump
  562. then appears later and is fully tracked, then it's the end
  563. of the if-else blocks and the code paths converge (thus
  564. marking the end of the cross-jump) }
  565. if (Next_Label.typ = ait_label) then
  566. begin
  567. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  568. begin
  569. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  570. Next := Next_Label;
  571. { CrossJump gets set to false by LabelAccountedFor if the
  572. list is completely emptied (as it indicates that all
  573. code paths have converged). We could avoid this nuance
  574. by moving the TrackJump call to before the
  575. LabelAccountedFor call, but this is slower in situations
  576. where LabelAccountedFor would return False due to the
  577. creation of a new object that is not used and destroyed
  578. soon after. }
  579. CrossJump := True;
  580. Continue;
  581. end;
  582. end
  583. else if (Next_Label.typ <> ait_marker) then
  584. { We just did a RemoveDeadCodeAfterJump, so either we find
  585. a label, the end of the procedure or some kind of marker}
  586. InternalError(2022041720);
  587. end;
  588. Result := False;
  589. Exit;
  590. end
  591. else
  592. begin
  593. if not Assigned(JumpTracking) then
  594. begin
  595. { Cross-label optimisations often causes other optimisations
  596. to perform worse because they're not given the chance to
  597. optimise locally. In this case, don't do the cross-label
  598. optimisations yet, but flag them as a potential possibility
  599. for the next iteration of Pass 1 }
  600. if not NotFirstIteration then
  601. Include(OptsToCheck, aoc_ForceNewIteration);
  602. end
  603. else if IsJumpToLabel(taicpu(Next)) then
  604. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  605. else
  606. { Conditional jumps should always be a jump to label }
  607. InternalError(2022041701);
  608. CrossJump := True;
  609. Continue;
  610. end;
  611. if Next.typ = ait_label then
  612. begin
  613. if not Assigned(JumpTracking) then
  614. begin
  615. { Cross-label optimisations often causes other optimisations
  616. to perform worse because they're not given the chance to
  617. optimise locally. In this case, don't do the cross-label
  618. optimisations yet, but flag them as a potential possibility
  619. for the next iteration of Pass 1 }
  620. if not NotFirstIteration then
  621. Include(OptsToCheck, aoc_ForceNewIteration);
  622. end
  623. else if LabelAccountedFor(tai_label(Next).labsym) then
  624. Continue;
  625. { If we reach here, we're at a label that hasn't been seen before
  626. (or JumpTracking was nil) }
  627. Break;
  628. end;
  629. until not Result or
  630. not (cs_opt_level3 in current_settings.optimizerswitches) or
  631. not (Next.typ in [ait_label, ait_instruction]) or
  632. RegInInstruction(reg,Next);
  633. end;
  634. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  635. begin
  636. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  637. begin
  638. Result:=GetNextInstruction(Current,Next);
  639. exit;
  640. end;
  641. Next:=tai(Current.Next);
  642. Result:=false;
  643. while assigned(Next) do
  644. begin
  645. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  646. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  647. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  648. exit
  649. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  650. begin
  651. Result:=true;
  652. exit;
  653. end;
  654. Next:=tai(Next.Next);
  655. end;
  656. end;
  657. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  658. begin
  659. Result:=RegReadByInstruction(reg,hp);
  660. end;
  661. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  662. var
  663. p: taicpu;
  664. opcount: longint;
  665. begin
  666. RegReadByInstruction := false;
  667. if hp.typ <> ait_instruction then
  668. exit;
  669. p := taicpu(hp);
  670. case p.opcode of
  671. A_CALL:
  672. regreadbyinstruction := true;
  673. A_IMUL:
  674. case p.ops of
  675. 1:
  676. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  677. (
  678. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  679. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  680. );
  681. 2,3:
  682. regReadByInstruction :=
  683. reginop(reg,p.oper[0]^) or
  684. reginop(reg,p.oper[1]^);
  685. else
  686. InternalError(2019112801);
  687. end;
  688. A_MUL:
  689. begin
  690. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  691. (
  692. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  693. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  694. );
  695. end;
  696. A_IDIV,A_DIV:
  697. begin
  698. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  699. (
  700. (getregtype(reg)=R_INTREGISTER) and
  701. (
  702. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  703. )
  704. );
  705. end;
  706. else
  707. begin
  708. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  709. begin
  710. RegReadByInstruction := false;
  711. exit;
  712. end;
  713. for opcount := 0 to p.ops-1 do
  714. if (p.oper[opCount]^.typ = top_ref) and
  715. RegInRef(reg,p.oper[opcount]^.ref^) then
  716. begin
  717. RegReadByInstruction := true;
  718. exit
  719. end;
  720. { special handling for SSE MOVSD }
  721. if (p.opcode=A_MOVSD) and (p.ops>0) then
  722. begin
  723. if p.ops<>2 then
  724. internalerror(2017042702);
  725. regReadByInstruction := reginop(reg,p.oper[0]^) or
  726. (
  727. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  728. );
  729. exit;
  730. end;
  731. with insprop[p.opcode] do
  732. begin
  733. case getregtype(reg) of
  734. R_INTREGISTER:
  735. begin
  736. case getsupreg(reg) of
  737. RS_EAX:
  738. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  739. begin
  740. RegReadByInstruction := true;
  741. exit
  742. end;
  743. RS_ECX:
  744. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  745. begin
  746. RegReadByInstruction := true;
  747. exit
  748. end;
  749. RS_EDX:
  750. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  751. begin
  752. RegReadByInstruction := true;
  753. exit
  754. end;
  755. RS_EBX:
  756. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  757. begin
  758. RegReadByInstruction := true;
  759. exit
  760. end;
  761. RS_ESP:
  762. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  763. begin
  764. RegReadByInstruction := true;
  765. exit
  766. end;
  767. RS_EBP:
  768. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  769. begin
  770. RegReadByInstruction := true;
  771. exit
  772. end;
  773. RS_ESI:
  774. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  775. begin
  776. RegReadByInstruction := true;
  777. exit
  778. end;
  779. RS_EDI:
  780. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  781. begin
  782. RegReadByInstruction := true;
  783. exit
  784. end;
  785. end;
  786. end;
  787. R_MMREGISTER:
  788. begin
  789. case getsupreg(reg) of
  790. RS_XMM0:
  791. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  792. begin
  793. RegReadByInstruction := true;
  794. exit
  795. end;
  796. end;
  797. end;
  798. else
  799. ;
  800. end;
  801. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  802. begin
  803. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  804. begin
  805. case p.condition of
  806. C_A,C_NBE, { CF=0 and ZF=0 }
  807. C_BE,C_NA: { CF=1 or ZF=1 }
  808. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  809. C_AE,C_NB,C_NC, { CF=0 }
  810. C_B,C_NAE,C_C: { CF=1 }
  811. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  812. C_NE,C_NZ, { ZF=0 }
  813. C_E,C_Z: { ZF=1 }
  814. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  815. C_G,C_NLE, { ZF=0 and SF=OF }
  816. C_LE,C_NG: { ZF=1 or SF<>OF }
  817. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  818. C_GE,C_NL, { SF=OF }
  819. C_L,C_NGE: { SF<>OF }
  820. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  821. C_NO, { OF=0 }
  822. C_O: { OF=1 }
  823. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  824. C_NP,C_PO, { PF=0 }
  825. C_P,C_PE: { PF=1 }
  826. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  827. C_NS, { SF=0 }
  828. C_S: { SF=1 }
  829. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  830. else
  831. internalerror(2017042701);
  832. end;
  833. if RegReadByInstruction then
  834. exit;
  835. end;
  836. case getsubreg(reg) of
  837. R_SUBW,R_SUBD,R_SUBQ:
  838. RegReadByInstruction :=
  839. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  840. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  841. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  842. R_SUBFLAGCARRY:
  843. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  844. R_SUBFLAGPARITY:
  845. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  846. R_SUBFLAGAUXILIARY:
  847. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  848. R_SUBFLAGZERO:
  849. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  850. R_SUBFLAGSIGN:
  851. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  852. R_SUBFLAGOVERFLOW:
  853. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  854. R_SUBFLAGINTERRUPT:
  855. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  856. R_SUBFLAGDIRECTION:
  857. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  858. else
  859. internalerror(2017042601);
  860. end;
  861. exit;
  862. end;
  863. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  864. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  865. (p.oper[0]^.reg=p.oper[1]^.reg) then
  866. exit;
  867. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  868. begin
  869. RegReadByInstruction := true;
  870. exit
  871. end;
  872. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  873. begin
  874. RegReadByInstruction := true;
  875. exit
  876. end;
  877. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  878. begin
  879. RegReadByInstruction := true;
  880. exit
  881. end;
  882. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  883. begin
  884. RegReadByInstruction := true;
  885. exit
  886. end;
  887. end;
  888. end;
  889. end;
  890. end;
  891. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  892. begin
  893. result:=false;
  894. if p1.typ<>ait_instruction then
  895. exit;
  896. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  897. exit(true);
  898. if (getregtype(reg)=R_INTREGISTER) and
  899. { change information for xmm movsd are not correct }
  900. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  901. begin
  902. { Handle instructions that behave differently depending on the size and operand count }
  903. case taicpu(p1).opcode of
  904. A_MUL, A_DIV, A_IDIV:
  905. if taicpu(p1).opsize = S_B then
  906. Result := (getsupreg(Reg) = RS_EAX)
  907. else
  908. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  909. A_IMUL:
  910. if taicpu(p1).ops = 1 then
  911. begin
  912. if taicpu(p1).opsize = S_B then
  913. Result := (getsupreg(Reg) = RS_EAX)
  914. else
  915. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  916. end;
  917. { If ops are greater than 1, call inherited method }
  918. else
  919. case getsupreg(reg) of
  920. { RS_EAX = RS_RAX on x86-64 }
  921. RS_EAX:
  922. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  923. RS_ECX:
  924. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  925. RS_EDX:
  926. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  927. RS_EBX:
  928. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  929. RS_ESP:
  930. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  931. RS_EBP:
  932. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  933. RS_ESI:
  934. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  935. RS_EDI:
  936. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  937. else
  938. ;
  939. end;
  940. end;
  941. if result then
  942. exit;
  943. end
  944. else if getregtype(reg)=R_MMREGISTER then
  945. begin
  946. case getsupreg(reg) of
  947. RS_XMM0:
  948. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  949. else
  950. ;
  951. end;
  952. if result then
  953. exit;
  954. end
  955. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  956. begin
  957. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  958. exit(true);
  959. case getsubreg(reg) of
  960. R_SUBFLAGCARRY:
  961. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  962. R_SUBFLAGPARITY:
  963. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  964. R_SUBFLAGAUXILIARY:
  965. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  966. R_SUBFLAGZERO:
  967. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  968. R_SUBFLAGSIGN:
  969. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  970. R_SUBFLAGOVERFLOW:
  971. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  972. R_SUBFLAGINTERRUPT:
  973. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  974. R_SUBFLAGDIRECTION:
  975. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  976. R_SUBW,R_SUBD,R_SUBQ:
  977. { Everything except the direction bits }
  978. Result:=
  979. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  980. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  981. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  982. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  983. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  984. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  985. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  986. else
  987. ;
  988. end;
  989. if result then
  990. exit;
  991. end
  992. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  993. exit(true);
  994. Result:=inherited RegInInstruction(Reg, p1);
  995. end;
  996. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  997. const
  998. WriteOps: array[0..3] of set of TInsChange =
  999. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1000. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1001. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1002. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1003. var
  1004. OperIdx: Integer;
  1005. begin
  1006. Result := False;
  1007. if p1.typ <> ait_instruction then
  1008. exit;
  1009. with insprop[taicpu(p1).opcode] do
  1010. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1011. begin
  1012. case getsubreg(reg) of
  1013. R_SUBW,R_SUBD,R_SUBQ:
  1014. Result :=
  1015. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1016. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1017. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1018. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1019. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1020. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1021. R_SUBFLAGCARRY:
  1022. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1023. R_SUBFLAGPARITY:
  1024. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1025. R_SUBFLAGAUXILIARY:
  1026. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1027. R_SUBFLAGZERO:
  1028. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1029. R_SUBFLAGSIGN:
  1030. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1031. R_SUBFLAGOVERFLOW:
  1032. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1033. R_SUBFLAGINTERRUPT:
  1034. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1035. R_SUBFLAGDIRECTION:
  1036. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1037. else
  1038. internalerror(2017042602);
  1039. end;
  1040. exit;
  1041. end;
  1042. case taicpu(p1).opcode of
  1043. A_CALL:
  1044. { We could potentially set Result to False if the register in
  1045. question is non-volatile for the subroutine's calling convention,
  1046. but this would require detecting the calling convention in use and
  1047. also assuming that the routine doesn't contain malformed assembly
  1048. language, for example... so it could only be done under -O4 as it
  1049. would be considered a side-effect. [Kit] }
  1050. Result := True;
  1051. A_MOVSD:
  1052. { special handling for SSE MOVSD }
  1053. if (taicpu(p1).ops>0) then
  1054. begin
  1055. if taicpu(p1).ops<>2 then
  1056. internalerror(2017042703);
  1057. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1058. end;
  1059. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1060. so fix it here (FK)
  1061. }
  1062. A_VMOVSS,
  1063. A_VMOVSD:
  1064. begin
  1065. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1066. exit;
  1067. end;
  1068. A_MUL, A_DIV, A_IDIV:
  1069. begin
  1070. if taicpu(p1).opsize = S_B then
  1071. Result := (getsupreg(Reg) = RS_EAX)
  1072. else
  1073. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1074. end;
  1075. A_IMUL:
  1076. begin
  1077. if taicpu(p1).ops = 1 then
  1078. begin
  1079. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1080. end
  1081. else
  1082. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1083. Exit;
  1084. end;
  1085. else
  1086. ;
  1087. end;
  1088. if Result then
  1089. exit;
  1090. with insprop[taicpu(p1).opcode] do
  1091. begin
  1092. if getregtype(reg)=R_INTREGISTER then
  1093. begin
  1094. case getsupreg(reg) of
  1095. RS_EAX:
  1096. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1097. begin
  1098. Result := True;
  1099. exit
  1100. end;
  1101. RS_ECX:
  1102. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1103. begin
  1104. Result := True;
  1105. exit
  1106. end;
  1107. RS_EDX:
  1108. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1109. begin
  1110. Result := True;
  1111. exit
  1112. end;
  1113. RS_EBX:
  1114. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1115. begin
  1116. Result := True;
  1117. exit
  1118. end;
  1119. RS_ESP:
  1120. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1121. begin
  1122. Result := True;
  1123. exit
  1124. end;
  1125. RS_EBP:
  1126. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1127. begin
  1128. Result := True;
  1129. exit
  1130. end;
  1131. RS_ESI:
  1132. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1133. begin
  1134. Result := True;
  1135. exit
  1136. end;
  1137. RS_EDI:
  1138. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1139. begin
  1140. Result := True;
  1141. exit
  1142. end;
  1143. end;
  1144. end;
  1145. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1146. if (WriteOps[OperIdx]*Ch<>[]) and
  1147. { The register doesn't get modified inside a reference }
  1148. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1149. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1150. begin
  1151. Result := true;
  1152. exit
  1153. end;
  1154. end;
  1155. end;
  1156. {$ifdef DEBUG_AOPTCPU}
  1157. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1158. begin
  1159. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1160. end;
  1161. function debug_tostr(i: tcgint): string; inline;
  1162. begin
  1163. Result := tostr(i);
  1164. end;
  1165. function debug_hexstr(i: tcgint): string;
  1166. begin
  1167. Result := '0x';
  1168. case i of
  1169. 0..$FF:
  1170. Result := Result + hexstr(i, 2);
  1171. $100..$FFFF:
  1172. Result := Result + hexstr(i, 4);
  1173. $10000..$FFFFFF:
  1174. Result := Result + hexstr(i, 6);
  1175. $1000000..$FFFFFFFF:
  1176. Result := Result + hexstr(i, 8);
  1177. else
  1178. Result := Result + hexstr(i, 16);
  1179. end;
  1180. end;
  1181. function debug_regname(r: TRegister): string; inline;
  1182. begin
  1183. Result := '%' + std_regname(r);
  1184. end;
  1185. { Debug output function - creates a string representation of an operator }
  1186. function debug_operstr(oper: TOper): string;
  1187. begin
  1188. case oper.typ of
  1189. top_const:
  1190. Result := '$' + debug_tostr(oper.val);
  1191. top_reg:
  1192. Result := debug_regname(oper.reg);
  1193. top_ref:
  1194. begin
  1195. if oper.ref^.offset <> 0 then
  1196. Result := debug_tostr(oper.ref^.offset) + '('
  1197. else
  1198. Result := '(';
  1199. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1200. begin
  1201. Result := Result + debug_regname(oper.ref^.base);
  1202. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1203. Result := Result + ',' + debug_regname(oper.ref^.index);
  1204. end
  1205. else
  1206. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1207. Result := Result + debug_regname(oper.ref^.index);
  1208. if (oper.ref^.scalefactor > 1) then
  1209. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1210. else
  1211. Result := Result + ')';
  1212. end;
  1213. else
  1214. Result := '[UNKNOWN]';
  1215. end;
  1216. end;
  1217. function debug_op2str(opcode: tasmop): string; inline;
  1218. begin
  1219. Result := std_op2str[opcode];
  1220. end;
  1221. function debug_opsize2str(opsize: topsize): string; inline;
  1222. begin
  1223. Result := gas_opsize2str[opsize];
  1224. end;
  1225. {$else DEBUG_AOPTCPU}
  1226. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1227. begin
  1228. end;
  1229. function debug_tostr(i: tcgint): string; inline;
  1230. begin
  1231. Result := '';
  1232. end;
  1233. function debug_hexstr(i: tcgint): string; inline;
  1234. begin
  1235. Result := '';
  1236. end;
  1237. function debug_regname(r: TRegister): string; inline;
  1238. begin
  1239. Result := '';
  1240. end;
  1241. function debug_operstr(oper: TOper): string; inline;
  1242. begin
  1243. Result := '';
  1244. end;
  1245. function debug_op2str(opcode: tasmop): string; inline;
  1246. begin
  1247. Result := '';
  1248. end;
  1249. function debug_opsize2str(opsize: topsize): string; inline;
  1250. begin
  1251. Result := '';
  1252. end;
  1253. {$endif DEBUG_AOPTCPU}
  1254. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1255. begin
  1256. {$ifdef x86_64}
  1257. { Always fine on x86-64 }
  1258. Result := True;
  1259. {$else x86_64}
  1260. Result :=
  1261. {$ifdef i8086}
  1262. (current_settings.cputype >= cpu_386) and
  1263. {$endif i8086}
  1264. (
  1265. { Always accept if optimising for size }
  1266. (cs_opt_size in current_settings.optimizerswitches) or
  1267. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1268. (current_settings.optimizecputype >= cpu_Pentium2)
  1269. );
  1270. {$endif x86_64}
  1271. end;
  1272. { Attempts to allocate a volatile integer register for use between p and hp,
  1273. using AUsedRegs for the current register usage information. Returns NR_NO
  1274. if no free register could be found }
  1275. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1276. var
  1277. RegSet: TCPURegisterSet;
  1278. CurrentSuperReg: Integer;
  1279. CurrentReg: TRegister;
  1280. Currentp: tai;
  1281. Breakout: Boolean;
  1282. begin
  1283. Result := NR_NO;
  1284. RegSet :=
  1285. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1286. current_procinfo.saved_regs_int;
  1287. (*
  1288. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1289. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1290. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1291. *)
  1292. for CurrentSuperReg in RegSet do
  1293. begin
  1294. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1295. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1296. {$if defined(i386) or defined(i8086)}
  1297. { If the target size is 8-bit, make sure we can actually encode it }
  1298. and (
  1299. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1300. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1301. )
  1302. {$endif i386 or i8086}
  1303. then
  1304. begin
  1305. Currentp := p;
  1306. Breakout := False;
  1307. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1308. begin
  1309. case Currentp.typ of
  1310. ait_instruction:
  1311. begin
  1312. if RegInInstruction(CurrentReg, Currentp) then
  1313. begin
  1314. Breakout := True;
  1315. Break;
  1316. end;
  1317. { Cannot allocate across an unconditional jump }
  1318. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1319. Exit;
  1320. end;
  1321. ait_marker:
  1322. { Don't try anything more if a marker is hit }
  1323. Exit;
  1324. ait_regalloc:
  1325. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1326. begin
  1327. Breakout := True;
  1328. Break;
  1329. end;
  1330. else
  1331. ;
  1332. end;
  1333. end;
  1334. if Breakout then
  1335. { Try the next register }
  1336. Continue;
  1337. { We have a free register available }
  1338. Result := CurrentReg;
  1339. if not DontAlloc then
  1340. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1341. Exit;
  1342. end;
  1343. end;
  1344. end;
  1345. { Attempts to allocate a volatile MM register for use between p and hp,
  1346. using AUsedRegs for the current register usage information. Returns NR_NO
  1347. if no free register could be found }
  1348. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1349. var
  1350. RegSet: TCPURegisterSet;
  1351. CurrentSuperReg: Integer;
  1352. CurrentReg: TRegister;
  1353. Currentp: tai;
  1354. Breakout: Boolean;
  1355. begin
  1356. Result := NR_NO;
  1357. RegSet :=
  1358. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1359. current_procinfo.saved_regs_mm;
  1360. for CurrentSuperReg in RegSet do
  1361. begin
  1362. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1363. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1364. begin
  1365. Currentp := p;
  1366. Breakout := False;
  1367. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1368. begin
  1369. case Currentp.typ of
  1370. ait_instruction:
  1371. begin
  1372. if RegInInstruction(CurrentReg, Currentp) then
  1373. begin
  1374. Breakout := True;
  1375. Break;
  1376. end;
  1377. { Cannot allocate across an unconditional jump }
  1378. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1379. Exit;
  1380. end;
  1381. ait_marker:
  1382. { Don't try anything more if a marker is hit }
  1383. Exit;
  1384. ait_regalloc:
  1385. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1386. begin
  1387. Breakout := True;
  1388. Break;
  1389. end;
  1390. else
  1391. ;
  1392. end;
  1393. end;
  1394. if Breakout then
  1395. { Try the next register }
  1396. Continue;
  1397. { We have a free register available }
  1398. Result := CurrentReg;
  1399. if not DontAlloc then
  1400. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1401. Exit;
  1402. end;
  1403. end;
  1404. end;
  1405. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1406. begin
  1407. if not SuperRegistersEqual(reg1,reg2) then
  1408. exit(false);
  1409. if getregtype(reg1)<>R_INTREGISTER then
  1410. exit(true); {because SuperRegisterEqual is true}
  1411. case getsubreg(reg1) of
  1412. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1413. higher, it preserves the high bits, so the new value depends on
  1414. reg2's previous value. In other words, it is equivalent to doing:
  1415. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1416. R_SUBL:
  1417. exit(getsubreg(reg2)=R_SUBL);
  1418. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1419. higher, it actually does a:
  1420. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1421. R_SUBH:
  1422. exit(getsubreg(reg2)=R_SUBH);
  1423. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1424. bits of reg2:
  1425. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1426. R_SUBW:
  1427. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1428. { a write to R_SUBD always overwrites every other subregister,
  1429. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1430. R_SUBD,
  1431. R_SUBQ:
  1432. exit(true);
  1433. else
  1434. internalerror(2017042801);
  1435. end;
  1436. end;
  1437. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1438. begin
  1439. if not SuperRegistersEqual(reg1,reg2) then
  1440. exit(false);
  1441. if getregtype(reg1)<>R_INTREGISTER then
  1442. exit(true); {because SuperRegisterEqual is true}
  1443. case getsubreg(reg1) of
  1444. R_SUBL:
  1445. exit(getsubreg(reg2)<>R_SUBH);
  1446. R_SUBH:
  1447. exit(getsubreg(reg2)<>R_SUBL);
  1448. R_SUBW,
  1449. R_SUBD,
  1450. R_SUBQ:
  1451. exit(true);
  1452. else
  1453. internalerror(2017042802);
  1454. end;
  1455. end;
  1456. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1457. var
  1458. hp1 : tai;
  1459. l : TCGInt;
  1460. begin
  1461. result:=false;
  1462. if not(GetNextInstruction(p, hp1)) then
  1463. exit;
  1464. { changes the code sequence
  1465. shr/sar const1, x
  1466. shl const2, x
  1467. to
  1468. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1469. if (taicpu(p).oper[0]^.typ = top_const) and
  1470. MatchInstruction(hp1,A_SHL,[]) and
  1471. (taicpu(hp1).oper[0]^.typ = top_const) and
  1472. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1473. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1474. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1475. begin
  1476. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1477. not(cs_opt_size in current_settings.optimizerswitches) then
  1478. begin
  1479. { shr/sar const1, %reg
  1480. shl const2, %reg
  1481. with const1 > const2 }
  1482. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1483. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1484. taicpu(hp1).opcode := A_AND;
  1485. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1486. case taicpu(p).opsize Of
  1487. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1488. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1489. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1490. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1491. else
  1492. Internalerror(2017050703)
  1493. end;
  1494. end
  1495. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1496. not(cs_opt_size in current_settings.optimizerswitches) then
  1497. begin
  1498. { shr/sar const1, %reg
  1499. shl const2, %reg
  1500. with const1 < const2 }
  1501. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1502. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1503. taicpu(p).opcode := A_AND;
  1504. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1505. case taicpu(p).opsize Of
  1506. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1507. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1508. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1509. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1510. else
  1511. Internalerror(2017050702)
  1512. end;
  1513. end
  1514. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1515. begin
  1516. { shr/sar const1, %reg
  1517. shl const2, %reg
  1518. with const1 = const2 }
  1519. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1520. taicpu(p).opcode := A_AND;
  1521. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1522. case taicpu(p).opsize Of
  1523. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1524. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1525. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1526. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1527. else
  1528. Internalerror(2017050701)
  1529. end;
  1530. RemoveInstruction(hp1);
  1531. end;
  1532. end;
  1533. end;
  1534. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1535. var
  1536. opsize : topsize;
  1537. hp1, hp2 : tai;
  1538. tmpref : treference;
  1539. ShiftValue : Cardinal;
  1540. BaseValue : TCGInt;
  1541. begin
  1542. result:=false;
  1543. opsize:=taicpu(p).opsize;
  1544. { changes certain "imul const, %reg"'s to lea sequences }
  1545. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1546. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1547. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1548. if (taicpu(p).oper[0]^.val = 1) then
  1549. if (taicpu(p).ops = 2) then
  1550. { remove "imul $1, reg" }
  1551. begin
  1552. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1553. Result := RemoveCurrentP(p);
  1554. end
  1555. else
  1556. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1557. begin
  1558. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1559. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1560. asml.InsertAfter(hp1, p);
  1561. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1562. RemoveCurrentP(p, hp1);
  1563. Result := True;
  1564. end
  1565. else if ((taicpu(p).ops <= 2) or
  1566. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1567. not(cs_opt_size in current_settings.optimizerswitches) and
  1568. (not(GetNextInstruction(p, hp1)) or
  1569. not((tai(hp1).typ = ait_instruction) and
  1570. ((taicpu(hp1).opcode=A_Jcc) and
  1571. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1572. begin
  1573. {
  1574. imul X, reg1, reg2 to
  1575. lea (reg1,reg1,Y), reg2
  1576. shl ZZ,reg2
  1577. imul XX, reg1 to
  1578. lea (reg1,reg1,YY), reg1
  1579. shl ZZ,reg2
  1580. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1581. it does not exist as a separate optimization target in FPC though.
  1582. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1583. at most two zeros
  1584. }
  1585. reference_reset(tmpref,1,[]);
  1586. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1587. begin
  1588. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1589. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1590. TmpRef.base := taicpu(p).oper[1]^.reg;
  1591. TmpRef.index := taicpu(p).oper[1]^.reg;
  1592. if not(BaseValue in [3,5,9]) then
  1593. Internalerror(2018110101);
  1594. TmpRef.ScaleFactor := BaseValue-1;
  1595. if (taicpu(p).ops = 2) then
  1596. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1597. else
  1598. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1599. AsmL.InsertAfter(hp1,p);
  1600. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1601. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1602. RemoveCurrentP(p, hp1);
  1603. if ShiftValue>0 then
  1604. begin
  1605. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1606. AsmL.InsertAfter(hp2,hp1);
  1607. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1608. end;
  1609. Result := True;
  1610. end;
  1611. end;
  1612. end;
  1613. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1614. begin
  1615. Result := False;
  1616. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1617. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1618. begin
  1619. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1620. taicpu(p).opcode := A_MOV;
  1621. Result := True;
  1622. end;
  1623. end;
  1624. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1625. var
  1626. p: taicpu absolute hp; { Implicit typecast }
  1627. i: Integer;
  1628. begin
  1629. Result := False;
  1630. if not assigned(hp) or
  1631. (hp.typ <> ait_instruction) then
  1632. Exit;
  1633. Prefetch(insprop[p.opcode]);
  1634. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1635. with insprop[p.opcode] do
  1636. begin
  1637. case getsubreg(reg) of
  1638. R_SUBW,R_SUBD,R_SUBQ:
  1639. Result:=
  1640. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1641. uncommon flags are checked first }
  1642. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1643. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1644. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1645. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1646. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1647. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1648. R_SUBFLAGCARRY:
  1649. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1650. R_SUBFLAGPARITY:
  1651. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1652. R_SUBFLAGAUXILIARY:
  1653. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1654. R_SUBFLAGZERO:
  1655. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1656. R_SUBFLAGSIGN:
  1657. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1658. R_SUBFLAGOVERFLOW:
  1659. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1660. R_SUBFLAGINTERRUPT:
  1661. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1662. R_SUBFLAGDIRECTION:
  1663. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1664. else
  1665. internalerror(2017050501);
  1666. end;
  1667. exit;
  1668. end;
  1669. { Handle special cases first }
  1670. case p.opcode of
  1671. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1672. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1673. begin
  1674. Result :=
  1675. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1676. (p.oper[1]^.typ = top_reg) and
  1677. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1678. (
  1679. (p.oper[0]^.typ = top_const) or
  1680. (
  1681. (p.oper[0]^.typ = top_reg) and
  1682. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1683. ) or (
  1684. (p.oper[0]^.typ = top_ref) and
  1685. not RegInRef(reg,p.oper[0]^.ref^)
  1686. )
  1687. );
  1688. end;
  1689. A_MUL, A_IMUL:
  1690. Result :=
  1691. (
  1692. (p.ops=3) and { IMUL only }
  1693. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1694. (
  1695. (
  1696. (p.oper[1]^.typ=top_reg) and
  1697. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1698. ) or (
  1699. (p.oper[1]^.typ=top_ref) and
  1700. not RegInRef(reg,p.oper[1]^.ref^)
  1701. )
  1702. )
  1703. ) or (
  1704. (
  1705. (p.ops=1) and
  1706. (
  1707. (
  1708. (
  1709. (p.oper[0]^.typ=top_reg) and
  1710. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1711. )
  1712. ) or (
  1713. (p.oper[0]^.typ=top_ref) and
  1714. not RegInRef(reg,p.oper[0]^.ref^)
  1715. )
  1716. ) and (
  1717. (
  1718. (p.opsize=S_B) and
  1719. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1720. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1721. ) or (
  1722. (p.opsize=S_W) and
  1723. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1724. ) or (
  1725. (p.opsize=S_L) and
  1726. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1727. {$ifdef x86_64}
  1728. ) or (
  1729. (p.opsize=S_Q) and
  1730. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1731. {$endif x86_64}
  1732. )
  1733. )
  1734. )
  1735. );
  1736. A_CBW:
  1737. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1738. {$ifndef x86_64}
  1739. A_LDS:
  1740. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1741. A_LES:
  1742. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1743. {$endif not x86_64}
  1744. A_LFS:
  1745. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1746. A_LGS:
  1747. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1748. A_LSS:
  1749. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1750. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1751. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1752. A_LODSB:
  1753. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1754. A_LODSW:
  1755. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1756. {$ifdef x86_64}
  1757. A_LODSQ:
  1758. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1759. {$endif x86_64}
  1760. A_LODSD:
  1761. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1762. A_FSTSW, A_FNSTSW:
  1763. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1764. else
  1765. begin
  1766. with insprop[p.opcode] do
  1767. begin
  1768. if (
  1769. { xor %reg,%reg etc. is classed as a new value }
  1770. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1771. MatchOpType(p, top_reg, top_reg) and
  1772. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1773. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1774. ) then
  1775. begin
  1776. Result := True;
  1777. Exit;
  1778. end;
  1779. { Make sure the entire register is overwritten }
  1780. if (getregtype(reg) = R_INTREGISTER) then
  1781. begin
  1782. if (p.ops > 0) then
  1783. begin
  1784. if RegInOp(reg, p.oper[0]^) then
  1785. begin
  1786. if (p.oper[0]^.typ = top_ref) then
  1787. begin
  1788. if RegInRef(reg, p.oper[0]^.ref^) then
  1789. begin
  1790. Result := False;
  1791. Exit;
  1792. end;
  1793. end
  1794. else if (p.oper[0]^.typ = top_reg) then
  1795. begin
  1796. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1797. begin
  1798. Result := False;
  1799. Exit;
  1800. end
  1801. else if ([Ch_WOp1]*Ch<>[]) then
  1802. begin
  1803. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1804. Result := True
  1805. else
  1806. begin
  1807. Result := False;
  1808. Exit;
  1809. end;
  1810. end;
  1811. end;
  1812. end;
  1813. if (p.ops > 1) then
  1814. begin
  1815. if RegInOp(reg, p.oper[1]^) then
  1816. begin
  1817. if (p.oper[1]^.typ = top_ref) then
  1818. begin
  1819. if RegInRef(reg, p.oper[1]^.ref^) then
  1820. begin
  1821. Result := False;
  1822. Exit;
  1823. end;
  1824. end
  1825. else if (p.oper[1]^.typ = top_reg) then
  1826. begin
  1827. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1828. begin
  1829. Result := False;
  1830. Exit;
  1831. end
  1832. else if ([Ch_WOp2]*Ch<>[]) then
  1833. begin
  1834. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1835. Result := True
  1836. else
  1837. begin
  1838. Result := False;
  1839. Exit;
  1840. end;
  1841. end;
  1842. end;
  1843. end;
  1844. if (p.ops > 2) then
  1845. begin
  1846. if RegInOp(reg, p.oper[2]^) then
  1847. begin
  1848. if (p.oper[2]^.typ = top_ref) then
  1849. begin
  1850. if RegInRef(reg, p.oper[2]^.ref^) then
  1851. begin
  1852. Result := False;
  1853. Exit;
  1854. end;
  1855. end
  1856. else if (p.oper[2]^.typ = top_reg) then
  1857. begin
  1858. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1859. begin
  1860. Result := False;
  1861. Exit;
  1862. end
  1863. else if ([Ch_WOp3]*Ch<>[]) then
  1864. begin
  1865. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1866. Result := True
  1867. else
  1868. begin
  1869. Result := False;
  1870. Exit;
  1871. end;
  1872. end;
  1873. end;
  1874. end;
  1875. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1876. begin
  1877. if (p.oper[3]^.typ = top_ref) then
  1878. begin
  1879. if RegInRef(reg, p.oper[3]^.ref^) then
  1880. begin
  1881. Result := False;
  1882. Exit;
  1883. end;
  1884. end
  1885. else if (p.oper[3]^.typ = top_reg) then
  1886. begin
  1887. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1888. begin
  1889. Result := False;
  1890. Exit;
  1891. end
  1892. else if ([Ch_WOp4]*Ch<>[]) then
  1893. begin
  1894. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1895. Result := True
  1896. else
  1897. begin
  1898. Result := False;
  1899. Exit;
  1900. end;
  1901. end;
  1902. end;
  1903. end;
  1904. end;
  1905. end;
  1906. end;
  1907. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1908. case getsupreg(reg) of
  1909. RS_EAX:
  1910. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1911. begin
  1912. Result := True;
  1913. Exit;
  1914. end;
  1915. RS_ECX:
  1916. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1917. begin
  1918. Result := True;
  1919. Exit;
  1920. end;
  1921. RS_EDX:
  1922. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1923. begin
  1924. Result := True;
  1925. Exit;
  1926. end;
  1927. RS_EBX:
  1928. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1929. begin
  1930. Result := True;
  1931. Exit;
  1932. end;
  1933. RS_ESP:
  1934. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1935. begin
  1936. Result := True;
  1937. Exit;
  1938. end;
  1939. RS_EBP:
  1940. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1941. begin
  1942. Result := True;
  1943. Exit;
  1944. end;
  1945. RS_ESI:
  1946. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1947. begin
  1948. Result := True;
  1949. Exit;
  1950. end;
  1951. RS_EDI:
  1952. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1953. begin
  1954. Result := True;
  1955. Exit;
  1956. end;
  1957. else
  1958. ;
  1959. end;
  1960. end;
  1961. end;
  1962. end;
  1963. end;
  1964. end;
  1965. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1966. var
  1967. hp2,hp3 : tai;
  1968. begin
  1969. { some x86-64 issue a NOP before the real exit code }
  1970. if MatchInstruction(p,A_NOP,[]) then
  1971. GetNextInstruction(p,p);
  1972. result:=assigned(p) and (p.typ=ait_instruction) and
  1973. ((taicpu(p).opcode = A_RET) or
  1974. ((taicpu(p).opcode=A_LEAVE) and
  1975. GetNextInstruction(p,hp2) and
  1976. MatchInstruction(hp2,A_RET,[S_NO])
  1977. ) or
  1978. (((taicpu(p).opcode=A_LEA) and
  1979. MatchOpType(taicpu(p),top_ref,top_reg) and
  1980. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1981. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1982. ) and
  1983. GetNextInstruction(p,hp2) and
  1984. MatchInstruction(hp2,A_RET,[S_NO])
  1985. ) or
  1986. ((((taicpu(p).opcode=A_MOV) and
  1987. MatchOpType(taicpu(p),top_reg,top_reg) and
  1988. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1989. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1990. ((taicpu(p).opcode=A_LEA) and
  1991. MatchOpType(taicpu(p),top_ref,top_reg) and
  1992. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1993. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1994. )
  1995. ) and
  1996. GetNextInstruction(p,hp2) and
  1997. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1998. MatchOpType(taicpu(hp2),top_reg) and
  1999. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2000. GetNextInstruction(hp2,hp3) and
  2001. MatchInstruction(hp3,A_RET,[S_NO])
  2002. )
  2003. );
  2004. end;
  2005. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2006. begin
  2007. isFoldableArithOp := False;
  2008. case hp1.opcode of
  2009. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2010. isFoldableArithOp :=
  2011. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2012. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2013. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2014. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2015. (taicpu(hp1).oper[1]^.reg = reg);
  2016. A_INC,A_DEC,A_NEG,A_NOT:
  2017. isFoldableArithOp :=
  2018. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2019. (taicpu(hp1).oper[0]^.reg = reg);
  2020. else
  2021. ;
  2022. end;
  2023. end;
  2024. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2025. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2026. var
  2027. hp2: tai;
  2028. begin
  2029. hp2 := p;
  2030. repeat
  2031. hp2 := tai(hp2.previous);
  2032. if assigned(hp2) and
  2033. (hp2.typ = ait_regalloc) and
  2034. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2035. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2036. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2037. begin
  2038. RemoveInstruction(hp2);
  2039. break;
  2040. end;
  2041. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2042. end;
  2043. begin
  2044. case current_procinfo.procdef.returndef.typ of
  2045. arraydef,recorddef,pointerdef,
  2046. stringdef,enumdef,procdef,objectdef,errordef,
  2047. filedef,setdef,procvardef,
  2048. classrefdef,forwarddef:
  2049. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2050. orddef:
  2051. if current_procinfo.procdef.returndef.size <> 0 then
  2052. begin
  2053. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2054. { for int64/qword }
  2055. if current_procinfo.procdef.returndef.size = 8 then
  2056. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2057. end;
  2058. else
  2059. ;
  2060. end;
  2061. end;
  2062. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2063. var
  2064. hp1,hp2 : tai;
  2065. begin
  2066. result:=false;
  2067. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2068. begin
  2069. { vmova* reg1,reg1
  2070. =>
  2071. <nop> }
  2072. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2073. begin
  2074. RemoveCurrentP(p);
  2075. result:=true;
  2076. exit;
  2077. end;
  2078. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2079. (hp1.typ = ait_instruction) and
  2080. (
  2081. { Under -O2 and below, the instructions are always adjacent }
  2082. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2083. (taicpu(hp1).ops <= 1) or
  2084. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2085. { If reg1 = reg3, reg1 must not be modified in between }
  2086. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2087. ) then
  2088. begin
  2089. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2090. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2091. begin
  2092. { vmova* reg1,reg2
  2093. ...
  2094. vmova* reg2,reg3
  2095. dealloc reg2
  2096. =>
  2097. vmova* reg1,reg3 }
  2098. TransferUsedRegs(TmpUsedRegs);
  2099. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2100. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2101. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2102. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2103. begin
  2104. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2105. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2106. TransferUsedRegs(TmpUsedRegs);
  2107. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2108. RemoveInstruction(hp1);
  2109. result:=true;
  2110. exit;
  2111. end;
  2112. { special case:
  2113. vmova* reg1,<op>
  2114. ...
  2115. vmova* <op>,reg1
  2116. =>
  2117. vmova* reg1,<op> }
  2118. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2119. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2120. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2121. ) then
  2122. begin
  2123. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2124. RemoveInstruction(hp1);
  2125. result:=true;
  2126. exit;
  2127. end
  2128. end
  2129. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2130. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2131. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2132. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2133. ) and
  2134. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2135. begin
  2136. { vmova* reg1,reg2
  2137. ...
  2138. vmovs* reg2,<op>
  2139. dealloc reg2
  2140. =>
  2141. vmovs* reg1,<op> }
  2142. TransferUsedRegs(TmpUsedRegs);
  2143. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2144. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2145. begin
  2146. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2147. taicpu(p).opcode:=taicpu(hp1).opcode;
  2148. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2149. TransferUsedRegs(TmpUsedRegs);
  2150. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2151. RemoveInstruction(hp1);
  2152. result:=true;
  2153. exit;
  2154. end
  2155. end;
  2156. if MatchInstruction(hp1,[A_VFMADDPD,
  2157. A_VFMADD132PD,
  2158. A_VFMADD132PS,
  2159. A_VFMADD132SD,
  2160. A_VFMADD132SS,
  2161. A_VFMADD213PD,
  2162. A_VFMADD213PS,
  2163. A_VFMADD213SD,
  2164. A_VFMADD213SS,
  2165. A_VFMADD231PD,
  2166. A_VFMADD231PS,
  2167. A_VFMADD231SD,
  2168. A_VFMADD231SS,
  2169. A_VFMADDSUB132PD,
  2170. A_VFMADDSUB132PS,
  2171. A_VFMADDSUB213PD,
  2172. A_VFMADDSUB213PS,
  2173. A_VFMADDSUB231PD,
  2174. A_VFMADDSUB231PS,
  2175. A_VFMSUB132PD,
  2176. A_VFMSUB132PS,
  2177. A_VFMSUB132SD,
  2178. A_VFMSUB132SS,
  2179. A_VFMSUB213PD,
  2180. A_VFMSUB213PS,
  2181. A_VFMSUB213SD,
  2182. A_VFMSUB213SS,
  2183. A_VFMSUB231PD,
  2184. A_VFMSUB231PS,
  2185. A_VFMSUB231SD,
  2186. A_VFMSUB231SS,
  2187. A_VFMSUBADD132PD,
  2188. A_VFMSUBADD132PS,
  2189. A_VFMSUBADD213PD,
  2190. A_VFMSUBADD213PS,
  2191. A_VFMSUBADD231PD,
  2192. A_VFMSUBADD231PS,
  2193. A_VFNMADD132PD,
  2194. A_VFNMADD132PS,
  2195. A_VFNMADD132SD,
  2196. A_VFNMADD132SS,
  2197. A_VFNMADD213PD,
  2198. A_VFNMADD213PS,
  2199. A_VFNMADD213SD,
  2200. A_VFNMADD213SS,
  2201. A_VFNMADD231PD,
  2202. A_VFNMADD231PS,
  2203. A_VFNMADD231SD,
  2204. A_VFNMADD231SS,
  2205. A_VFNMSUB132PD,
  2206. A_VFNMSUB132PS,
  2207. A_VFNMSUB132SD,
  2208. A_VFNMSUB132SS,
  2209. A_VFNMSUB213PD,
  2210. A_VFNMSUB213PS,
  2211. A_VFNMSUB213SD,
  2212. A_VFNMSUB213SS,
  2213. A_VFNMSUB231PD,
  2214. A_VFNMSUB231PS,
  2215. A_VFNMSUB231SD,
  2216. A_VFNMSUB231SS],[S_NO]) and
  2217. { we mix single and double opperations here because we assume that the compiler
  2218. generates vmovapd only after double operations and vmovaps only after single operations }
  2219. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2220. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2221. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2222. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2223. begin
  2224. TransferUsedRegs(TmpUsedRegs);
  2225. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2226. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2227. begin
  2228. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2229. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2230. RemoveCurrentP(p)
  2231. else
  2232. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2233. RemoveInstruction(hp2);
  2234. end;
  2235. end
  2236. else if (hp1.typ = ait_instruction) and
  2237. (((taicpu(p).opcode=A_MOVAPS) and
  2238. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2239. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2240. ((taicpu(p).opcode=A_MOVAPD) and
  2241. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2242. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2243. ) and
  2244. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2245. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2246. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2247. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2248. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2249. { change
  2250. movapX reg,reg2
  2251. addsX/subsX/... reg3, reg2
  2252. movapX reg2,reg
  2253. to
  2254. addsX/subsX/... reg3,reg
  2255. }
  2256. begin
  2257. TransferUsedRegs(TmpUsedRegs);
  2258. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2259. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2260. begin
  2261. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2262. debug_op2str(taicpu(p).opcode)+' '+
  2263. debug_op2str(taicpu(hp1).opcode)+' '+
  2264. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2265. { we cannot eliminate the first move if
  2266. the operations uses the same register for source and dest }
  2267. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2268. { Remember that hp1 is not necessarily the immediate
  2269. next instruction }
  2270. RemoveCurrentP(p);
  2271. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2272. RemoveInstruction(hp2);
  2273. result:=true;
  2274. end;
  2275. end
  2276. else if (hp1.typ = ait_instruction) and
  2277. (((taicpu(p).opcode=A_VMOVAPD) and
  2278. (taicpu(hp1).opcode=A_VCOMISD)) or
  2279. ((taicpu(p).opcode=A_VMOVAPS) and
  2280. ((taicpu(hp1).opcode=A_VCOMISS))
  2281. )
  2282. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2283. { change
  2284. movapX reg,reg1
  2285. vcomisX reg1,reg1
  2286. to
  2287. vcomisX reg,reg
  2288. }
  2289. begin
  2290. TransferUsedRegs(TmpUsedRegs);
  2291. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2292. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2293. begin
  2294. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2295. debug_op2str(taicpu(p).opcode)+' '+
  2296. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2297. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2298. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2299. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2300. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2301. RemoveCurrentP(p);
  2302. result:=true;
  2303. exit;
  2304. end;
  2305. end
  2306. end;
  2307. end;
  2308. end;
  2309. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2310. var
  2311. hp1 : tai;
  2312. begin
  2313. result:=false;
  2314. { replace
  2315. V<Op>X %mreg1,%mreg2,%mreg3
  2316. VMovX %mreg3,%mreg4
  2317. dealloc %mreg3
  2318. by
  2319. V<Op>X %mreg1,%mreg2,%mreg4
  2320. ?
  2321. }
  2322. if GetNextInstruction(p,hp1) and
  2323. { we mix single and double operations here because we assume that the compiler
  2324. generates vmovapd only after double operations and vmovaps only after single operations }
  2325. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2326. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2327. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2328. begin
  2329. TransferUsedRegs(TmpUsedRegs);
  2330. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2331. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2332. begin
  2333. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2334. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2335. RemoveInstruction(hp1);
  2336. result:=true;
  2337. end;
  2338. end;
  2339. end;
  2340. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2341. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2342. begin
  2343. Result := False;
  2344. { For safety reasons, only check for exact register matches }
  2345. { Check base register }
  2346. if (ref.base = AOldReg) then
  2347. begin
  2348. ref.base := ANewReg;
  2349. Result := True;
  2350. end;
  2351. { Check index register }
  2352. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2353. begin
  2354. ref.index := ANewReg;
  2355. Result := True;
  2356. end;
  2357. end;
  2358. { Replaces all references to AOldReg in an operand to ANewReg }
  2359. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2360. var
  2361. OldSupReg, NewSupReg: TSuperRegister;
  2362. OldSubReg, NewSubReg: TSubRegister;
  2363. OldRegType: TRegisterType;
  2364. ThisOper: POper;
  2365. begin
  2366. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2367. Result := False;
  2368. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2369. InternalError(2020011801);
  2370. OldSupReg := getsupreg(AOldReg);
  2371. OldSubReg := getsubreg(AOldReg);
  2372. OldRegType := getregtype(AOldReg);
  2373. NewSupReg := getsupreg(ANewReg);
  2374. NewSubReg := getsubreg(ANewReg);
  2375. if OldRegType <> getregtype(ANewReg) then
  2376. InternalError(2020011802);
  2377. if OldSubReg <> NewSubReg then
  2378. InternalError(2020011803);
  2379. case ThisOper^.typ of
  2380. top_reg:
  2381. if (
  2382. (ThisOper^.reg = AOldReg) or
  2383. (
  2384. (OldRegType = R_INTREGISTER) and
  2385. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2386. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2387. (
  2388. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2389. {$ifndef x86_64}
  2390. and (
  2391. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2392. don't have an 8-bit representation }
  2393. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2394. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2395. )
  2396. {$endif x86_64}
  2397. )
  2398. )
  2399. ) then
  2400. begin
  2401. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2402. Result := True;
  2403. end;
  2404. top_ref:
  2405. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2406. Result := True;
  2407. else
  2408. ;
  2409. end;
  2410. end;
  2411. { Replaces all references to AOldReg in an instruction to ANewReg }
  2412. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2413. const
  2414. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2415. var
  2416. OperIdx: Integer;
  2417. begin
  2418. Result := False;
  2419. for OperIdx := 0 to p.ops - 1 do
  2420. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2421. begin
  2422. { The shift and rotate instructions can only use CL }
  2423. if not (
  2424. (OperIdx = 0) and
  2425. { This second condition just helps to avoid unnecessarily
  2426. calling MatchInstruction for 10 different opcodes }
  2427. (p.oper[0]^.reg = NR_CL) and
  2428. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2429. ) then
  2430. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2431. end
  2432. else if p.oper[OperIdx]^.typ = top_ref then
  2433. { It's okay to replace registers in references that get written to }
  2434. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2435. end;
  2436. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2437. begin
  2438. Result :=
  2439. (ref^.index = NR_NO) and
  2440. (
  2441. {$ifdef x86_64}
  2442. (
  2443. (ref^.base = NR_RIP) and
  2444. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2445. ) or
  2446. {$endif x86_64}
  2447. (ref^.refaddr = addr_full) or
  2448. (ref^.base = NR_STACK_POINTER_REG) or
  2449. (ref^.base = current_procinfo.framepointer)
  2450. );
  2451. end;
  2452. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2453. var
  2454. l: asizeint;
  2455. begin
  2456. Result := False;
  2457. { Should have been checked previously }
  2458. if p.opcode <> A_LEA then
  2459. InternalError(2020072501);
  2460. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2461. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2462. not(cs_opt_size in current_settings.optimizerswitches) then
  2463. exit;
  2464. with p.oper[0]^.ref^ do
  2465. begin
  2466. if (base <> p.oper[1]^.reg) or
  2467. (index <> NR_NO) or
  2468. assigned(symbol) then
  2469. exit;
  2470. l:=offset;
  2471. if (l=1) and UseIncDec then
  2472. begin
  2473. p.opcode:=A_INC;
  2474. p.loadreg(0,p.oper[1]^.reg);
  2475. p.ops:=1;
  2476. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2477. end
  2478. else if (l=-1) and UseIncDec then
  2479. begin
  2480. p.opcode:=A_DEC;
  2481. p.loadreg(0,p.oper[1]^.reg);
  2482. p.ops:=1;
  2483. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2484. end
  2485. else
  2486. begin
  2487. if (l<0) and (l<>-2147483648) then
  2488. begin
  2489. p.opcode:=A_SUB;
  2490. p.loadConst(0,-l);
  2491. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2492. end
  2493. else
  2494. begin
  2495. p.opcode:=A_ADD;
  2496. p.loadConst(0,l);
  2497. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2498. end;
  2499. end;
  2500. end;
  2501. Result := True;
  2502. end;
  2503. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2504. var
  2505. CurrentReg, ReplaceReg: TRegister;
  2506. begin
  2507. Result := False;
  2508. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2509. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2510. case hp.opcode of
  2511. A_FSTSW, A_FNSTSW,
  2512. A_IN, A_INS, A_OUT, A_OUTS,
  2513. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2514. { These routines have explicit operands, but they are restricted in
  2515. what they can be (e.g. IN and OUT can only read from AL, AX or
  2516. EAX. }
  2517. Exit;
  2518. A_IMUL:
  2519. begin
  2520. { The 1-operand version writes to implicit registers
  2521. The 2-operand version reads from the first operator, and reads
  2522. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2523. the 3-operand version reads from a register that it doesn't write to
  2524. }
  2525. case hp.ops of
  2526. 1:
  2527. if (
  2528. (
  2529. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2530. ) or
  2531. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2532. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2533. begin
  2534. Result := True;
  2535. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2536. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2537. end;
  2538. 2:
  2539. { Only modify the first parameter }
  2540. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2541. begin
  2542. Result := True;
  2543. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2544. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2545. end;
  2546. 3:
  2547. { Only modify the second parameter }
  2548. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2549. begin
  2550. Result := True;
  2551. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2552. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2553. end;
  2554. else
  2555. InternalError(2020012901);
  2556. end;
  2557. end;
  2558. else
  2559. if (hp.ops > 0) and
  2560. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2561. begin
  2562. Result := True;
  2563. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2564. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2565. end;
  2566. end;
  2567. end;
  2568. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2569. var
  2570. hp2: tai;
  2571. p_SourceReg, p_TargetReg: TRegister;
  2572. begin
  2573. Result := False;
  2574. { Backward optimisation. If we have:
  2575. func. %reg1,%reg2
  2576. mov %reg2,%reg3
  2577. (dealloc %reg2)
  2578. Change to:
  2579. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2580. Perform similar optimisations with 1, 3 and 4-operand instructions
  2581. that only have one output.
  2582. }
  2583. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2584. begin
  2585. p_SourceReg := taicpu(p).oper[0]^.reg;
  2586. p_TargetReg := taicpu(p).oper[1]^.reg;
  2587. TransferUsedRegs(TmpUsedRegs);
  2588. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2589. GetLastInstruction(p, hp2) and
  2590. (hp2.typ = ait_instruction) and
  2591. { Have to make sure it's an instruction that only reads from
  2592. the first operands and only writes (not reads or modifies) to
  2593. the last one; in essence, a pure function such as BSR, POPCNT
  2594. or ANDN }
  2595. (
  2596. (
  2597. (taicpu(hp2).ops = 1) and
  2598. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2599. ) or
  2600. (
  2601. (taicpu(hp2).ops = 2) and
  2602. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2603. ) or
  2604. (
  2605. (taicpu(hp2).ops = 3) and
  2606. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2607. ) or
  2608. (
  2609. (taicpu(hp2).ops = 4) and
  2610. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2611. )
  2612. ) and
  2613. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2614. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2615. begin
  2616. case taicpu(hp2).opcode of
  2617. A_FSTSW, A_FNSTSW,
  2618. A_IN, A_INS, A_OUT, A_OUTS,
  2619. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2620. { These routines have explicit operands, but they are restricted in
  2621. what they can be (e.g. IN and OUT can only read from AL, AX or
  2622. EAX. }
  2623. ;
  2624. else
  2625. begin
  2626. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2627. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2628. if not RegInInstruction(p_TargetReg, hp2) then
  2629. begin
  2630. { Since we're allocating from an earlier point, we
  2631. need to remove the register from the tracking }
  2632. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2633. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2634. end;
  2635. RemoveCurrentp(p, hp1);
  2636. { If the Func was another MOV instruction, we might get
  2637. "mov %reg,%reg" that doesn't get removed in Pass 2
  2638. otherwise, so deal with it here (also do something
  2639. similar with lea (%reg),%reg}
  2640. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2641. begin
  2642. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2643. if p = hp2 then
  2644. RemoveCurrentp(p)
  2645. else
  2646. RemoveInstruction(hp2);
  2647. end;
  2648. Result := True;
  2649. Exit;
  2650. end;
  2651. end;
  2652. end;
  2653. end;
  2654. end;
  2655. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2656. begin
  2657. Result := False;
  2658. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2659. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2660. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2661. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2662. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2663. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2664. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2665. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2666. begin
  2667. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2668. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2669. Result := True;
  2670. end;
  2671. end;
  2672. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2673. var
  2674. hp1, hp2, hp3, hp4: tai;
  2675. DoOptimisation, TempBool: Boolean;
  2676. {$ifdef x86_64}
  2677. NewConst: TCGInt;
  2678. {$endif x86_64}
  2679. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2680. begin
  2681. if taicpu(hp1).opcode = signed_movop then
  2682. begin
  2683. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2684. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2685. end
  2686. else
  2687. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2688. end;
  2689. function TryConstMerge(var p1, p2: tai): Boolean;
  2690. var
  2691. ThisRef: TReference;
  2692. begin
  2693. Result := False;
  2694. ThisRef := taicpu(p2).oper[1]^.ref^;
  2695. { Only permit writes to the stack, since we can guarantee alignment with that }
  2696. if (ThisRef.index = NR_NO) and
  2697. (
  2698. (ThisRef.base = NR_STACK_POINTER_REG) or
  2699. (ThisRef.base = current_procinfo.framepointer)
  2700. ) then
  2701. begin
  2702. case taicpu(p).opsize of
  2703. S_B:
  2704. begin
  2705. { Word writes must be on a 2-byte boundary }
  2706. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2707. begin
  2708. { Reduce offset of second reference to see if it is sequential with the first }
  2709. Dec(ThisRef.offset, 1);
  2710. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2711. begin
  2712. { Make sure the constants aren't represented as a
  2713. negative number, as these won't merge properly }
  2714. taicpu(p1).opsize := S_W;
  2715. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2716. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2717. RemoveInstruction(p2);
  2718. Result := True;
  2719. end;
  2720. end;
  2721. end;
  2722. S_W:
  2723. begin
  2724. { Longword writes must be on a 4-byte boundary }
  2725. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2726. begin
  2727. { Reduce offset of second reference to see if it is sequential with the first }
  2728. Dec(ThisRef.offset, 2);
  2729. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2730. begin
  2731. { Make sure the constants aren't represented as a
  2732. negative number, as these won't merge properly }
  2733. taicpu(p1).opsize := S_L;
  2734. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2735. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2736. RemoveInstruction(p2);
  2737. Result := True;
  2738. end;
  2739. end;
  2740. end;
  2741. {$ifdef x86_64}
  2742. S_L:
  2743. begin
  2744. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2745. see if the constants can be encoded this way. }
  2746. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2747. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2748. { Quadword writes must be on an 8-byte boundary }
  2749. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2750. begin
  2751. { Reduce offset of second reference to see if it is sequential with the first }
  2752. Dec(ThisRef.offset, 4);
  2753. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2754. begin
  2755. { Make sure the constants aren't represented as a
  2756. negative number, as these won't merge properly }
  2757. taicpu(p1).opsize := S_Q;
  2758. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2759. taicpu(p1).oper[0]^.val := NewConst;
  2760. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2761. RemoveInstruction(p2);
  2762. Result := True;
  2763. end;
  2764. end;
  2765. end;
  2766. {$endif x86_64}
  2767. else
  2768. ;
  2769. end;
  2770. end;
  2771. end;
  2772. var
  2773. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2774. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2775. NewSize: topsize; NewOffset: asizeint;
  2776. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2777. SourceRef, TargetRef: TReference;
  2778. MovAligned, MovUnaligned: TAsmOp;
  2779. ThisRef: TReference;
  2780. JumpTracking: TLinkedList;
  2781. begin
  2782. Result:=false;
  2783. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2784. { remove mov reg1,reg1? }
  2785. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2786. then
  2787. begin
  2788. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2789. { take care of the register (de)allocs following p }
  2790. RemoveCurrentP(p, hp1);
  2791. Result:=true;
  2792. exit;
  2793. end;
  2794. { All the next optimisations require a next instruction }
  2795. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2796. Exit;
  2797. { Prevent compiler warnings }
  2798. p_TargetReg := NR_NO;
  2799. if taicpu(p).oper[1]^.typ = top_reg then
  2800. begin
  2801. { Saves on a large number of dereferences }
  2802. p_TargetReg := taicpu(p).oper[1]^.reg;
  2803. { Look for:
  2804. mov %reg1,%reg2
  2805. ??? %reg2,r/m
  2806. Change to:
  2807. mov %reg1,%reg2
  2808. ??? %reg1,r/m
  2809. }
  2810. if taicpu(p).oper[0]^.typ = top_reg then
  2811. begin
  2812. if RegReadByInstruction(p_TargetReg, hp1) and
  2813. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2814. begin
  2815. { A change has occurred, just not in p }
  2816. Result := True;
  2817. TransferUsedRegs(TmpUsedRegs);
  2818. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2819. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2820. { Just in case something didn't get modified (e.g. an
  2821. implicit register) }
  2822. not RegReadByInstruction(p_TargetReg, hp1) then
  2823. begin
  2824. { We can remove the original MOV }
  2825. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2826. RemoveCurrentp(p, hp1);
  2827. { UsedRegs got updated by RemoveCurrentp }
  2828. Result := True;
  2829. Exit;
  2830. end;
  2831. { If we know a MOV instruction has become a null operation, we might as well
  2832. get rid of it now to save time. }
  2833. if (taicpu(hp1).opcode = A_MOV) and
  2834. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2835. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2836. { Just being a register is enough to confirm it's a null operation }
  2837. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2838. begin
  2839. Result := True;
  2840. { Speed-up to reduce a pipeline stall... if we had something like...
  2841. movl %eax,%edx
  2842. movw %dx,%ax
  2843. ... the second instruction would change to movw %ax,%ax, but
  2844. given that it is now %ax that's active rather than %eax,
  2845. penalties might occur due to a partial register write, so instead,
  2846. change it to a MOVZX instruction when optimising for speed.
  2847. }
  2848. if not (cs_opt_size in current_settings.optimizerswitches) and
  2849. IsMOVZXAcceptable and
  2850. (taicpu(hp1).opsize < taicpu(p).opsize)
  2851. {$ifdef x86_64}
  2852. { operations already implicitly set the upper 64 bits to zero }
  2853. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2854. {$endif x86_64}
  2855. then
  2856. begin
  2857. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2858. case taicpu(p).opsize of
  2859. S_W:
  2860. if taicpu(hp1).opsize = S_B then
  2861. taicpu(hp1).opsize := S_BL
  2862. else
  2863. InternalError(2020012911);
  2864. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2865. case taicpu(hp1).opsize of
  2866. S_B:
  2867. taicpu(hp1).opsize := S_BL;
  2868. S_W:
  2869. taicpu(hp1).opsize := S_WL;
  2870. else
  2871. InternalError(2020012912);
  2872. end;
  2873. else
  2874. InternalError(2020012910);
  2875. end;
  2876. taicpu(hp1).opcode := A_MOVZX;
  2877. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2878. end
  2879. else
  2880. begin
  2881. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2882. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2883. RemoveInstruction(hp1);
  2884. { The instruction after what was hp1 is now the immediate next instruction,
  2885. so we can continue to make optimisations if it's present }
  2886. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2887. Exit;
  2888. hp1 := hp2;
  2889. end;
  2890. end;
  2891. end;
  2892. end;
  2893. end;
  2894. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2895. overwrites the original destination register. e.g.
  2896. movl ###,%reg2d
  2897. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2898. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2899. }
  2900. if (taicpu(p).oper[1]^.typ = top_reg) and
  2901. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2902. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2903. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2904. begin
  2905. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2906. begin
  2907. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2908. case taicpu(p).oper[0]^.typ of
  2909. top_const:
  2910. { We have something like:
  2911. movb $x, %regb
  2912. movzbl %regb,%regd
  2913. Change to:
  2914. movl $x, %regd
  2915. }
  2916. begin
  2917. case taicpu(hp1).opsize of
  2918. S_BW:
  2919. begin
  2920. convert_mov_value(A_MOVSX, $FF);
  2921. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2922. taicpu(p).opsize := S_W;
  2923. end;
  2924. S_BL:
  2925. begin
  2926. convert_mov_value(A_MOVSX, $FF);
  2927. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2928. taicpu(p).opsize := S_L;
  2929. end;
  2930. S_WL:
  2931. begin
  2932. convert_mov_value(A_MOVSX, $FFFF);
  2933. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2934. taicpu(p).opsize := S_L;
  2935. end;
  2936. {$ifdef x86_64}
  2937. S_BQ:
  2938. begin
  2939. convert_mov_value(A_MOVSX, $FF);
  2940. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2941. taicpu(p).opsize := S_Q;
  2942. end;
  2943. S_WQ:
  2944. begin
  2945. convert_mov_value(A_MOVSX, $FFFF);
  2946. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2947. taicpu(p).opsize := S_Q;
  2948. end;
  2949. S_LQ:
  2950. begin
  2951. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2952. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2953. taicpu(p).opsize := S_Q;
  2954. end;
  2955. {$endif x86_64}
  2956. else
  2957. { If hp1 was a MOV instruction, it should have been
  2958. optimised already }
  2959. InternalError(2020021001);
  2960. end;
  2961. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2962. RemoveInstruction(hp1);
  2963. Result := True;
  2964. Exit;
  2965. end;
  2966. top_ref:
  2967. begin
  2968. { We have something like:
  2969. movb mem, %regb
  2970. movzbl %regb,%regd
  2971. Change to:
  2972. movzbl mem, %regd
  2973. }
  2974. ThisRef := taicpu(p).oper[0]^.ref^;
  2975. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2976. begin
  2977. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2978. taicpu(hp1).loadref(0, ThisRef);
  2979. { Make sure any registers in the references are properly tracked }
  2980. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2981. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2982. if (ThisRef.index <> NR_NO) then
  2983. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2984. RemoveCurrentP(p, hp1);
  2985. Result := True;
  2986. Exit;
  2987. end;
  2988. end;
  2989. else
  2990. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2991. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2992. Exit;
  2993. end;
  2994. end
  2995. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2996. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2997. optimised }
  2998. else
  2999. begin
  3000. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3001. RemoveCurrentP(p, hp1);
  3002. Result := True;
  3003. Exit;
  3004. end;
  3005. end;
  3006. if (taicpu(hp1).opcode = A_AND) and
  3007. (taicpu(p).oper[1]^.typ = top_reg) and
  3008. MatchOpType(taicpu(hp1),top_const,top_reg) then
  3009. begin
  3010. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  3011. begin
  3012. case taicpu(p).opsize of
  3013. S_L:
  3014. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  3015. begin
  3016. { Optimize out:
  3017. mov x, %reg
  3018. and ffffffffh, %reg
  3019. }
  3020. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  3021. RemoveInstruction(hp1);
  3022. Result:=true;
  3023. exit;
  3024. end;
  3025. S_Q: { TODO: Confirm if this is even possible }
  3026. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  3027. begin
  3028. { Optimize out:
  3029. mov x, %reg
  3030. and ffffffffffffffffh, %reg
  3031. }
  3032. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  3033. RemoveInstruction(hp1);
  3034. Result:=true;
  3035. exit;
  3036. end;
  3037. else
  3038. ;
  3039. end;
  3040. if (
  3041. (taicpu(p).oper[0]^.typ=top_reg) or
  3042. (
  3043. (taicpu(p).oper[0]^.typ=top_ref) and
  3044. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  3045. )
  3046. ) and
  3047. GetNextInstruction(hp1,hp2) and
  3048. MatchInstruction(hp2,A_TEST,[]) and
  3049. (
  3050. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3051. (
  3052. { If the register being tested is smaller than the one
  3053. that received a bitwise AND, permit it if the constant
  3054. fits into the smaller size }
  3055. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3056. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3057. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3058. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3059. (
  3060. (
  3061. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3062. (taicpu(hp1).oper[0]^.val <= $FF)
  3063. ) or
  3064. (
  3065. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3066. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3067. {$ifdef x86_64}
  3068. ) or
  3069. (
  3070. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3071. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3072. {$endif x86_64}
  3073. )
  3074. )
  3075. )
  3076. ) and
  3077. (
  3078. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3079. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3080. ) and
  3081. GetNextInstruction(hp2,hp3) and
  3082. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3083. (taicpu(hp3).condition in [C_E,C_NE]) then
  3084. begin
  3085. TransferUsedRegs(TmpUsedRegs);
  3086. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3087. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3088. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3089. begin
  3090. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3091. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3092. taicpu(hp1).opcode:=A_TEST;
  3093. { Shrink the TEST instruction down to the smallest possible size }
  3094. case taicpu(hp1).oper[0]^.val of
  3095. 0..255:
  3096. if (taicpu(hp1).opsize <> S_B)
  3097. {$ifndef x86_64}
  3098. and (
  3099. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3100. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3101. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3102. )
  3103. {$endif x86_64}
  3104. then
  3105. begin
  3106. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3107. { Only print debug message if the TEST instruction
  3108. is a different size before and after }
  3109. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3110. taicpu(hp1).opsize := S_B;
  3111. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3112. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3113. end;
  3114. 256..65535:
  3115. if (taicpu(hp1).opsize <> S_W) then
  3116. begin
  3117. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3118. { Only print debug message if the TEST instruction
  3119. is a different size before and after }
  3120. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3121. taicpu(hp1).opsize := S_W;
  3122. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3123. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3124. end;
  3125. {$ifdef x86_64}
  3126. 65536..$7FFFFFFF:
  3127. if (taicpu(hp1).opsize <> S_L) then
  3128. begin
  3129. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3130. { Only print debug message if the TEST instruction
  3131. is a different size before and after }
  3132. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3133. taicpu(hp1).opsize := S_L;
  3134. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3135. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3136. end;
  3137. {$endif x86_64}
  3138. else
  3139. ;
  3140. end;
  3141. RemoveInstruction(hp2);
  3142. RemoveCurrentP(p, hp1);
  3143. Result:=true;
  3144. exit;
  3145. end;
  3146. end;
  3147. end
  3148. else if IsMOVZXAcceptable and
  3149. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3150. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3151. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3152. then
  3153. begin
  3154. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3155. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3156. case taicpu(p).opsize of
  3157. S_B:
  3158. if (taicpu(hp1).oper[0]^.val = $ff) then
  3159. begin
  3160. { Convert:
  3161. movb x, %regl movb x, %regl
  3162. andw ffh, %regw andl ffh, %regd
  3163. To:
  3164. movzbw x, %regd movzbl x, %regd
  3165. (Identical registers, just different sizes)
  3166. }
  3167. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3168. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3169. case taicpu(hp1).opsize of
  3170. S_W: NewSize := S_BW;
  3171. S_L: NewSize := S_BL;
  3172. {$ifdef x86_64}
  3173. S_Q: NewSize := S_BQ;
  3174. {$endif x86_64}
  3175. else
  3176. InternalError(2018011510);
  3177. end;
  3178. end
  3179. else
  3180. NewSize := S_NO;
  3181. S_W:
  3182. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3183. begin
  3184. { Convert:
  3185. movw x, %regw
  3186. andl ffffh, %regd
  3187. To:
  3188. movzwl x, %regd
  3189. (Identical registers, just different sizes)
  3190. }
  3191. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3192. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3193. case taicpu(hp1).opsize of
  3194. S_L: NewSize := S_WL;
  3195. {$ifdef x86_64}
  3196. S_Q: NewSize := S_WQ;
  3197. {$endif x86_64}
  3198. else
  3199. InternalError(2018011511);
  3200. end;
  3201. end
  3202. else
  3203. NewSize := S_NO;
  3204. else
  3205. NewSize := S_NO;
  3206. end;
  3207. if NewSize <> S_NO then
  3208. begin
  3209. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3210. { The actual optimization }
  3211. taicpu(p).opcode := A_MOVZX;
  3212. taicpu(p).changeopsize(NewSize);
  3213. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3214. { Safeguard if "and" is followed by a conditional command }
  3215. TransferUsedRegs(TmpUsedRegs);
  3216. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3217. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3218. begin
  3219. { At this point, the "and" command is effectively equivalent to
  3220. "test %reg,%reg". This will be handled separately by the
  3221. Peephole Optimizer. [Kit] }
  3222. DebugMsg(SPeepholeOptimization + PreMessage +
  3223. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3224. end
  3225. else
  3226. begin
  3227. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3228. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3229. RemoveInstruction(hp1);
  3230. end;
  3231. Result := True;
  3232. Exit;
  3233. end;
  3234. end;
  3235. end;
  3236. if (taicpu(hp1).opcode = A_OR) and
  3237. (taicpu(p).oper[1]^.typ = top_reg) and
  3238. MatchOperand(taicpu(p).oper[0]^, 0) and
  3239. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3240. begin
  3241. { mov 0, %reg
  3242. or ###,%reg
  3243. Change to (only if the flags are not used):
  3244. mov ###,%reg
  3245. }
  3246. TransferUsedRegs(TmpUsedRegs);
  3247. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3248. DoOptimisation := True;
  3249. { Even if the flags are used, we might be able to do the optimisation
  3250. if the conditions are predictable }
  3251. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3252. begin
  3253. { Only perform if ### = %reg (the same register) or equal to 0,
  3254. so %reg is guaranteed to still have a value of zero }
  3255. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3256. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3257. begin
  3258. hp2 := hp1;
  3259. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3260. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3261. GetNextInstruction(hp2, hp3) do
  3262. begin
  3263. { Don't continue modifying if the flags state is getting changed }
  3264. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3265. Break;
  3266. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3267. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3268. begin
  3269. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3270. begin
  3271. { Condition is always true }
  3272. case taicpu(hp3).opcode of
  3273. A_Jcc:
  3274. begin
  3275. { Check for jump shortcuts before we destroy the condition }
  3276. hp4 := hp3;
  3277. DoJumpOptimizations(hp3, TempBool);
  3278. { Make sure hp3 hasn't changed }
  3279. if (hp4 = hp3) then
  3280. begin
  3281. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3282. MakeUnconditional(taicpu(hp3));
  3283. end;
  3284. Result := True;
  3285. end;
  3286. A_CMOVcc:
  3287. begin
  3288. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3289. taicpu(hp3).opcode := A_MOV;
  3290. taicpu(hp3).condition := C_None;
  3291. Result := True;
  3292. end;
  3293. A_SETcc:
  3294. begin
  3295. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3296. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3297. taicpu(hp3).opcode := A_MOV;
  3298. taicpu(hp3).ops := 2;
  3299. taicpu(hp3).condition := C_None;
  3300. taicpu(hp3).opsize := S_B;
  3301. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3302. taicpu(hp3).loadconst(0, 1);
  3303. Result := True;
  3304. end;
  3305. else
  3306. InternalError(2021090701);
  3307. end;
  3308. end
  3309. 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
  3310. begin
  3311. { Condition is always false }
  3312. case taicpu(hp3).opcode of
  3313. A_Jcc:
  3314. begin
  3315. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3316. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3317. RemoveInstruction(hp3);
  3318. Result := True;
  3319. { Since hp3 was deleted, hp2 must not be updated }
  3320. Continue;
  3321. end;
  3322. A_CMOVcc:
  3323. begin
  3324. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3325. RemoveInstruction(hp3);
  3326. Result := True;
  3327. { Since hp3 was deleted, hp2 must not be updated }
  3328. Continue;
  3329. end;
  3330. A_SETcc:
  3331. begin
  3332. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3333. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3334. taicpu(hp3).opcode := A_MOV;
  3335. taicpu(hp3).ops := 2;
  3336. taicpu(hp3).condition := C_None;
  3337. taicpu(hp3).opsize := S_B;
  3338. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3339. taicpu(hp3).loadconst(0, 0);
  3340. Result := True;
  3341. end;
  3342. else
  3343. InternalError(2021090702);
  3344. end;
  3345. end
  3346. else
  3347. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3348. DoOptimisation := False;
  3349. end;
  3350. hp2 := hp3;
  3351. end;
  3352. { Flags are still in use - don't optimise }
  3353. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3354. DoOptimisation := False;
  3355. end
  3356. else
  3357. DoOptimisation := False;
  3358. end;
  3359. if DoOptimisation then
  3360. begin
  3361. {$ifdef x86_64}
  3362. { OR only supports 32-bit sign-extended constants for 64-bit
  3363. instructions, so compensate for this if the constant is
  3364. encoded as a value greater than or equal to 2^31 }
  3365. if (taicpu(hp1).opsize = S_Q) and
  3366. (taicpu(hp1).oper[0]^.typ = top_const) and
  3367. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3368. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3369. {$endif x86_64}
  3370. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3371. taicpu(hp1).opcode := A_MOV;
  3372. RemoveCurrentP(p, hp1);
  3373. Result := True;
  3374. Exit;
  3375. end;
  3376. end;
  3377. { Next instruction is also a MOV ? }
  3378. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3379. begin
  3380. if MatchOpType(taicpu(p), top_const, top_ref) and
  3381. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3382. TryConstMerge(p, hp1) then
  3383. begin
  3384. Result := True;
  3385. { In case we have four byte writes in a row, check for 2 more
  3386. right now so we don't have to wait for another iteration of
  3387. pass 1
  3388. }
  3389. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3390. case taicpu(p).opsize of
  3391. S_W:
  3392. begin
  3393. if GetNextInstruction(p, hp1) and
  3394. MatchInstruction(hp1, A_MOV, [S_B]) and
  3395. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3396. GetNextInstruction(hp1, hp2) and
  3397. MatchInstruction(hp2, A_MOV, [S_B]) and
  3398. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3399. { Try to merge the two bytes }
  3400. TryConstMerge(hp1, hp2) then
  3401. { Now try to merge the two words (hp2 will get deleted) }
  3402. TryConstMerge(p, hp1);
  3403. end;
  3404. S_L:
  3405. begin
  3406. { Though this only really benefits x86_64 and not i386, it
  3407. gets a potential optimisation done faster and hence
  3408. reduces the number of times OptPass1MOV is entered }
  3409. if GetNextInstruction(p, hp1) and
  3410. MatchInstruction(hp1, A_MOV, [S_W]) and
  3411. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3412. GetNextInstruction(hp1, hp2) and
  3413. MatchInstruction(hp2, A_MOV, [S_W]) and
  3414. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3415. { Try to merge the two words }
  3416. TryConstMerge(hp1, hp2) then
  3417. { This will always fail on i386, so don't bother
  3418. calling it unless we're doing x86_64 }
  3419. {$ifdef x86_64}
  3420. { Now try to merge the two longwords (hp2 will get deleted) }
  3421. TryConstMerge(p, hp1)
  3422. {$endif x86_64}
  3423. ;
  3424. end;
  3425. else
  3426. ;
  3427. end;
  3428. Exit;
  3429. end;
  3430. if (taicpu(p).oper[1]^.typ = top_reg) and
  3431. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3432. begin
  3433. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3434. TransferUsedRegs(TmpUsedRegs);
  3435. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3436. { we have
  3437. mov x, %treg
  3438. mov %treg, y
  3439. }
  3440. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3441. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3442. { we've got
  3443. mov x, %treg
  3444. mov %treg, y
  3445. with %treg is not used after }
  3446. case taicpu(p).oper[0]^.typ Of
  3447. { top_reg is covered by DeepMOVOpt }
  3448. top_const:
  3449. begin
  3450. { change
  3451. mov const, %treg
  3452. mov %treg, y
  3453. to
  3454. mov const, y
  3455. }
  3456. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3457. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3458. begin
  3459. if taicpu(hp1).oper[1]^.typ=top_reg then
  3460. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3461. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3462. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3463. RemoveInstruction(hp1);
  3464. Result:=true;
  3465. Exit;
  3466. end;
  3467. end;
  3468. top_ref:
  3469. case taicpu(hp1).oper[1]^.typ of
  3470. top_reg:
  3471. begin
  3472. { change
  3473. mov mem, %treg
  3474. mov %treg, %reg
  3475. to
  3476. mov mem, %reg"
  3477. }
  3478. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3479. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3480. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3481. RemoveInstruction(hp1);
  3482. Result:=true;
  3483. Exit;
  3484. end;
  3485. top_ref:
  3486. begin
  3487. {$ifdef x86_64}
  3488. { Look for the following to simplify:
  3489. mov x(mem1), %reg
  3490. mov %reg, y(mem2)
  3491. mov x+8(mem1), %reg
  3492. mov %reg, y+8(mem2)
  3493. Change to:
  3494. movdqu x(mem1), %xmmreg
  3495. movdqu %xmmreg, y(mem2)
  3496. ...but only as long as the memory blocks don't overlap
  3497. }
  3498. SourceRef := taicpu(p).oper[0]^.ref^;
  3499. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3500. if (taicpu(p).opsize = S_Q) and
  3501. GetNextInstruction(hp1, hp2) and
  3502. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3503. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3504. begin
  3505. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3506. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3507. Inc(SourceRef.offset, 8);
  3508. if UseAVX then
  3509. begin
  3510. MovAligned := A_VMOVDQA;
  3511. MovUnaligned := A_VMOVDQU;
  3512. end
  3513. else
  3514. begin
  3515. MovAligned := A_MOVDQA;
  3516. MovUnaligned := A_MOVDQU;
  3517. end;
  3518. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3519. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3520. begin
  3521. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3522. Inc(TargetRef.offset, 8);
  3523. if GetNextInstruction(hp2, hp3) and
  3524. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3525. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3526. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3527. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3528. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3529. begin
  3530. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3531. if NewMMReg <> NR_NO then
  3532. begin
  3533. { Remember that the offsets are 8 ahead }
  3534. if ((SourceRef.offset mod 16) = 8) and
  3535. (
  3536. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3537. (SourceRef.base = current_procinfo.framepointer) or
  3538. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3539. ) then
  3540. taicpu(p).opcode := MovAligned
  3541. else
  3542. taicpu(p).opcode := MovUnaligned;
  3543. taicpu(p).opsize := S_XMM;
  3544. taicpu(p).oper[1]^.reg := NewMMReg;
  3545. if ((TargetRef.offset mod 16) = 8) and
  3546. (
  3547. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3548. (TargetRef.base = current_procinfo.framepointer) or
  3549. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3550. ) then
  3551. taicpu(hp1).opcode := MovAligned
  3552. else
  3553. taicpu(hp1).opcode := MovUnaligned;
  3554. taicpu(hp1).opsize := S_XMM;
  3555. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3556. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3557. RemoveInstruction(hp2);
  3558. RemoveInstruction(hp3);
  3559. Result := True;
  3560. Exit;
  3561. end;
  3562. end;
  3563. end
  3564. else
  3565. begin
  3566. { See if the next references are 8 less rather than 8 greater }
  3567. Dec(SourceRef.offset, 16); { -8 the other way }
  3568. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3569. begin
  3570. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3571. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3572. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3573. GetNextInstruction(hp2, hp3) and
  3574. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3575. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3576. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3577. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3578. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3579. begin
  3580. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3581. if NewMMReg <> NR_NO then
  3582. begin
  3583. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3584. if ((SourceRef.offset mod 16) = 0) and
  3585. (
  3586. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3587. (SourceRef.base = current_procinfo.framepointer) or
  3588. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3589. ) then
  3590. taicpu(hp2).opcode := MovAligned
  3591. else
  3592. taicpu(hp2).opcode := MovUnaligned;
  3593. taicpu(hp2).opsize := S_XMM;
  3594. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3595. if ((TargetRef.offset mod 16) = 0) and
  3596. (
  3597. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3598. (TargetRef.base = current_procinfo.framepointer) or
  3599. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3600. ) then
  3601. taicpu(hp3).opcode := MovAligned
  3602. else
  3603. taicpu(hp3).opcode := MovUnaligned;
  3604. taicpu(hp3).opsize := S_XMM;
  3605. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3606. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3607. RemoveInstruction(hp1);
  3608. RemoveCurrentP(p, hp2);
  3609. Result := True;
  3610. Exit;
  3611. end;
  3612. end;
  3613. end;
  3614. end;
  3615. end;
  3616. {$endif x86_64}
  3617. end;
  3618. else
  3619. { The write target should be a reg or a ref }
  3620. InternalError(2021091601);
  3621. end;
  3622. else
  3623. ;
  3624. end
  3625. else
  3626. { %treg is used afterwards, but all eventualities
  3627. other than the first MOV instruction being a constant
  3628. are covered by DeepMOVOpt, so only check for that }
  3629. if (taicpu(p).oper[0]^.typ = top_const) and
  3630. (
  3631. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3632. not (cs_opt_size in current_settings.optimizerswitches) or
  3633. (taicpu(hp1).opsize = S_B)
  3634. ) and
  3635. (
  3636. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3637. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3638. ) then
  3639. begin
  3640. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3641. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3642. end;
  3643. end;
  3644. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3645. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3646. { mov reg1, mem1 or mov mem1, reg1
  3647. mov mem2, reg2 mov reg2, mem2}
  3648. begin
  3649. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3650. { mov reg1, mem1 or mov mem1, reg1
  3651. mov mem2, reg1 mov reg2, mem1}
  3652. begin
  3653. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3654. { Removes the second statement from
  3655. mov reg1, mem1/reg2
  3656. mov mem1/reg2, reg1 }
  3657. begin
  3658. if taicpu(p).oper[0]^.typ=top_reg then
  3659. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3660. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3661. RemoveInstruction(hp1);
  3662. Result:=true;
  3663. exit;
  3664. end
  3665. else
  3666. begin
  3667. TransferUsedRegs(TmpUsedRegs);
  3668. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3669. if (taicpu(p).oper[1]^.typ = top_ref) and
  3670. { mov reg1, mem1
  3671. mov mem2, reg1 }
  3672. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3673. GetNextInstruction(hp1, hp2) and
  3674. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3675. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3676. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3677. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3678. { change to
  3679. mov reg1, mem1 mov reg1, mem1
  3680. mov mem2, reg1 cmp reg1, mem2
  3681. cmp mem1, reg1
  3682. }
  3683. begin
  3684. RemoveInstruction(hp2);
  3685. taicpu(hp1).opcode := A_CMP;
  3686. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3687. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3688. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3689. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3690. end;
  3691. end;
  3692. end
  3693. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3694. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3695. begin
  3696. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3697. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3698. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3699. end
  3700. else
  3701. begin
  3702. TransferUsedRegs(TmpUsedRegs);
  3703. if GetNextInstruction(hp1, hp2) and
  3704. MatchOpType(taicpu(p),top_ref,top_reg) and
  3705. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3706. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3707. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3708. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3709. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3710. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3711. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3712. { mov mem1, %reg1
  3713. mov %reg1, mem2
  3714. mov mem2, reg2
  3715. to:
  3716. mov mem1, reg2
  3717. mov reg2, mem2}
  3718. begin
  3719. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3720. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3721. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3722. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3723. RemoveInstruction(hp2);
  3724. Result := True;
  3725. end
  3726. {$ifdef i386}
  3727. { this is enabled for i386 only, as the rules to create the reg sets below
  3728. are too complicated for x86-64, so this makes this code too error prone
  3729. on x86-64
  3730. }
  3731. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3732. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3733. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3734. { mov mem1, reg1 mov mem1, reg1
  3735. mov reg1, mem2 mov reg1, mem2
  3736. mov mem2, reg2 mov mem2, reg1
  3737. to: to:
  3738. mov mem1, reg1 mov mem1, reg1
  3739. mov mem1, reg2 mov reg1, mem2
  3740. mov reg1, mem2
  3741. or (if mem1 depends on reg1
  3742. and/or if mem2 depends on reg2)
  3743. to:
  3744. mov mem1, reg1
  3745. mov reg1, mem2
  3746. mov reg1, reg2
  3747. }
  3748. begin
  3749. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3750. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3751. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3752. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3753. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3754. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3755. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3756. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3757. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3758. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3759. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3760. end
  3761. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3762. begin
  3763. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3764. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3765. end
  3766. else
  3767. begin
  3768. RemoveInstruction(hp2);
  3769. end
  3770. {$endif i386}
  3771. ;
  3772. end;
  3773. end
  3774. { movl [mem1],reg1
  3775. movl [mem1],reg2
  3776. to
  3777. movl [mem1],reg1
  3778. movl reg1,reg2
  3779. }
  3780. else if not CheckMovMov2MovMov2(p, hp1) and
  3781. { movl const1,[mem1]
  3782. movl [mem1],reg1
  3783. to
  3784. movl const1,reg1
  3785. movl reg1,[mem1]
  3786. }
  3787. MatchOpType(Taicpu(p),top_const,top_ref) and
  3788. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3789. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3790. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3791. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3792. begin
  3793. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3794. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3795. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3796. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3797. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3798. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3799. Result:=true;
  3800. exit;
  3801. end;
  3802. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3803. { Change:
  3804. movl %reg1,%reg2
  3805. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3806. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3807. To:
  3808. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3809. movl x(%reg1),%reg1
  3810. movl %reg1,%regX
  3811. }
  3812. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3813. begin
  3814. p_SourceReg := taicpu(p).oper[0]^.reg;
  3815. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3816. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3817. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3818. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3819. GetNextInstruction(hp1, hp2) and
  3820. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3821. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3822. begin
  3823. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3824. if RegInRef(p_TargetReg, SourceRef) and
  3825. { If %reg1 also appears in the second reference, then it will
  3826. not refer to the same memory block as the first reference }
  3827. not RegInRef(p_SourceReg, SourceRef) then
  3828. begin
  3829. { Check to see if the references match if %reg2 is changed to %reg1 }
  3830. if SourceRef.base = p_TargetReg then
  3831. SourceRef.base := p_SourceReg;
  3832. if SourceRef.index = p_TargetReg then
  3833. SourceRef.index := p_SourceReg;
  3834. { RefsEqual also checks to ensure both references are non-volatile }
  3835. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3836. begin
  3837. taicpu(hp2).loadreg(0, p_SourceReg);
  3838. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3839. Result := True;
  3840. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3841. begin
  3842. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3843. RemoveCurrentP(p, hp1);
  3844. Exit;
  3845. end
  3846. else
  3847. begin
  3848. { Check to see if %reg2 is no longer in use }
  3849. TransferUsedRegs(TmpUsedRegs);
  3850. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3851. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3852. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3853. begin
  3854. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3855. RemoveCurrentP(p, hp1);
  3856. Exit;
  3857. end;
  3858. end;
  3859. { If we reach this point, p and hp1 weren't actually modified,
  3860. so we can do a bit more work on this pass }
  3861. end;
  3862. end;
  3863. end;
  3864. end;
  3865. end;
  3866. {$ifdef x86_64}
  3867. { Change:
  3868. movl %reg1l,%reg2l
  3869. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3870. To:
  3871. movl %reg1l,%reg2l
  3872. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3873. If %reg1 = %reg3, convert to:
  3874. movl %reg1l,%reg2l
  3875. andl %reg1l,%reg1l
  3876. }
  3877. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3878. MatchOpType(taicpu(p), top_reg, top_reg) and
  3879. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3880. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3881. begin
  3882. TransferUsedRegs(TmpUsedRegs);
  3883. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3884. taicpu(hp1).opsize := S_L;
  3885. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3886. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3887. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3888. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3889. begin
  3890. { %reg1 = %reg3 }
  3891. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3892. taicpu(hp1).opcode := A_AND;
  3893. end
  3894. else
  3895. begin
  3896. { %reg1 <> %reg3 }
  3897. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3898. end;
  3899. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3900. begin
  3901. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3902. RemoveCurrentP(p, hp1);
  3903. Result := True;
  3904. Exit;
  3905. end
  3906. else
  3907. begin
  3908. { Initial instruction wasn't actually changed }
  3909. Include(OptsToCheck, aoc_ForceNewIteration);
  3910. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3911. appears below since %reg1 has technically changed }
  3912. if taicpu(hp1).opcode = A_AND then
  3913. Exit;
  3914. end;
  3915. end;
  3916. {$endif x86_64}
  3917. { search further than the next instruction for a mov (as long as it's not a jump) }
  3918. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3919. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3920. (taicpu(p).oper[1]^.typ = top_reg) and
  3921. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3922. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3923. begin
  3924. { we work with hp2 here, so hp1 can be still used later on when
  3925. checking for GetNextInstruction_p }
  3926. hp3 := hp1;
  3927. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3928. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3929. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3930. TransferUsedRegs(TmpUsedRegs);
  3931. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3932. if NotFirstIteration then
  3933. JumpTracking := TLinkedList.Create
  3934. else
  3935. JumpTracking := nil;
  3936. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3937. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3938. (hp2.typ=ait_instruction) do
  3939. begin
  3940. case taicpu(hp2).opcode of
  3941. A_POP:
  3942. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3943. begin
  3944. if not CrossJump and
  3945. not RegUsedBetween(p_TargetReg, p, hp2) then
  3946. begin
  3947. { We can remove the original MOV since the register
  3948. wasn't used between it and its popping from the stack }
  3949. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3950. RemoveCurrentp(p, hp1);
  3951. Result := True;
  3952. JumpTracking.Free;
  3953. Exit;
  3954. end;
  3955. { Can't go any further }
  3956. Break;
  3957. end;
  3958. A_MOV:
  3959. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3960. ((taicpu(p).oper[0]^.typ=top_const) or
  3961. ((taicpu(p).oper[0]^.typ=top_reg) and
  3962. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3963. )
  3964. ) then
  3965. begin
  3966. { we have
  3967. mov x, %treg
  3968. mov %treg, y
  3969. }
  3970. { We don't need to call UpdateUsedRegs for every instruction between
  3971. p and hp2 because the register we're concerned about will not
  3972. become deallocated (otherwise GetNextInstructionUsingReg would
  3973. have stopped at an earlier instruction). [Kit] }
  3974. TempRegUsed :=
  3975. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3976. RegReadByInstruction(p_TargetReg, hp3) or
  3977. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3978. case taicpu(p).oper[0]^.typ Of
  3979. top_reg:
  3980. begin
  3981. { change
  3982. mov %reg, %treg
  3983. mov %treg, y
  3984. to
  3985. mov %reg, y
  3986. }
  3987. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3988. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3989. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3990. begin
  3991. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3992. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3993. if TempRegUsed then
  3994. begin
  3995. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3996. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3997. { Set the start of the next GetNextInstructionUsingRegCond search
  3998. to start at the entry right before hp2 (which is about to be removed) }
  3999. hp3 := tai(hp2.Previous);
  4000. RemoveInstruction(hp2);
  4001. Include(OptsToCheck, aoc_ForceNewIteration);
  4002. { See if there's more we can optimise }
  4003. Continue;
  4004. end
  4005. else
  4006. begin
  4007. RemoveInstruction(hp2);
  4008. { We can remove the original MOV too }
  4009. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4010. RemoveCurrentP(p, hp1);
  4011. Result:=true;
  4012. JumpTracking.Free;
  4013. Exit;
  4014. end;
  4015. end
  4016. else
  4017. begin
  4018. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4019. taicpu(hp2).loadReg(0, p_SourceReg);
  4020. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4021. { Check to see if the register also appears in the reference }
  4022. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4023. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4024. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4025. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4026. begin
  4027. { Don't remove the first instruction if the temporary register is in use }
  4028. if not TempRegUsed then
  4029. begin
  4030. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4031. RemoveCurrentP(p, hp1);
  4032. Result:=true;
  4033. JumpTracking.Free;
  4034. Exit;
  4035. end;
  4036. { No need to set Result to True here. If there's another instruction later
  4037. on that can be optimised, it will be detected when the main Pass 1 loop
  4038. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4039. hp3 := hp2;
  4040. Continue;
  4041. end;
  4042. end;
  4043. end;
  4044. top_const:
  4045. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4046. begin
  4047. { change
  4048. mov const, %treg
  4049. mov %treg, y
  4050. to
  4051. mov const, y
  4052. }
  4053. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4054. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4055. begin
  4056. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4057. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4058. if TempRegUsed then
  4059. begin
  4060. { Don't remove the first instruction if the temporary register is in use }
  4061. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4062. { No need to set Result to True. If there's another instruction later on
  4063. that can be optimised, it will be detected when the main Pass 1 loop
  4064. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4065. end
  4066. else
  4067. begin
  4068. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4069. RemoveCurrentP(p, hp1);
  4070. Result:=true;
  4071. Exit;
  4072. end;
  4073. end;
  4074. end;
  4075. else
  4076. Internalerror(2019103001);
  4077. end;
  4078. end
  4079. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4080. begin
  4081. if not CrossJump and
  4082. not RegUsedBetween(p_TargetReg, p, hp2) and
  4083. not RegReadByInstruction(p_TargetReg, hp2) then
  4084. begin
  4085. { Register is not used before it is overwritten }
  4086. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4087. RemoveCurrentp(p, hp1);
  4088. Result := True;
  4089. Exit;
  4090. end;
  4091. if (taicpu(p).oper[0]^.typ = top_const) and
  4092. (taicpu(hp2).oper[0]^.typ = top_const) then
  4093. begin
  4094. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4095. begin
  4096. { Same value - register hasn't changed }
  4097. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4098. RemoveInstruction(hp2);
  4099. Include(OptsToCheck, aoc_ForceNewIteration);
  4100. { See if there's more we can optimise }
  4101. Continue;
  4102. end;
  4103. end;
  4104. {$ifdef x86_64}
  4105. end
  4106. { Change:
  4107. movl %reg1l,%reg2l
  4108. ...
  4109. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4110. To:
  4111. movl %reg1l,%reg2l
  4112. ...
  4113. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4114. If %reg1 = %reg3, convert to:
  4115. movl %reg1l,%reg2l
  4116. ...
  4117. andl %reg1l,%reg1l
  4118. }
  4119. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4120. (taicpu(p).oper[0]^.typ = top_reg) and
  4121. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4122. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4123. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4124. begin
  4125. TempRegUsed :=
  4126. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4127. RegReadByInstruction(p_TargetReg, hp3) or
  4128. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4129. taicpu(hp2).opsize := S_L;
  4130. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4131. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4132. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4133. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4134. begin
  4135. { %reg1 = %reg3 }
  4136. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4137. taicpu(hp2).opcode := A_AND;
  4138. end
  4139. else
  4140. begin
  4141. { %reg1 <> %reg3 }
  4142. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4143. end;
  4144. if not TempRegUsed then
  4145. begin
  4146. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4147. RemoveCurrentP(p, hp1);
  4148. Result := True;
  4149. Exit;
  4150. end
  4151. else
  4152. begin
  4153. { Initial instruction wasn't actually changed }
  4154. Include(OptsToCheck, aoc_ForceNewIteration);
  4155. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4156. appears below since %reg1 has technically changed }
  4157. if taicpu(hp2).opcode = A_AND then
  4158. Break;
  4159. end;
  4160. {$endif x86_64}
  4161. end
  4162. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4163. GetNextInstruction(hp2, hp4) and
  4164. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4165. { Optimise the following first:
  4166. movl [mem1],reg1
  4167. movl [mem1],reg2
  4168. to
  4169. movl [mem1],reg1
  4170. movl reg1,reg2
  4171. If [mem1] contains the target register and reg1 is the
  4172. the source register, this optimisation will get missed
  4173. and produce less efficient code later on.
  4174. }
  4175. if CheckMovMov2MovMov2(hp2, hp4) then
  4176. { Initial instruction wasn't actually changed }
  4177. Include(OptsToCheck, aoc_ForceNewIteration);
  4178. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4179. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4180. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4181. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4182. begin
  4183. {
  4184. Change from:
  4185. mov ###, %reg
  4186. ...
  4187. movs/z %reg,%reg (Same register, just different sizes)
  4188. To:
  4189. movs/z ###, %reg (Longer version)
  4190. ...
  4191. (remove)
  4192. }
  4193. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4194. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4195. { Keep the first instruction as mov if ### is a constant }
  4196. if taicpu(p).oper[0]^.typ = top_const then
  4197. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4198. else
  4199. begin
  4200. taicpu(p).opcode := taicpu(hp2).opcode;
  4201. taicpu(p).opsize := taicpu(hp2).opsize;
  4202. end;
  4203. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4204. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4205. RemoveInstruction(hp2);
  4206. Result := True;
  4207. JumpTracking.Free;
  4208. Exit;
  4209. end;
  4210. else
  4211. { Move down to the if-block below };
  4212. end;
  4213. { Also catches MOV/S/Z instructions that aren't modified }
  4214. if taicpu(p).oper[0]^.typ = top_reg then
  4215. begin
  4216. p_SourceReg := taicpu(p).oper[0]^.reg;
  4217. if
  4218. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4219. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4220. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4221. begin
  4222. Result := True;
  4223. { Just in case something didn't get modified (e.g. an
  4224. implicit register). Also, if it does read from this
  4225. register, then there's no longer an advantage to
  4226. changing the register on subsequent instructions.}
  4227. if not RegReadByInstruction(p_TargetReg, hp2) then
  4228. begin
  4229. { If a conditional jump was crossed, do not delete
  4230. the original MOV no matter what }
  4231. if not CrossJump and
  4232. { RegEndOfLife returns True if the register is
  4233. deallocated before the next instruction or has
  4234. been loaded with a new value }
  4235. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4236. begin
  4237. { We can remove the original MOV }
  4238. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4239. RemoveCurrentp(p, hp1);
  4240. JumpTracking.Free;
  4241. Result := True;
  4242. Exit;
  4243. end;
  4244. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4245. begin
  4246. { See if there's more we can optimise }
  4247. hp3 := hp2;
  4248. Continue;
  4249. end;
  4250. end;
  4251. end;
  4252. end;
  4253. { Break out of the while loop under normal circumstances }
  4254. Break;
  4255. end;
  4256. JumpTracking.Free;
  4257. end;
  4258. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4259. (taicpu(p).oper[1]^.typ = top_reg) and
  4260. (taicpu(p).opsize = S_L) and
  4261. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4262. (hp2.typ = ait_instruction) and
  4263. (taicpu(hp2).opcode = A_AND) and
  4264. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4265. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4266. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4267. ) then
  4268. begin
  4269. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4270. begin
  4271. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4272. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4273. begin
  4274. { Optimize out:
  4275. mov x, %reg
  4276. and ffffffffh, %reg
  4277. }
  4278. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4279. RemoveInstruction(hp2);
  4280. Result:=true;
  4281. exit;
  4282. end;
  4283. end;
  4284. end;
  4285. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4286. x >= RetOffset) as it doesn't do anything (it writes either to a
  4287. parameter or to the temporary storage room for the function
  4288. result)
  4289. }
  4290. if IsExitCode(hp1) and
  4291. (taicpu(p).oper[1]^.typ = top_ref) and
  4292. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4293. (
  4294. (
  4295. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4296. not (
  4297. assigned(current_procinfo.procdef.funcretsym) and
  4298. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4299. )
  4300. ) or
  4301. { Also discard writes to the stack that are below the base pointer,
  4302. as this is temporary storage rather than a function result on the
  4303. stack, say. }
  4304. (
  4305. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4306. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4307. )
  4308. ) then
  4309. begin
  4310. RemoveCurrentp(p, hp1);
  4311. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4312. RemoveLastDeallocForFuncRes(p);
  4313. Result:=true;
  4314. exit;
  4315. end;
  4316. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4317. begin
  4318. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4319. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4320. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4321. begin
  4322. { change
  4323. mov reg1, mem1
  4324. test/cmp x, mem1
  4325. to
  4326. mov reg1, mem1
  4327. test/cmp x, reg1
  4328. }
  4329. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4330. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4331. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4332. Result := True;
  4333. Exit;
  4334. end;
  4335. if DoMovCmpMemOpt(p, hp1) then
  4336. begin
  4337. Result := True;
  4338. Exit;
  4339. end;
  4340. end;
  4341. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4342. { If the flags register is in use, don't change the instruction to an
  4343. ADD otherwise this will scramble the flags. [Kit] }
  4344. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4345. begin
  4346. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4347. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4348. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4349. ) or
  4350. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4351. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4352. )
  4353. ) then
  4354. { mov reg1,ref
  4355. lea reg2,[reg1,reg2]
  4356. to
  4357. add reg2,ref}
  4358. begin
  4359. TransferUsedRegs(TmpUsedRegs);
  4360. { reg1 may not be used afterwards }
  4361. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4362. begin
  4363. Taicpu(hp1).opcode:=A_ADD;
  4364. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4365. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4366. RemoveCurrentp(p, hp1);
  4367. result:=true;
  4368. exit;
  4369. end;
  4370. end;
  4371. { If the LEA instruction can be converted into an arithmetic instruction,
  4372. it may be possible to then fold it in the next optimisation, otherwise
  4373. there's nothing more that can be optimised here. }
  4374. if not ConvertLEA(taicpu(hp1)) then
  4375. Exit;
  4376. end;
  4377. if (taicpu(p).oper[1]^.typ = top_reg) and
  4378. (hp1.typ = ait_instruction) and
  4379. GetNextInstruction(hp1, hp2) and
  4380. MatchInstruction(hp2,A_MOV,[]) and
  4381. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4382. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4383. (
  4384. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4385. {$ifdef x86_64}
  4386. or
  4387. (
  4388. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4389. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4390. )
  4391. {$endif x86_64}
  4392. ) then
  4393. begin
  4394. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4395. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4396. { change movsX/movzX reg/ref, reg2
  4397. add/sub/or/... reg3/$const, reg2
  4398. mov reg2 reg/ref
  4399. dealloc reg2
  4400. to
  4401. add/sub/or/... reg3/$const, reg/ref }
  4402. begin
  4403. TransferUsedRegs(TmpUsedRegs);
  4404. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4405. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4406. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4407. begin
  4408. { by example:
  4409. movswl %si,%eax movswl %si,%eax p
  4410. decl %eax addl %edx,%eax hp1
  4411. movw %ax,%si movw %ax,%si hp2
  4412. ->
  4413. movswl %si,%eax movswl %si,%eax p
  4414. decw %eax addw %edx,%eax hp1
  4415. movw %ax,%si movw %ax,%si hp2
  4416. }
  4417. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4418. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4419. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4420. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4421. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4422. {
  4423. ->
  4424. movswl %si,%eax movswl %si,%eax p
  4425. decw %si addw %dx,%si hp1
  4426. movw %ax,%si movw %ax,%si hp2
  4427. }
  4428. case taicpu(hp1).ops of
  4429. 1:
  4430. begin
  4431. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4432. if taicpu(hp1).oper[0]^.typ=top_reg then
  4433. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4434. end;
  4435. 2:
  4436. begin
  4437. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4438. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4439. (taicpu(hp1).opcode<>A_SHL) and
  4440. (taicpu(hp1).opcode<>A_SHR) and
  4441. (taicpu(hp1).opcode<>A_SAR) then
  4442. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4443. end;
  4444. else
  4445. internalerror(2008042701);
  4446. end;
  4447. {
  4448. ->
  4449. decw %si addw %dx,%si p
  4450. }
  4451. RemoveInstruction(hp2);
  4452. RemoveCurrentP(p, hp1);
  4453. Result:=True;
  4454. Exit;
  4455. end;
  4456. end;
  4457. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4458. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4459. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4460. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4461. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4462. )
  4463. {$ifdef i386}
  4464. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4465. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4466. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4467. {$endif i386}
  4468. then
  4469. { change movsX/movzX reg/ref, reg2
  4470. add/sub/or/... regX/$const, reg2
  4471. mov reg2, reg3
  4472. dealloc reg2
  4473. to
  4474. movsX/movzX reg/ref, reg3
  4475. add/sub/or/... reg3/$const, reg3
  4476. }
  4477. begin
  4478. TransferUsedRegs(TmpUsedRegs);
  4479. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4480. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4481. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4482. begin
  4483. { by example:
  4484. movswl %si,%eax movswl %si,%eax p
  4485. decl %eax addl %edx,%eax hp1
  4486. movw %ax,%si movw %ax,%si hp2
  4487. ->
  4488. movswl %si,%eax movswl %si,%eax p
  4489. decw %eax addw %edx,%eax hp1
  4490. movw %ax,%si movw %ax,%si hp2
  4491. }
  4492. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4493. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4494. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4495. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4496. { limit size of constants as well to avoid assembler errors, but
  4497. check opsize to avoid overflow when left shifting the 1 }
  4498. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4499. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4500. {$ifdef x86_64}
  4501. { Be careful of, for example:
  4502. movl %reg1,%reg2
  4503. addl %reg3,%reg2
  4504. movq %reg2,%reg4
  4505. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4506. }
  4507. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4508. begin
  4509. taicpu(hp2).changeopsize(S_L);
  4510. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4511. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4512. end;
  4513. {$endif x86_64}
  4514. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4515. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4516. if taicpu(p).oper[0]^.typ=top_reg then
  4517. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4518. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4519. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4520. {
  4521. ->
  4522. movswl %si,%eax movswl %si,%eax p
  4523. decw %si addw %dx,%si hp1
  4524. movw %ax,%si movw %ax,%si hp2
  4525. }
  4526. case taicpu(hp1).ops of
  4527. 1:
  4528. begin
  4529. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4530. if taicpu(hp1).oper[0]^.typ=top_reg then
  4531. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4532. end;
  4533. 2:
  4534. begin
  4535. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4536. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4537. (taicpu(hp1).opcode<>A_SHL) and
  4538. (taicpu(hp1).opcode<>A_SHR) and
  4539. (taicpu(hp1).opcode<>A_SAR) then
  4540. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4541. end;
  4542. else
  4543. internalerror(2018111801);
  4544. end;
  4545. {
  4546. ->
  4547. decw %si addw %dx,%si p
  4548. }
  4549. RemoveInstruction(hp2);
  4550. end;
  4551. end;
  4552. end;
  4553. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4554. GetNextInstruction(hp1, hp2) and
  4555. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4556. MatchOperand(Taicpu(p).oper[0]^,0) and
  4557. (Taicpu(p).oper[1]^.typ = top_reg) and
  4558. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4559. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4560. { mov reg1,0
  4561. bts reg1,operand1 --> mov reg1,operand2
  4562. or reg1,operand2 bts reg1,operand1}
  4563. begin
  4564. Taicpu(hp2).opcode:=A_MOV;
  4565. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4566. asml.remove(hp1);
  4567. insertllitem(hp2,hp2.next,hp1);
  4568. RemoveCurrentp(p, hp1);
  4569. Result:=true;
  4570. exit;
  4571. end;
  4572. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4573. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4574. GetNextInstruction(hp1, hp2) and
  4575. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4576. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4577. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4578. { change
  4579. mov reg1,reg2
  4580. sub reg3,reg2
  4581. cmp reg3,reg1
  4582. into
  4583. mov reg1,reg2
  4584. sub reg3,reg2
  4585. }
  4586. begin
  4587. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4588. RemoveInstruction(hp2);
  4589. Result:=true;
  4590. exit;
  4591. end;
  4592. {
  4593. mov ref,reg0
  4594. <op> reg0,reg1
  4595. dealloc reg0
  4596. to
  4597. <op> ref,reg1
  4598. }
  4599. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4600. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4601. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4602. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4603. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4604. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4605. begin
  4606. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4607. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4608. RemoveCurrentp(p, hp1);
  4609. Result:=true;
  4610. exit;
  4611. end;
  4612. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4613. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4614. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4615. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4616. begin
  4617. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4618. {$ifdef x86_64}
  4619. { Convert:
  4620. movq x(ref),%reg64
  4621. shrq y,%reg64
  4622. To:
  4623. movl x+4(ref),%reg32
  4624. shrl y-32,%reg32 (Remove if y = 32)
  4625. }
  4626. if (taicpu(p).opsize = S_Q) and
  4627. (taicpu(hp1).opcode = A_SHR) and
  4628. (taicpu(hp1).oper[0]^.val >= 32) then
  4629. begin
  4630. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4631. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4632. { Convert to 32-bit }
  4633. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4634. taicpu(p).opsize := S_L;
  4635. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4636. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4637. if (taicpu(hp1).oper[0]^.val = 32) then
  4638. begin
  4639. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4640. RemoveInstruction(hp1);
  4641. end
  4642. else
  4643. begin
  4644. { This will potentially open up more arithmetic operations since
  4645. the peephole optimizer now has a big hint that only the lower
  4646. 32 bits are currently in use (and opcodes are smaller in size) }
  4647. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4648. taicpu(hp1).opsize := S_L;
  4649. Dec(taicpu(hp1).oper[0]^.val, 32);
  4650. DebugMsg(SPeepholeOptimization + PreMessage +
  4651. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4652. end;
  4653. Result := True;
  4654. Exit;
  4655. end;
  4656. {$endif x86_64}
  4657. { Convert:
  4658. movl x(ref),%reg
  4659. shrl $24,%reg
  4660. To:
  4661. movzbl x+3(ref),%reg
  4662. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4663. Also accept sar instead of shr, but convert to movsx instead of movzx
  4664. }
  4665. if taicpu(hp1).opcode = A_SHR then
  4666. MovUnaligned := A_MOVZX
  4667. else
  4668. MovUnaligned := A_MOVSX;
  4669. NewSize := S_NO;
  4670. NewOffset := 0;
  4671. case taicpu(p).opsize of
  4672. S_B:
  4673. { No valid combinations };
  4674. S_W:
  4675. if (taicpu(hp1).oper[0]^.val = 8) then
  4676. begin
  4677. NewSize := S_BW;
  4678. NewOffset := 1;
  4679. end;
  4680. S_L:
  4681. case taicpu(hp1).oper[0]^.val of
  4682. 16:
  4683. begin
  4684. NewSize := S_WL;
  4685. NewOffset := 2;
  4686. end;
  4687. 24:
  4688. begin
  4689. NewSize := S_BL;
  4690. NewOffset := 3;
  4691. end;
  4692. else
  4693. ;
  4694. end;
  4695. {$ifdef x86_64}
  4696. S_Q:
  4697. case taicpu(hp1).oper[0]^.val of
  4698. 32:
  4699. begin
  4700. if taicpu(hp1).opcode = A_SAR then
  4701. begin
  4702. { 32-bit to 64-bit is a distinct instruction }
  4703. MovUnaligned := A_MOVSXD;
  4704. NewSize := S_LQ;
  4705. NewOffset := 4;
  4706. end
  4707. else
  4708. { Should have been handled by MovShr2Mov above }
  4709. InternalError(2022081811);
  4710. end;
  4711. 48:
  4712. begin
  4713. NewSize := S_WQ;
  4714. NewOffset := 6;
  4715. end;
  4716. 56:
  4717. begin
  4718. NewSize := S_BQ;
  4719. NewOffset := 7;
  4720. end;
  4721. else
  4722. ;
  4723. end;
  4724. {$endif x86_64}
  4725. else
  4726. InternalError(2022081810);
  4727. end;
  4728. if (NewSize <> S_NO) and
  4729. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4730. begin
  4731. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4732. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4733. debug_op2str(MovUnaligned);
  4734. {$ifdef x86_64}
  4735. if MovUnaligned <> A_MOVSXD then
  4736. { Don't add size suffix for MOVSXD }
  4737. {$endif x86_64}
  4738. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4739. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4740. taicpu(p).opcode := MovUnaligned;
  4741. taicpu(p).opsize := NewSize;
  4742. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4743. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4744. RemoveInstruction(hp1);
  4745. Result := True;
  4746. Exit;
  4747. end;
  4748. end;
  4749. { Backward optimisation shared with OptPass2MOV }
  4750. if FuncMov2Func(p, hp1) then
  4751. begin
  4752. Result := True;
  4753. Exit;
  4754. end;
  4755. end;
  4756. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4757. var
  4758. hp1 : tai;
  4759. begin
  4760. Result:=false;
  4761. if taicpu(p).ops <> 2 then
  4762. exit;
  4763. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4764. GetNextInstruction(p,hp1) then
  4765. begin
  4766. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4767. (taicpu(hp1).ops = 2) then
  4768. begin
  4769. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4770. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4771. { movXX reg1, mem1 or movXX mem1, reg1
  4772. movXX mem2, reg2 movXX reg2, mem2}
  4773. begin
  4774. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4775. { movXX reg1, mem1 or movXX mem1, reg1
  4776. movXX mem2, reg1 movXX reg2, mem1}
  4777. begin
  4778. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4779. begin
  4780. { Removes the second statement from
  4781. movXX reg1, mem1/reg2
  4782. movXX mem1/reg2, reg1
  4783. }
  4784. if taicpu(p).oper[0]^.typ=top_reg then
  4785. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4786. { Removes the second statement from
  4787. movXX mem1/reg1, reg2
  4788. movXX reg2, mem1/reg1
  4789. }
  4790. if (taicpu(p).oper[1]^.typ=top_reg) and
  4791. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4792. begin
  4793. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4794. RemoveInstruction(hp1);
  4795. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4796. Result:=true;
  4797. exit;
  4798. end
  4799. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4800. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4801. begin
  4802. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4803. RemoveInstruction(hp1);
  4804. Result:=true;
  4805. exit;
  4806. end;
  4807. end
  4808. end;
  4809. end;
  4810. end;
  4811. end;
  4812. end;
  4813. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4814. var
  4815. hp1 : tai;
  4816. begin
  4817. result:=false;
  4818. { replace
  4819. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4820. MovX %mreg2,%mreg1
  4821. dealloc %mreg2
  4822. by
  4823. <Op>X %mreg2,%mreg1
  4824. ?
  4825. }
  4826. if GetNextInstruction(p,hp1) and
  4827. { we mix single and double opperations here because we assume that the compiler
  4828. generates vmovapd only after double operations and vmovaps only after single operations }
  4829. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4830. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4831. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4832. (taicpu(p).oper[0]^.typ=top_reg) then
  4833. begin
  4834. TransferUsedRegs(TmpUsedRegs);
  4835. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4836. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4837. begin
  4838. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4839. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4840. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4841. RemoveInstruction(hp1);
  4842. result:=true;
  4843. end;
  4844. end;
  4845. end;
  4846. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4847. var
  4848. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4849. JumpLabel, JumpLabel_dist: TAsmLabel;
  4850. FirstValue, SecondValue: TCGInt;
  4851. function OptimizeJump(var InputP: tai): Boolean;
  4852. var
  4853. TempBool: Boolean;
  4854. begin
  4855. Result := False;
  4856. TempBool := True;
  4857. if DoJumpOptimizations(InputP, TempBool) or
  4858. not TempBool then
  4859. begin
  4860. Result := True;
  4861. if Assigned(InputP) then
  4862. begin
  4863. { CollapseZeroDistJump will be set to the label or an align
  4864. before it after the jump if it optimises, whether or not
  4865. the label is live or dead }
  4866. if (InputP.typ = ait_align) or
  4867. (
  4868. (InputP.typ = ait_label) and
  4869. not (tai_label(InputP).labsym.is_used)
  4870. ) then
  4871. GetNextInstruction(InputP, InputP);
  4872. end;
  4873. Exit;
  4874. end;
  4875. end;
  4876. begin
  4877. Result := False;
  4878. if (taicpu(p).oper[0]^.typ = top_const) and
  4879. (taicpu(p).oper[0]^.val <> -1) then
  4880. begin
  4881. { Convert unsigned maximum constants to -1 to aid optimisation }
  4882. case taicpu(p).opsize of
  4883. S_B:
  4884. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4885. begin
  4886. taicpu(p).oper[0]^.val := -1;
  4887. Result := True;
  4888. Exit;
  4889. end;
  4890. S_W:
  4891. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4892. begin
  4893. taicpu(p).oper[0]^.val := -1;
  4894. Result := True;
  4895. Exit;
  4896. end;
  4897. S_L:
  4898. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4899. begin
  4900. taicpu(p).oper[0]^.val := -1;
  4901. Result := True;
  4902. Exit;
  4903. end;
  4904. {$ifdef x86_64}
  4905. S_Q:
  4906. { Storing anything greater than $7FFFFFFF is not possible so do
  4907. nothing };
  4908. {$endif x86_64}
  4909. else
  4910. InternalError(2021121001);
  4911. end;
  4912. end;
  4913. if GetNextInstruction(p, hp1) and
  4914. TrySwapMovCmp(p, hp1) then
  4915. begin
  4916. Result := True;
  4917. Exit;
  4918. end;
  4919. p_label := nil;
  4920. JumpLabel := nil;
  4921. if MatchInstruction(hp1, A_Jcc, []) then
  4922. begin
  4923. if OptimizeJump(hp1) then
  4924. begin
  4925. Result := True;
  4926. if Assigned(hp1) then
  4927. begin
  4928. { CollapseZeroDistJump will be set to the label or an align
  4929. before it after the jump if it optimises, whether or not
  4930. the label is live or dead }
  4931. if (hp1.typ = ait_align) or
  4932. (
  4933. (hp1.typ = ait_label) and
  4934. not (tai_label(hp1).labsym.is_used)
  4935. ) then
  4936. GetNextInstruction(hp1, hp1);
  4937. end;
  4938. TransferUsedRegs(TmpUsedRegs);
  4939. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4940. if not Assigned(hp1) or
  4941. (
  4942. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4943. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4944. ) then
  4945. begin
  4946. { No more conditional jumps; conditional statement is no longer required }
  4947. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4948. RemoveCurrentP(p);
  4949. end;
  4950. Exit;
  4951. end;
  4952. if IsJumpToLabel(taicpu(hp1)) then
  4953. begin
  4954. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4955. if Assigned(JumpLabel) then
  4956. p_label := getlabelwithsym(JumpLabel);
  4957. end;
  4958. end;
  4959. { Search for:
  4960. test $x,(reg/ref)
  4961. jne @lbl1
  4962. test $y,(reg/ref) (same register or reference)
  4963. jne @lbl1
  4964. Change to:
  4965. test $(x or y),(reg/ref)
  4966. jne @lbl1
  4967. (Note, this doesn't work with je instead of jne)
  4968. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4969. Also search for:
  4970. test $x,(reg/ref)
  4971. je @lbl1
  4972. ...
  4973. test $y,(reg/ref)
  4974. je/jne @lbl2
  4975. If (x or y) = x, then the second jump is deterministic
  4976. }
  4977. if (
  4978. (
  4979. (taicpu(p).oper[0]^.typ = top_const) or
  4980. (
  4981. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4982. (taicpu(p).oper[0]^.typ = top_reg) and
  4983. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4984. )
  4985. ) and
  4986. MatchInstruction(hp1, A_JCC, [])
  4987. ) then
  4988. begin
  4989. if (taicpu(p).oper[0]^.typ = top_reg) and
  4990. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4991. FirstValue := -1
  4992. else
  4993. FirstValue := taicpu(p).oper[0]^.val;
  4994. { If we have several test/jne's in a row, it might be the case that
  4995. the second label doesn't go to the same location, but the one
  4996. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4997. so accommodate for this with a while loop.
  4998. }
  4999. hp1_last := hp1;
  5000. while (
  5001. (
  5002. (taicpu(p).oper[1]^.typ = top_reg) and
  5003. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5004. ) or GetNextInstruction(hp1_last, p_dist)
  5005. ) and (p_dist.typ = ait_instruction) do
  5006. begin
  5007. if (
  5008. (
  5009. (taicpu(p_dist).opcode = A_TEST) and
  5010. (
  5011. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5012. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5013. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5014. )
  5015. ) or
  5016. (
  5017. { cmp 0,%reg = test %reg,%reg }
  5018. (taicpu(p_dist).opcode = A_CMP) and
  5019. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5020. )
  5021. ) and
  5022. { Make sure the destination operands are actually the same }
  5023. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5024. GetNextInstruction(p_dist, hp1_dist) and
  5025. MatchInstruction(hp1_dist, A_JCC, []) then
  5026. begin
  5027. if OptimizeJump(hp1_dist) then
  5028. begin
  5029. Result := True;
  5030. Exit;
  5031. end;
  5032. if
  5033. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5034. (
  5035. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5036. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5037. ) then
  5038. SecondValue := -1
  5039. else
  5040. SecondValue := taicpu(p_dist).oper[0]^.val;
  5041. { If both of the TEST constants are identical, delete the
  5042. second TEST that is unnecessary (be careful though, just
  5043. in case the flags are modified in between) }
  5044. if (FirstValue = SecondValue) then
  5045. begin
  5046. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5047. begin
  5048. { Since the second jump's condition is a subset of the first, we
  5049. know it will never branch because the first jump dominates it.
  5050. Get it out of the way now rather than wait for the jump
  5051. optimisations for a speed boost. }
  5052. if IsJumpToLabel(taicpu(hp1_dist)) then
  5053. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5054. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5055. RemoveInstruction(hp1_dist);
  5056. Result := True;
  5057. end
  5058. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5059. begin
  5060. { If the inverse of the first condition is a subset of the second,
  5061. the second one will definitely branch if the first one doesn't }
  5062. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5063. { We can remove the TEST instruction too }
  5064. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5065. RemoveInstruction(p_dist);
  5066. MakeUnconditional(taicpu(hp1_dist));
  5067. RemoveDeadCodeAfterJump(hp1_dist);
  5068. { Since the jump is now unconditional, we can't
  5069. continue any further with this particular
  5070. optimisation. The original TEST is still intact
  5071. though, so there might be something else we can
  5072. do }
  5073. Include(OptsToCheck, aoc_ForceNewIteration);
  5074. Break;
  5075. end;
  5076. if Result or
  5077. { If a jump wasn't removed or made unconditional, only
  5078. remove the identical TEST instruction if the flags
  5079. weren't modified }
  5080. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5081. begin
  5082. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5083. RemoveInstruction(p_dist);
  5084. { If the jump was removed or made unconditional, we
  5085. don't need to allocate NR_DEFAULTFLAGS over the
  5086. entire range }
  5087. if not Result then
  5088. begin
  5089. { Mark the flags as 'in use' over the entire range }
  5090. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5091. { Speed gain - continue search from the Jcc instruction }
  5092. hp1_last := hp1_dist;
  5093. { Only the TEST instruction was removed, and the
  5094. original was unchanged, so we can safely do
  5095. another iteration of the while loop }
  5096. Include(OptsToCheck, aoc_ForceNewIteration);
  5097. Continue;
  5098. end;
  5099. Exit;
  5100. end;
  5101. end;
  5102. hp1_last := nil;
  5103. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5104. (
  5105. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5106. { Always adjacent under -O2 and under }
  5107. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5108. (
  5109. GetNextInstruction(hp1, hp1_last) and
  5110. (hp1_last = p_dist)
  5111. )
  5112. ) and
  5113. (
  5114. (
  5115. { Test the following variant:
  5116. test $x,(reg/ref)
  5117. jne @lbl1
  5118. test $y,(reg/ref)
  5119. je @lbl2
  5120. @lbl1:
  5121. Becomes:
  5122. test $(x or y),(reg/ref)
  5123. je @lbl2
  5124. @lbl1: (may become a dead label)
  5125. }
  5126. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5127. GetNextInstruction(hp1_dist, hp1_last) and
  5128. (hp1_last = p_label)
  5129. ) or
  5130. (
  5131. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5132. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5133. then the second jump will never branch, so it can also be
  5134. removed regardless of where it goes }
  5135. (
  5136. (FirstValue = -1) or
  5137. (SecondValue = -1) or
  5138. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5139. )
  5140. )
  5141. ) then
  5142. begin
  5143. { Same jump location... can be a register since nothing's changed }
  5144. { If any of the entries are equivalent to test %reg,%reg, then the
  5145. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5146. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5147. if (hp1_last = p_label) then
  5148. begin
  5149. { Variant }
  5150. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5151. RemoveInstruction(p_dist);
  5152. if Assigned(JumpLabel) then
  5153. JumpLabel.decrefs;
  5154. RemoveInstruction(hp1);
  5155. end
  5156. else
  5157. begin
  5158. { Only remove the second test if no jumps or other conditional instructions follow }
  5159. TransferUsedRegs(TmpUsedRegs);
  5160. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5161. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5162. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5163. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5164. begin
  5165. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5166. RemoveInstruction(p_dist);
  5167. { Remove the first jump, not the second, to keep
  5168. any register deallocations between the second
  5169. TEST/JNE pair in the same place. Aids future
  5170. optimisation. }
  5171. if Assigned(JumpLabel) then
  5172. JumpLabel.decrefs;
  5173. RemoveInstruction(hp1);
  5174. end
  5175. else
  5176. begin
  5177. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5178. if IsJumpToLabel(taicpu(hp1_dist)) then
  5179. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5180. { Remove second jump in this instance }
  5181. RemoveInstruction(hp1_dist);
  5182. end;
  5183. end;
  5184. Result := True;
  5185. Exit;
  5186. end;
  5187. end;
  5188. if { If -O2 and under, it may stop on any old instruction }
  5189. (cs_opt_level3 in current_settings.optimizerswitches) and
  5190. (taicpu(p).oper[1]^.typ = top_reg) and
  5191. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5192. begin
  5193. hp1_last := p_dist;
  5194. Continue;
  5195. end;
  5196. Break;
  5197. end;
  5198. end;
  5199. { Search for:
  5200. test %reg,%reg
  5201. j(c1) @lbl1
  5202. ...
  5203. @lbl:
  5204. test %reg,%reg (same register)
  5205. j(c2) @lbl2
  5206. If c2 is a subset of c1, change to:
  5207. test %reg,%reg
  5208. j(c1) @lbl2
  5209. (@lbl1 may become a dead label as a result)
  5210. }
  5211. if (taicpu(p).oper[1]^.typ = top_reg) and
  5212. (taicpu(p).oper[0]^.typ = top_reg) and
  5213. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5214. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5215. Assigned(p_label) and
  5216. GetNextInstruction(p_label, p_dist) and
  5217. MatchInstruction(p_dist, A_TEST, []) and
  5218. { It's fine if the second test uses smaller sub-registers }
  5219. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5220. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5221. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5222. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5223. GetNextInstruction(p_dist, hp1_dist) and
  5224. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5225. begin
  5226. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5227. if JumpLabel = JumpLabel_dist then
  5228. { This is an infinite loop }
  5229. Exit;
  5230. { Best optimisation when the first condition is a subset (or equal) of the second }
  5231. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5232. begin
  5233. { Any registers used here will already be allocated }
  5234. if Assigned(JumpLabel) then
  5235. JumpLabel.DecRefs;
  5236. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5237. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5238. Result := True;
  5239. Exit;
  5240. end;
  5241. end;
  5242. end;
  5243. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5244. var
  5245. hp1, hp2: tai;
  5246. ActiveReg: TRegister;
  5247. OldOffset: asizeint;
  5248. ThisConst: TCGInt;
  5249. function RegDeallocated: Boolean;
  5250. begin
  5251. TransferUsedRegs(TmpUsedRegs);
  5252. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5253. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5254. end;
  5255. begin
  5256. result:=false;
  5257. hp1 := nil;
  5258. { replace
  5259. addX const,%reg1
  5260. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5261. dealloc %reg1
  5262. by
  5263. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5264. }
  5265. if MatchOpType(taicpu(p),top_const,top_reg) then
  5266. begin
  5267. ActiveReg := taicpu(p).oper[1]^.reg;
  5268. { Ensures the entire register was updated }
  5269. if (taicpu(p).opsize >= S_L) and
  5270. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5271. MatchInstruction(hp1,A_LEA,[]) and
  5272. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5273. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5274. (
  5275. { Cover the case where the register in the reference is also the destination register }
  5276. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5277. (
  5278. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5279. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5280. RegDeallocated
  5281. )
  5282. ) then
  5283. begin
  5284. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5285. {$push}
  5286. {$R-}{$Q-}
  5287. { Explicitly disable overflow checking for these offset calculation
  5288. as those do not matter for the final result }
  5289. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5290. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5291. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5292. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5293. {$pop}
  5294. {$ifdef x86_64}
  5295. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5296. begin
  5297. { Overflow; abort }
  5298. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5299. end
  5300. else
  5301. {$endif x86_64}
  5302. begin
  5303. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5304. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5305. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5306. RemoveCurrentP(p, hp1)
  5307. else
  5308. RemoveCurrentP(p);
  5309. result:=true;
  5310. Exit;
  5311. end;
  5312. end;
  5313. if (
  5314. { Save calling GetNextInstructionUsingReg again }
  5315. Assigned(hp1) or
  5316. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5317. ) and
  5318. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5319. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5320. begin
  5321. if taicpu(hp1).oper[0]^.typ = top_const then
  5322. begin
  5323. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5324. if taicpu(hp1).opcode = A_ADD then
  5325. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5326. else
  5327. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5328. Result := True;
  5329. { Handle any overflows }
  5330. case taicpu(p).opsize of
  5331. S_B:
  5332. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5333. S_W:
  5334. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5335. S_L:
  5336. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5337. {$ifdef x86_64}
  5338. S_Q:
  5339. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5340. { Overflow; abort }
  5341. Result := False
  5342. else
  5343. taicpu(p).oper[0]^.val := ThisConst;
  5344. {$endif x86_64}
  5345. else
  5346. InternalError(2021102610);
  5347. end;
  5348. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5349. if Result then
  5350. begin
  5351. if (taicpu(p).oper[0]^.val < 0) and
  5352. (
  5353. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5354. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5355. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5356. ) then
  5357. begin
  5358. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5359. taicpu(p).opcode := A_SUB;
  5360. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5361. end
  5362. else
  5363. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5364. RemoveInstruction(hp1);
  5365. end;
  5366. end
  5367. else
  5368. begin
  5369. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5370. TransferUsedRegs(TmpUsedRegs);
  5371. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5372. hp2 := p;
  5373. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5374. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5375. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5376. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5377. begin
  5378. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5379. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5380. Asml.Remove(p);
  5381. Asml.InsertAfter(p, hp1);
  5382. p := hp1;
  5383. Result := True;
  5384. Exit;
  5385. end;
  5386. end;
  5387. end;
  5388. if DoArithCombineOpt(p) then
  5389. Result:=true;
  5390. end;
  5391. end;
  5392. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5393. var
  5394. hp1, hp2: tai;
  5395. ref: Integer;
  5396. saveref: treference;
  5397. offsetcalc: Int64;
  5398. TempReg: TRegister;
  5399. Multiple: TCGInt;
  5400. Adjacent, IntermediateRegDiscarded: Boolean;
  5401. begin
  5402. Result:=false;
  5403. { play save and throw an error if LEA uses a seg register prefix,
  5404. this is most likely an error somewhere else }
  5405. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5406. internalerror(2022022001);
  5407. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5408. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5409. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5410. (
  5411. { do not mess with leas accessing the stack pointer
  5412. unless it's a null operation }
  5413. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5414. (
  5415. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5416. (taicpu(p).oper[0]^.ref^.offset = 0)
  5417. )
  5418. ) and
  5419. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5420. begin
  5421. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5422. begin
  5423. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5424. begin
  5425. taicpu(p).opcode := A_MOV;
  5426. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5427. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5428. end
  5429. else
  5430. begin
  5431. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5432. RemoveCurrentP(p);
  5433. end;
  5434. Result:=true;
  5435. exit;
  5436. end
  5437. else if (
  5438. { continue to use lea to adjust the stack pointer,
  5439. it is the recommended way, but only if not optimizing for size }
  5440. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5441. (cs_opt_size in current_settings.optimizerswitches)
  5442. ) and
  5443. { If the flags register is in use, don't change the instruction
  5444. to an ADD otherwise this will scramble the flags. [Kit] }
  5445. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5446. ConvertLEA(taicpu(p)) then
  5447. begin
  5448. Result:=true;
  5449. exit;
  5450. end;
  5451. end;
  5452. { Don't optimise if the stack or frame pointer is the destination register }
  5453. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5454. Exit;
  5455. if GetNextInstruction(p,hp1) and
  5456. (hp1.typ=ait_instruction) then
  5457. begin
  5458. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5459. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5460. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5461. begin
  5462. TransferUsedRegs(TmpUsedRegs);
  5463. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5464. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5465. begin
  5466. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5467. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5468. RemoveInstruction(hp1);
  5469. result:=true;
  5470. exit;
  5471. end;
  5472. end;
  5473. { changes
  5474. lea <ref1>, reg1
  5475. <op> ...,<ref. with reg1>,...
  5476. to
  5477. <op> ...,<ref1>,... }
  5478. { find a reference which uses reg1 }
  5479. 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
  5480. ref:=0
  5481. 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
  5482. ref:=1
  5483. else
  5484. ref:=-1;
  5485. if (ref<>-1) and
  5486. { reg1 must be either the base or the index }
  5487. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5488. begin
  5489. { reg1 can be removed from the reference }
  5490. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5491. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5492. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5493. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5494. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5495. else
  5496. Internalerror(2019111201);
  5497. { check if the can insert all data of the lea into the second instruction }
  5498. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5499. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5500. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5501. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5502. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5503. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5504. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5505. {$ifdef x86_64}
  5506. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5507. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5508. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5509. )
  5510. {$endif x86_64}
  5511. then
  5512. begin
  5513. { reg1 might not used by the second instruction after it is remove from the reference }
  5514. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5515. begin
  5516. TransferUsedRegs(TmpUsedRegs);
  5517. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5518. { reg1 is not updated so it might not be used afterwards }
  5519. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5520. begin
  5521. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5522. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5523. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5524. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5525. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5526. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5527. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5528. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5529. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5530. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5531. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5532. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5533. RemoveCurrentP(p, hp1);
  5534. result:=true;
  5535. exit;
  5536. end
  5537. end;
  5538. end;
  5539. { recover }
  5540. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5541. end;
  5542. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5543. if Adjacent or
  5544. { Check further ahead (up to 2 instructions ahead for -O2) }
  5545. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5546. begin
  5547. { Check common LEA/LEA conditions }
  5548. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5549. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5550. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5551. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5552. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5553. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5554. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5555. (
  5556. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5557. calling it (since it calls GetNextInstruction) }
  5558. Adjacent or
  5559. (
  5560. (
  5561. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5562. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5563. ) and (
  5564. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5565. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5566. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5567. )
  5568. )
  5569. ) then
  5570. begin
  5571. TransferUsedRegs(TmpUsedRegs);
  5572. hp2 := p;
  5573. repeat
  5574. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5575. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5576. IntermediateRegDiscarded :=
  5577. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5578. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5579. { changes
  5580. lea offset1(regX,scale), reg1
  5581. lea offset2(reg1,reg1), reg2
  5582. to
  5583. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5584. and
  5585. lea offset1(regX,scale1), reg1
  5586. lea offset2(reg1,scale2), reg2
  5587. to
  5588. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5589. and
  5590. lea offset1(regX,scale1), reg1
  5591. lea offset2(reg3,reg1,scale2), reg2
  5592. to
  5593. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5594. ... so long as the final scale does not exceed 8
  5595. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5596. }
  5597. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5598. (
  5599. { Don't optimise if size is a concern and the intermediate register remains in use }
  5600. IntermediateRegDiscarded or
  5601. not (cs_opt_size in current_settings.optimizerswitches)
  5602. ) and
  5603. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5604. (
  5605. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5606. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5607. ) and (
  5608. (
  5609. { lea (reg1,scale2), reg2 variant }
  5610. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5611. (
  5612. Adjacent or
  5613. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5614. ) and
  5615. (
  5616. (
  5617. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5618. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5619. ) or (
  5620. { lea (regX,regX), reg1 variant }
  5621. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5622. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5623. )
  5624. )
  5625. ) or (
  5626. { lea (reg1,reg1), reg1 variant }
  5627. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5628. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5629. )
  5630. ) then
  5631. begin
  5632. { Make everything homogeneous to make calculations easier }
  5633. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5634. begin
  5635. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5636. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5637. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5638. else
  5639. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5640. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5641. end;
  5642. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5643. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5644. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5645. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5646. begin
  5647. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5648. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5649. begin
  5650. { Put the register to change in the index register }
  5651. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5652. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5653. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5654. end;
  5655. { Change lea (reg,reg) to lea(,reg,2) }
  5656. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5657. begin
  5658. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5659. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5660. end;
  5661. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5662. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5663. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5664. { Just to prevent miscalculations }
  5665. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5666. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5667. else
  5668. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5669. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5670. if IntermediateRegDiscarded then
  5671. begin
  5672. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5673. RemoveCurrentP(p);
  5674. end
  5675. else
  5676. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5677. result:=true;
  5678. exit;
  5679. end;
  5680. end;
  5681. { changes
  5682. lea offset1(regX), reg1
  5683. lea offset2(reg1), reg2
  5684. to
  5685. lea offset1+offset2(regX), reg2 }
  5686. if (
  5687. { Don't optimise if size is a concern and the intermediate register remains in use }
  5688. IntermediateRegDiscarded or
  5689. not (cs_opt_size in current_settings.optimizerswitches)
  5690. ) and
  5691. (
  5692. (
  5693. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5694. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5695. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5696. ) or (
  5697. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5698. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5699. (
  5700. (
  5701. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5702. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5703. ) or (
  5704. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5705. (
  5706. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5707. (
  5708. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5709. (
  5710. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5711. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5712. )
  5713. )
  5714. )
  5715. )
  5716. )
  5717. )
  5718. ) then
  5719. begin
  5720. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5721. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5722. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5723. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5724. begin
  5725. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5726. begin
  5727. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5728. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5729. { if the register is used as index and base, we have to increase for base as well
  5730. and adapt base }
  5731. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5732. begin
  5733. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5734. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5735. end;
  5736. end
  5737. else
  5738. begin
  5739. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5740. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5741. end;
  5742. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5743. begin
  5744. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5745. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5746. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5747. end;
  5748. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5749. if IntermediateRegDiscarded then
  5750. begin
  5751. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5752. RemoveCurrentP(p);
  5753. end
  5754. else
  5755. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5756. result:=true;
  5757. exit;
  5758. end;
  5759. end;
  5760. end;
  5761. { Change:
  5762. leal/q $x(%reg1),%reg2
  5763. ...
  5764. shll/q $y,%reg2
  5765. To:
  5766. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5767. }
  5768. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5769. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5770. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5771. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5772. (taicpu(hp1).oper[0]^.val <= 3) then
  5773. begin
  5774. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5775. TransferUsedRegs(TmpUsedRegs);
  5776. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5777. if
  5778. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5779. (this works even if scalefactor is zero) }
  5780. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5781. { Ensure offset doesn't go out of bounds }
  5782. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5783. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5784. (
  5785. (
  5786. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5787. (
  5788. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5789. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5790. (
  5791. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5792. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5793. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5794. )
  5795. )
  5796. ) or (
  5797. (
  5798. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5799. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5800. ) and
  5801. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5802. )
  5803. ) then
  5804. begin
  5805. repeat
  5806. with taicpu(p).oper[0]^.ref^ do
  5807. begin
  5808. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5809. if index = base then
  5810. begin
  5811. if Multiple > 4 then
  5812. { Optimisation will no longer work because resultant
  5813. scale factor will exceed 8 }
  5814. Break;
  5815. base := NR_NO;
  5816. scalefactor := 2;
  5817. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5818. end
  5819. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5820. begin
  5821. { Scale factor only works on the index register }
  5822. index := base;
  5823. base := NR_NO;
  5824. end;
  5825. { For safety }
  5826. if scalefactor <= 1 then
  5827. begin
  5828. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5829. scalefactor := Multiple;
  5830. end
  5831. else
  5832. begin
  5833. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5834. scalefactor := scalefactor * Multiple;
  5835. end;
  5836. offset := offset * Multiple;
  5837. end;
  5838. RemoveInstruction(hp1);
  5839. Result := True;
  5840. Exit;
  5841. { This repeat..until loop exists for the benefit of Break }
  5842. until True;
  5843. end;
  5844. end;
  5845. end;
  5846. end;
  5847. end;
  5848. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5849. var
  5850. hp1 : tai;
  5851. SubInstr: Boolean;
  5852. ThisConst: TCGInt;
  5853. const
  5854. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5855. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5856. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5857. begin
  5858. Result := False;
  5859. if taicpu(p).oper[0]^.typ <> top_const then
  5860. { Should have been confirmed before calling }
  5861. InternalError(2021102601);
  5862. SubInstr := (taicpu(p).opcode = A_SUB);
  5863. if GetLastInstruction(p, hp1) and
  5864. (hp1.typ = ait_instruction) and
  5865. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5866. begin
  5867. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5868. { Bad size }
  5869. InternalError(2022042001);
  5870. case taicpu(hp1).opcode Of
  5871. A_INC:
  5872. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5873. begin
  5874. if SubInstr then
  5875. ThisConst := taicpu(p).oper[0]^.val - 1
  5876. else
  5877. ThisConst := taicpu(p).oper[0]^.val + 1;
  5878. end
  5879. else
  5880. Exit;
  5881. A_DEC:
  5882. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5883. begin
  5884. if SubInstr then
  5885. ThisConst := taicpu(p).oper[0]^.val + 1
  5886. else
  5887. ThisConst := taicpu(p).oper[0]^.val - 1;
  5888. end
  5889. else
  5890. Exit;
  5891. A_SUB:
  5892. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5893. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5894. begin
  5895. if SubInstr then
  5896. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5897. else
  5898. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5899. end
  5900. else
  5901. Exit;
  5902. A_ADD:
  5903. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5904. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5905. begin
  5906. if SubInstr then
  5907. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5908. else
  5909. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5910. end
  5911. else
  5912. Exit;
  5913. else
  5914. Exit;
  5915. end;
  5916. { Check that the values are in range }
  5917. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5918. { Overflow; abort }
  5919. Exit;
  5920. if (ThisConst = 0) then
  5921. begin
  5922. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5923. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5924. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5925. RemoveInstruction(hp1);
  5926. hp1 := tai(p.next);
  5927. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5928. if not GetLastInstruction(hp1, p) then
  5929. p := hp1;
  5930. end
  5931. else
  5932. begin
  5933. if taicpu(hp1).opercnt=1 then
  5934. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5935. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5936. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5937. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5938. else
  5939. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5940. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5941. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5942. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5943. RemoveInstruction(hp1);
  5944. taicpu(p).loadconst(0, ThisConst);
  5945. end;
  5946. Result := True;
  5947. end;
  5948. end;
  5949. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  5950. begin
  5951. Result := False;
  5952. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5953. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5954. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5955. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5956. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5957. (
  5958. (
  5959. (taicpu(hp1).opcode = A_TEST)
  5960. ) or (
  5961. (taicpu(hp1).opcode = A_CMP) and
  5962. { A sanity check more than anything }
  5963. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5964. )
  5965. ) then
  5966. begin
  5967. { change
  5968. mov mem, %reg
  5969. ...
  5970. cmp/test x, %reg / test %reg,%reg
  5971. (reg deallocated)
  5972. to
  5973. cmp/test x, mem / cmp 0, mem
  5974. }
  5975. TransferUsedRegs(TmpUsedRegs);
  5976. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5977. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5978. begin
  5979. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5980. if (taicpu(hp1).opcode = A_TEST) and
  5981. (
  5982. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5983. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5984. ) then
  5985. begin
  5986. taicpu(hp1).opcode := A_CMP;
  5987. taicpu(hp1).loadconst(0, 0);
  5988. end;
  5989. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5990. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5991. RemoveCurrentP(p);
  5992. if (p <> hp1) then
  5993. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  5994. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  5995. { Make sure the flags are allocated across the CMP instruction }
  5996. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5997. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  5998. Result := True;
  5999. Exit;
  6000. end;
  6001. end;
  6002. end;
  6003. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6004. var
  6005. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6006. ThisReg, SecondReg: TRegister;
  6007. JumpLoc: TAsmLabel;
  6008. NewSize: TOpSize;
  6009. begin
  6010. Result := False;
  6011. {
  6012. Convert:
  6013. j<c> .L1
  6014. .L2:
  6015. mov 1,reg
  6016. jmp .L3 (or ret, although it might not be a RET yet)
  6017. .L1:
  6018. mov 0,reg
  6019. jmp .L3 (or ret)
  6020. ( As long as .L3 <> .L1 or .L2)
  6021. To:
  6022. mov 0,reg
  6023. set<not(c)> reg
  6024. jmp .L3 (or ret)
  6025. .L2:
  6026. mov 1,reg
  6027. jmp .L3 (or ret)
  6028. .L1:
  6029. mov 0,reg
  6030. jmp .L3 (or ret)
  6031. }
  6032. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6033. Exit;
  6034. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6035. if GetNextInstruction(hp_label, hp2) and
  6036. MatchInstruction(hp2,A_MOV,[]) and
  6037. (taicpu(hp2).oper[0]^.typ = top_const) and
  6038. (
  6039. (
  6040. (taicpu(hp2).oper[1]^.typ = top_reg)
  6041. {$ifdef i386}
  6042. { Under i386, ESI, EDI, EBP and ESP
  6043. don't have an 8-bit representation }
  6044. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6045. {$endif i386}
  6046. ) or (
  6047. {$ifdef i386}
  6048. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6049. {$endif i386}
  6050. (taicpu(hp2).opsize = S_B)
  6051. )
  6052. ) and
  6053. GetNextInstruction(hp2, hp3) and
  6054. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6055. (
  6056. (taicpu(hp3).opcode=A_RET) or
  6057. (
  6058. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6059. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6060. )
  6061. ) and
  6062. GetNextInstruction(hp3, hp4) and
  6063. (hp4.typ=ait_label) and
  6064. (tai_label(hp4).labsym=JumpLoc) and
  6065. (
  6066. not (cs_opt_size in current_settings.optimizerswitches) or
  6067. { If the initial jump is the label's only reference, then it will
  6068. become a dead label if the other conditions are met and hence
  6069. remove at least 2 instructions, including a jump }
  6070. (JumpLoc.getrefs = 1)
  6071. ) and
  6072. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6073. that will be optimised out }
  6074. GetNextInstruction(hp4, hp5) and
  6075. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6076. (taicpu(hp5).oper[0]^.typ = top_const) and
  6077. (
  6078. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6079. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6080. ) and
  6081. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6082. GetNextInstruction(hp5,hp6) and
  6083. (
  6084. (hp6.typ<>ait_label) or
  6085. SkipLabels(hp6, hp6)
  6086. ) and
  6087. (hp6.typ=ait_instruction) then
  6088. begin
  6089. { First, let's look at the two jumps that are hp3 and hp6 }
  6090. if not
  6091. (
  6092. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6093. (
  6094. (taicpu(hp6).opcode=A_RET) or
  6095. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6096. )
  6097. ) then
  6098. { If condition is False, then the JMP/RET instructions matched conventionally }
  6099. begin
  6100. { See if one of the jumps can be instantly converted into a RET }
  6101. if (taicpu(hp3).opcode=A_JMP) then
  6102. begin
  6103. { Reuse hp5 }
  6104. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6105. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  6106. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  6107. Exit;
  6108. if MatchInstruction(hp5, A_RET, []) then
  6109. begin
  6110. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6111. ConvertJumpToRET(hp3, hp5);
  6112. Result := True;
  6113. end
  6114. else
  6115. Exit;
  6116. end;
  6117. if (taicpu(hp6).opcode=A_JMP) then
  6118. begin
  6119. { Reuse hp5 }
  6120. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6121. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6122. Exit;
  6123. if MatchInstruction(hp5, A_RET, []) then
  6124. begin
  6125. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6126. ConvertJumpToRET(hp6, hp5);
  6127. Result := True;
  6128. end
  6129. else
  6130. Exit;
  6131. end;
  6132. if not
  6133. (
  6134. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6135. (
  6136. (taicpu(hp6).opcode=A_RET) or
  6137. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6138. )
  6139. ) then
  6140. { Still doesn't match }
  6141. Exit;
  6142. end;
  6143. if (taicpu(hp2).oper[0]^.val = 1) then
  6144. begin
  6145. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6146. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6147. end
  6148. else
  6149. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6150. if taicpu(hp2).opsize=S_B then
  6151. begin
  6152. if taicpu(hp2).oper[1]^.typ = top_reg then
  6153. begin
  6154. SecondReg := taicpu(hp2).oper[1]^.reg;
  6155. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6156. end
  6157. else
  6158. begin
  6159. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6160. SecondReg := NR_NO;
  6161. end;
  6162. hp_pos := p;
  6163. hp_allocstart := hp4;
  6164. end
  6165. else
  6166. begin
  6167. { Will be a register because the size can't be S_B otherwise }
  6168. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6169. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6170. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6171. if (cs_opt_size in current_settings.optimizerswitches) then
  6172. begin
  6173. { Favour using MOVZX when optimising for size }
  6174. case taicpu(hp2).opsize of
  6175. S_W:
  6176. NewSize := S_BW;
  6177. S_L:
  6178. NewSize := S_BL;
  6179. {$ifdef x86_64}
  6180. S_Q:
  6181. begin
  6182. NewSize := S_BL;
  6183. { Will implicitly zero-extend to 64-bit }
  6184. setsubreg(SecondReg, R_SUBD);
  6185. end;
  6186. {$endif x86_64}
  6187. else
  6188. InternalError(2022101301);
  6189. end;
  6190. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6191. { Inserting it right before p will guarantee that the flags are also tracked }
  6192. Asml.InsertBefore(hp5, p);
  6193. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6194. hp_pos := hp5;
  6195. hp_allocstart := hp4;
  6196. end
  6197. else
  6198. begin
  6199. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6200. { Inserting it right before p will guarantee that the flags are also tracked }
  6201. Asml.InsertBefore(hp5, p);
  6202. hp_pos := p;
  6203. hp_allocstart := hp5;
  6204. end;
  6205. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6206. end;
  6207. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6208. taicpu(hp4).condition := taicpu(p).condition;
  6209. asml.InsertBefore(hp4, hp_pos);
  6210. if taicpu(hp3).is_jmp then
  6211. begin
  6212. JumpLoc.decrefs;
  6213. MakeUnconditional(taicpu(p));
  6214. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6215. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6216. end
  6217. else
  6218. ConvertJumpToRET(p, hp3);
  6219. if SecondReg <> NR_NO then
  6220. { Ensure the destination register is allocated over this region }
  6221. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6222. if (JumpLoc.getrefs = 0) then
  6223. RemoveDeadCodeAfterJump(hp3);
  6224. Result:=true;
  6225. exit;
  6226. end;
  6227. end;
  6228. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6229. var
  6230. hp1, hp2: tai;
  6231. ActiveReg: TRegister;
  6232. OldOffset: asizeint;
  6233. ThisConst: TCGInt;
  6234. function RegDeallocated: Boolean;
  6235. begin
  6236. TransferUsedRegs(TmpUsedRegs);
  6237. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6238. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6239. end;
  6240. begin
  6241. Result:=false;
  6242. hp1 := nil;
  6243. { replace
  6244. subX const,%reg1
  6245. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6246. dealloc %reg1
  6247. by
  6248. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6249. }
  6250. if MatchOpType(taicpu(p),top_const,top_reg) then
  6251. begin
  6252. ActiveReg := taicpu(p).oper[1]^.reg;
  6253. { Ensures the entire register was updated }
  6254. if (taicpu(p).opsize >= S_L) and
  6255. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6256. MatchInstruction(hp1,A_LEA,[]) and
  6257. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6258. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6259. (
  6260. { Cover the case where the register in the reference is also the destination register }
  6261. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6262. (
  6263. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6264. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6265. RegDeallocated
  6266. )
  6267. ) then
  6268. begin
  6269. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6270. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6271. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6272. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6273. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6274. {$ifdef x86_64}
  6275. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6276. begin
  6277. { Overflow; abort }
  6278. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6279. end
  6280. else
  6281. {$endif x86_64}
  6282. begin
  6283. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6284. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6285. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6286. RemoveCurrentP(p, hp1)
  6287. else
  6288. RemoveCurrentP(p);
  6289. result:=true;
  6290. Exit;
  6291. end;
  6292. end;
  6293. if (
  6294. { Save calling GetNextInstructionUsingReg again }
  6295. Assigned(hp1) or
  6296. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6297. ) and
  6298. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6299. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6300. begin
  6301. if taicpu(hp1).oper[0]^.typ = top_const then
  6302. begin
  6303. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6304. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6305. Result := True;
  6306. { Handle any overflows }
  6307. case taicpu(p).opsize of
  6308. S_B:
  6309. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6310. S_W:
  6311. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6312. S_L:
  6313. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6314. {$ifdef x86_64}
  6315. S_Q:
  6316. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6317. { Overflow; abort }
  6318. Result := False
  6319. else
  6320. taicpu(p).oper[0]^.val := ThisConst;
  6321. {$endif x86_64}
  6322. else
  6323. InternalError(2021102611);
  6324. end;
  6325. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6326. if Result then
  6327. begin
  6328. if (taicpu(p).oper[0]^.val < 0) and
  6329. (
  6330. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6331. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6332. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6333. ) then
  6334. begin
  6335. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6336. taicpu(p).opcode := A_SUB;
  6337. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6338. end
  6339. else
  6340. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6341. RemoveInstruction(hp1);
  6342. end;
  6343. end
  6344. else
  6345. begin
  6346. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6347. TransferUsedRegs(TmpUsedRegs);
  6348. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6349. hp2 := p;
  6350. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6351. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6352. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6353. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6354. begin
  6355. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6356. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6357. Asml.Remove(p);
  6358. Asml.InsertAfter(p, hp1);
  6359. p := hp1;
  6360. Result := True;
  6361. Exit;
  6362. end;
  6363. end;
  6364. end;
  6365. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6366. { * change "sub/add const1, reg" or "dec reg" followed by
  6367. "sub const2, reg" to one "sub ..., reg" }
  6368. {$ifdef i386}
  6369. if (taicpu(p).oper[0]^.val = 2) and
  6370. (ActiveReg = NR_ESP) and
  6371. { Don't do the sub/push optimization if the sub }
  6372. { comes from setting up the stack frame (JM) }
  6373. (not(GetLastInstruction(p,hp1)) or
  6374. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6375. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6376. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6377. begin
  6378. hp1 := tai(p.next);
  6379. while Assigned(hp1) and
  6380. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6381. not RegReadByInstruction(NR_ESP,hp1) and
  6382. not RegModifiedByInstruction(NR_ESP,hp1) do
  6383. hp1 := tai(hp1.next);
  6384. if Assigned(hp1) and
  6385. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6386. begin
  6387. taicpu(hp1).changeopsize(S_L);
  6388. if taicpu(hp1).oper[0]^.typ=top_reg then
  6389. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6390. hp1 := tai(p.next);
  6391. RemoveCurrentp(p, hp1);
  6392. Result:=true;
  6393. exit;
  6394. end;
  6395. end;
  6396. {$endif i386}
  6397. if DoArithCombineOpt(p) then
  6398. Result:=true;
  6399. end;
  6400. end;
  6401. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6402. var
  6403. TmpBool1,TmpBool2 : Boolean;
  6404. tmpref : treference;
  6405. hp1,hp2: tai;
  6406. mask, shiftval: tcgint;
  6407. begin
  6408. Result:=false;
  6409. { All these optimisations work on "shl/sal const,%reg" }
  6410. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6411. Exit;
  6412. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6413. (taicpu(p).oper[0]^.val <= 3) then
  6414. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6415. begin
  6416. { should we check the next instruction? }
  6417. TmpBool1 := True;
  6418. { have we found an add/sub which could be
  6419. integrated in the lea? }
  6420. TmpBool2 := False;
  6421. reference_reset(tmpref,2,[]);
  6422. TmpRef.index := taicpu(p).oper[1]^.reg;
  6423. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6424. while TmpBool1 and
  6425. GetNextInstruction(p, hp1) and
  6426. (tai(hp1).typ = ait_instruction) and
  6427. ((((taicpu(hp1).opcode = A_ADD) or
  6428. (taicpu(hp1).opcode = A_SUB)) and
  6429. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6430. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6431. (((taicpu(hp1).opcode = A_INC) or
  6432. (taicpu(hp1).opcode = A_DEC)) and
  6433. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6434. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6435. ((taicpu(hp1).opcode = A_LEA) and
  6436. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6437. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6438. (not GetNextInstruction(hp1,hp2) or
  6439. not instrReadsFlags(hp2)) Do
  6440. begin
  6441. TmpBool1 := False;
  6442. if taicpu(hp1).opcode=A_LEA then
  6443. begin
  6444. if (TmpRef.base = NR_NO) and
  6445. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6446. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6447. { Segment register isn't a concern here }
  6448. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6449. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6450. begin
  6451. TmpBool1 := True;
  6452. TmpBool2 := True;
  6453. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6454. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6455. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6456. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6457. RemoveInstruction(hp1);
  6458. end
  6459. end
  6460. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6461. begin
  6462. TmpBool1 := True;
  6463. TmpBool2 := True;
  6464. case taicpu(hp1).opcode of
  6465. A_ADD:
  6466. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6467. A_SUB:
  6468. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6469. else
  6470. internalerror(2019050536);
  6471. end;
  6472. RemoveInstruction(hp1);
  6473. end
  6474. else
  6475. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6476. (((taicpu(hp1).opcode = A_ADD) and
  6477. (TmpRef.base = NR_NO)) or
  6478. (taicpu(hp1).opcode = A_INC) or
  6479. (taicpu(hp1).opcode = A_DEC)) then
  6480. begin
  6481. TmpBool1 := True;
  6482. TmpBool2 := True;
  6483. case taicpu(hp1).opcode of
  6484. A_ADD:
  6485. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6486. A_INC:
  6487. inc(TmpRef.offset);
  6488. A_DEC:
  6489. dec(TmpRef.offset);
  6490. else
  6491. internalerror(2019050535);
  6492. end;
  6493. RemoveInstruction(hp1);
  6494. end;
  6495. end;
  6496. if TmpBool2
  6497. {$ifndef x86_64}
  6498. or
  6499. ((current_settings.optimizecputype < cpu_Pentium2) and
  6500. (taicpu(p).oper[0]^.val <= 3) and
  6501. not(cs_opt_size in current_settings.optimizerswitches))
  6502. {$endif x86_64}
  6503. then
  6504. begin
  6505. if not(TmpBool2) and
  6506. (taicpu(p).oper[0]^.val=1) then
  6507. begin
  6508. taicpu(p).opcode := A_ADD;
  6509. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6510. end
  6511. else
  6512. begin
  6513. taicpu(p).opcode := A_LEA;
  6514. taicpu(p).loadref(0, TmpRef);
  6515. end;
  6516. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6517. Result := True;
  6518. end;
  6519. end
  6520. {$ifndef x86_64}
  6521. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6522. begin
  6523. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6524. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6525. (unlike shl, which is only Tairable in the U pipe) }
  6526. if taicpu(p).oper[0]^.val=1 then
  6527. begin
  6528. taicpu(p).opcode := A_ADD;
  6529. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6530. Result := True;
  6531. end
  6532. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6533. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6534. else if (taicpu(p).opsize = S_L) and
  6535. (taicpu(p).oper[0]^.val<= 3) then
  6536. begin
  6537. reference_reset(tmpref,2,[]);
  6538. TmpRef.index := taicpu(p).oper[1]^.reg;
  6539. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6540. taicpu(p).opcode := A_LEA;
  6541. taicpu(p).loadref(0, TmpRef);
  6542. Result := True;
  6543. end;
  6544. end
  6545. {$endif x86_64}
  6546. else if
  6547. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6548. (
  6549. (
  6550. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6551. SetAndTest(hp1, hp2)
  6552. {$ifdef x86_64}
  6553. ) or
  6554. (
  6555. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6556. GetNextInstruction(hp1, hp2) and
  6557. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6558. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6559. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6560. {$endif x86_64}
  6561. )
  6562. ) and
  6563. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6564. begin
  6565. { Change:
  6566. shl x, %reg1
  6567. mov -(1<<x), %reg2
  6568. and %reg2, %reg1
  6569. Or:
  6570. shl x, %reg1
  6571. and -(1<<x), %reg1
  6572. To just:
  6573. shl x, %reg1
  6574. Since the and operation only zeroes bits that are already zero from the shl operation
  6575. }
  6576. case taicpu(p).oper[0]^.val of
  6577. 8:
  6578. mask:=$FFFFFFFFFFFFFF00;
  6579. 16:
  6580. mask:=$FFFFFFFFFFFF0000;
  6581. 32:
  6582. mask:=$FFFFFFFF00000000;
  6583. 63:
  6584. { Constant pre-calculated to prevent overflow errors with Int64 }
  6585. mask:=$8000000000000000;
  6586. else
  6587. begin
  6588. if taicpu(p).oper[0]^.val >= 64 then
  6589. { Shouldn't happen realistically, since the register
  6590. is guaranteed to be set to zero at this point }
  6591. mask := 0
  6592. else
  6593. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6594. end;
  6595. end;
  6596. if taicpu(hp1).oper[0]^.val = mask then
  6597. begin
  6598. { Everything checks out, perform the optimisation, as long as
  6599. the FLAGS register isn't being used}
  6600. TransferUsedRegs(TmpUsedRegs);
  6601. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6602. {$ifdef x86_64}
  6603. if (hp1 <> hp2) then
  6604. begin
  6605. { "shl/mov/and" version }
  6606. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6607. { Don't do the optimisation if the FLAGS register is in use }
  6608. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6609. begin
  6610. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6611. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6612. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6613. begin
  6614. RemoveInstruction(hp1);
  6615. Result := True;
  6616. end;
  6617. { Only set Result to True if the 'mov' instruction was removed }
  6618. RemoveInstruction(hp2);
  6619. end;
  6620. end
  6621. else
  6622. {$endif x86_64}
  6623. begin
  6624. { "shl/and" version }
  6625. { Don't do the optimisation if the FLAGS register is in use }
  6626. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6627. begin
  6628. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6629. RemoveInstruction(hp1);
  6630. Result := True;
  6631. end;
  6632. end;
  6633. Exit;
  6634. end
  6635. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6636. begin
  6637. { Even if the mask doesn't allow for its removal, we might be
  6638. able to optimise the mask for the "shl/and" version, which
  6639. may permit other peephole optimisations }
  6640. {$ifdef DEBUG_AOPTCPU}
  6641. mask := taicpu(hp1).oper[0]^.val and mask;
  6642. if taicpu(hp1).oper[0]^.val <> mask then
  6643. begin
  6644. DebugMsg(
  6645. SPeepholeOptimization +
  6646. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6647. ' to $' + debug_tostr(mask) +
  6648. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6649. taicpu(hp1).oper[0]^.val := mask;
  6650. end;
  6651. {$else DEBUG_AOPTCPU}
  6652. { If debugging is off, just set the operand even if it's the same }
  6653. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6654. {$endif DEBUG_AOPTCPU}
  6655. end;
  6656. end;
  6657. {
  6658. change
  6659. shl/sal const,reg
  6660. <op> ...(...,reg,1),...
  6661. into
  6662. <op> ...(...,reg,1 shl const),...
  6663. if const in 1..3
  6664. }
  6665. if MatchOpType(taicpu(p), top_const, top_reg) and
  6666. (taicpu(p).oper[0]^.val in [1..3]) and
  6667. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6668. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6669. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6670. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6671. MatchOpType(taicpu(hp1),top_ref))
  6672. ) and
  6673. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6674. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6675. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6676. begin
  6677. TransferUsedRegs(TmpUsedRegs);
  6678. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6679. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6680. begin
  6681. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6682. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6683. RemoveCurrentP(p);
  6684. Result:=true;
  6685. exit;
  6686. end;
  6687. end;
  6688. if MatchOpType(taicpu(p), top_const, top_reg) and
  6689. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6690. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6691. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6692. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6693. begin
  6694. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6695. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6696. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6697. {$ifdef x86_64}
  6698. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6699. {$endif x86_64}
  6700. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6701. begin
  6702. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6703. taicpu(hp1).opcode:=A_MOV;
  6704. taicpu(hp1).oper[0]^.val:=0;
  6705. end
  6706. else
  6707. begin
  6708. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6709. taicpu(hp1).oper[0]^.val:=shiftval;
  6710. end;
  6711. RemoveCurrentP(p);
  6712. Result:=true;
  6713. exit;
  6714. end;
  6715. end;
  6716. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6717. begin
  6718. case shr_size of
  6719. S_B:
  6720. { No valid combinations }
  6721. Result := False;
  6722. S_W:
  6723. Result := (Shift >= 8) and (movz_size = S_BW);
  6724. S_L:
  6725. Result :=
  6726. (Shift >= 24) { Any opsize is valid for this shift } or
  6727. ((Shift >= 16) and (movz_size = S_WL));
  6728. {$ifdef x86_64}
  6729. S_Q:
  6730. Result :=
  6731. (Shift >= 56) { Any opsize is valid for this shift } or
  6732. ((Shift >= 48) and (movz_size = S_WL));
  6733. {$endif x86_64}
  6734. else
  6735. InternalError(2022081510);
  6736. end;
  6737. end;
  6738. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6739. var
  6740. hp1, hp2: tai;
  6741. Shift: TCGInt;
  6742. LimitSize: Topsize;
  6743. DoNotMerge: Boolean;
  6744. begin
  6745. Result := False;
  6746. { All these optimisations work on "shr const,%reg" }
  6747. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6748. Exit;
  6749. DoNotMerge := False;
  6750. Shift := taicpu(p).oper[0]^.val;
  6751. LimitSize := taicpu(p).opsize;
  6752. hp1 := p;
  6753. repeat
  6754. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6755. Exit;
  6756. case taicpu(hp1).opcode of
  6757. A_TEST, A_CMP, A_Jcc:
  6758. { Skip over conditional jumps and relevant comparisons }
  6759. Continue;
  6760. A_MOVZX:
  6761. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6762. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6763. begin
  6764. { Since the original register is being read as is, subsequent
  6765. SHRs must not be merged at this point }
  6766. DoNotMerge := True;
  6767. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6768. begin
  6769. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6770. begin
  6771. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6772. taicpu(hp1).opcode := A_MOV;
  6773. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6774. case taicpu(hp1).opsize of
  6775. S_BW:
  6776. taicpu(hp1).opsize := S_W;
  6777. S_BL, S_WL:
  6778. taicpu(hp1).opsize := S_L;
  6779. else
  6780. InternalError(2022081503);
  6781. end;
  6782. { p itself hasn't changed, so no need to set Result to True }
  6783. Include(OptsToCheck, aoc_ForceNewIteration);
  6784. { See if there's anything afterwards that can be
  6785. optimised, since the input register hasn't changed }
  6786. Continue;
  6787. end;
  6788. { NOTE: If the MOVZX instruction reads and writes the same
  6789. register, defer this to the post-peephole optimisation stage }
  6790. Exit;
  6791. end;
  6792. end;
  6793. A_SHL, A_SAL, A_SHR:
  6794. if (taicpu(hp1).opsize <= LimitSize) and
  6795. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6796. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6797. begin
  6798. { Make sure the sizes don't exceed the register size limit
  6799. (measured by the shift value falling below the limit) }
  6800. if taicpu(hp1).opsize < LimitSize then
  6801. LimitSize := taicpu(hp1).opsize;
  6802. if taicpu(hp1).opcode = A_SHR then
  6803. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6804. else
  6805. begin
  6806. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6807. DoNotMerge := True;
  6808. end;
  6809. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6810. Exit;
  6811. { Since we've established that the combined shift is within
  6812. limits, we can actually combine the adjacent SHR
  6813. instructions even if they're different sizes }
  6814. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6815. begin
  6816. hp2 := tai(hp1.Previous);
  6817. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6818. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6819. RemoveInstruction(hp1);
  6820. hp1 := hp2;
  6821. { Though p has changed, only the constant has, and its
  6822. effects can still be detected on the next iteration of
  6823. the repeat..until loop }
  6824. Include(OptsToCheck, aoc_ForceNewIteration);
  6825. end;
  6826. { Move onto the next instruction }
  6827. Continue;
  6828. end;
  6829. else
  6830. ;
  6831. end;
  6832. Break;
  6833. until False;
  6834. end;
  6835. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6836. var
  6837. CurrentRef: TReference;
  6838. FullReg: TRegister;
  6839. hp1, hp2: tai;
  6840. begin
  6841. Result := False;
  6842. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6843. Exit;
  6844. { We assume you've checked if the operand is actually a reference by
  6845. this point. If it isn't, you'll most likely get an access violation }
  6846. CurrentRef := first_mov.oper[1]^.ref^;
  6847. { Memory must be aligned }
  6848. if (CurrentRef.offset mod 4) <> 0 then
  6849. Exit;
  6850. Inc(CurrentRef.offset);
  6851. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6852. if MatchOperand(second_mov.oper[0]^, 0) and
  6853. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6854. GetNextInstruction(second_mov, hp1) and
  6855. (hp1.typ = ait_instruction) and
  6856. (taicpu(hp1).opcode = A_MOV) and
  6857. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6858. (taicpu(hp1).oper[0]^.val = 0) then
  6859. begin
  6860. Inc(CurrentRef.offset);
  6861. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6862. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6863. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6864. begin
  6865. case taicpu(hp1).opsize of
  6866. S_B:
  6867. if GetNextInstruction(hp1, hp2) and
  6868. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6869. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6870. (taicpu(hp2).oper[0]^.val = 0) then
  6871. begin
  6872. Inc(CurrentRef.offset);
  6873. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6874. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6875. (taicpu(hp2).opsize = S_B) then
  6876. begin
  6877. RemoveInstruction(hp1);
  6878. RemoveInstruction(hp2);
  6879. first_mov.opsize := S_L;
  6880. if first_mov.oper[0]^.typ = top_reg then
  6881. begin
  6882. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6883. { Reuse second_mov as a MOVZX instruction }
  6884. second_mov.opcode := A_MOVZX;
  6885. second_mov.opsize := S_BL;
  6886. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6887. second_mov.loadreg(1, FullReg);
  6888. first_mov.oper[0]^.reg := FullReg;
  6889. asml.Remove(second_mov);
  6890. asml.InsertBefore(second_mov, first_mov);
  6891. end
  6892. else
  6893. { It's a value }
  6894. begin
  6895. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6896. RemoveInstruction(second_mov);
  6897. end;
  6898. Result := True;
  6899. Exit;
  6900. end;
  6901. end;
  6902. S_W:
  6903. begin
  6904. RemoveInstruction(hp1);
  6905. first_mov.opsize := S_L;
  6906. if first_mov.oper[0]^.typ = top_reg then
  6907. begin
  6908. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6909. { Reuse second_mov as a MOVZX instruction }
  6910. second_mov.opcode := A_MOVZX;
  6911. second_mov.opsize := S_BL;
  6912. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6913. second_mov.loadreg(1, FullReg);
  6914. first_mov.oper[0]^.reg := FullReg;
  6915. asml.Remove(second_mov);
  6916. asml.InsertBefore(second_mov, first_mov);
  6917. end
  6918. else
  6919. { It's a value }
  6920. begin
  6921. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6922. RemoveInstruction(second_mov);
  6923. end;
  6924. Result := True;
  6925. Exit;
  6926. end;
  6927. else
  6928. ;
  6929. end;
  6930. end;
  6931. end;
  6932. end;
  6933. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6934. { returns true if a "continue" should be done after this optimization }
  6935. var
  6936. hp1, hp2, hp3: tai;
  6937. begin
  6938. Result := false;
  6939. hp3 := nil;
  6940. if MatchOpType(taicpu(p),top_ref) and
  6941. GetNextInstruction(p, hp1) and
  6942. (hp1.typ = ait_instruction) and
  6943. (((taicpu(hp1).opcode = A_FLD) and
  6944. (taicpu(p).opcode = A_FSTP)) or
  6945. ((taicpu(p).opcode = A_FISTP) and
  6946. (taicpu(hp1).opcode = A_FILD))) and
  6947. MatchOpType(taicpu(hp1),top_ref) and
  6948. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6949. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6950. begin
  6951. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6952. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6953. GetNextInstruction(hp1, hp2) and
  6954. (((hp2.typ = ait_instruction) and
  6955. IsExitCode(hp2) and
  6956. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6957. not(assigned(current_procinfo.procdef.funcretsym) and
  6958. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6959. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6960. { fstp <temp>
  6961. fld <temp>
  6962. <dealloc> <temp>
  6963. }
  6964. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6965. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6966. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6967. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6968. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6969. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6970. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6971. )
  6972. )
  6973. ) then
  6974. begin
  6975. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6976. RemoveInstruction(hp1);
  6977. RemoveCurrentP(p, hp2);
  6978. { first case: exit code }
  6979. if hp2.typ = ait_instruction then
  6980. RemoveLastDeallocForFuncRes(p);
  6981. Result := true;
  6982. end
  6983. else
  6984. { we can do this only in fast math mode as fstp is rounding ...
  6985. ... still disabled as it breaks the compiler and/or rtl }
  6986. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6987. { ... or if another fstp equal to the first one follows }
  6988. GetNextInstruction(hp1,hp2) and
  6989. (hp2.typ = ait_instruction) and
  6990. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6991. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6992. begin
  6993. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6994. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6995. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6996. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6997. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6998. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  6999. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7000. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7001. ) then
  7002. begin
  7003. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7004. RemoveCurrentP(p,hp2);
  7005. RemoveInstruction(hp1);
  7006. Result := true;
  7007. end
  7008. else if { fst can't store an extended/comp value }
  7009. (taicpu(p).opsize <> S_FX) and
  7010. (taicpu(p).opsize <> S_IQ) then
  7011. begin
  7012. if (taicpu(p).opcode = A_FSTP) then
  7013. taicpu(p).opcode := A_FST
  7014. else
  7015. taicpu(p).opcode := A_FIST;
  7016. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7017. RemoveInstruction(hp1);
  7018. Result := true;
  7019. end;
  7020. end;
  7021. end;
  7022. end;
  7023. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7024. var
  7025. hp1, hp2, hp3: tai;
  7026. begin
  7027. result:=false;
  7028. if MatchOpType(taicpu(p),top_reg) and
  7029. GetNextInstruction(p, hp1) and
  7030. (hp1.typ = Ait_Instruction) and
  7031. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7032. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7033. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7034. { change to
  7035. fld reg fxxx reg,st
  7036. fxxxp st, st1 (hp1)
  7037. Remark: non commutative operations must be reversed!
  7038. }
  7039. begin
  7040. case taicpu(hp1).opcode Of
  7041. A_FMULP,A_FADDP,
  7042. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7043. begin
  7044. case taicpu(hp1).opcode Of
  7045. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7046. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7047. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7048. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7049. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7050. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7051. else
  7052. internalerror(2019050534);
  7053. end;
  7054. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7055. taicpu(hp1).oper[1]^.reg := NR_ST;
  7056. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7057. RemoveCurrentP(p, hp1);
  7058. Result:=true;
  7059. exit;
  7060. end;
  7061. else
  7062. ;
  7063. end;
  7064. end
  7065. else
  7066. if MatchOpType(taicpu(p),top_ref) and
  7067. GetNextInstruction(p, hp2) and
  7068. (hp2.typ = Ait_Instruction) and
  7069. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7070. (taicpu(p).opsize in [S_FS, S_FL]) and
  7071. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7072. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7073. if GetLastInstruction(p, hp1) and
  7074. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7075. MatchOpType(taicpu(hp1),top_ref) and
  7076. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7077. if ((taicpu(hp2).opcode = A_FMULP) or
  7078. (taicpu(hp2).opcode = A_FADDP)) then
  7079. { change to
  7080. fld/fst mem1 (hp1) fld/fst mem1
  7081. fld mem1 (p) fadd/
  7082. faddp/ fmul st, st
  7083. fmulp st, st1 (hp2) }
  7084. begin
  7085. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7086. RemoveCurrentP(p, hp1);
  7087. if (taicpu(hp2).opcode = A_FADDP) then
  7088. taicpu(hp2).opcode := A_FADD
  7089. else
  7090. taicpu(hp2).opcode := A_FMUL;
  7091. taicpu(hp2).oper[1]^.reg := NR_ST;
  7092. end
  7093. else
  7094. { change to
  7095. fld/fst mem1 (hp1) fld/fst mem1
  7096. fld mem1 (p) fld st
  7097. }
  7098. begin
  7099. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7100. taicpu(p).changeopsize(S_FL);
  7101. taicpu(p).loadreg(0,NR_ST);
  7102. end
  7103. else
  7104. begin
  7105. case taicpu(hp2).opcode Of
  7106. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7107. { change to
  7108. fld/fst mem1 (hp1) fld/fst mem1
  7109. fld mem2 (p) fxxx mem2
  7110. fxxxp st, st1 (hp2) }
  7111. begin
  7112. case taicpu(hp2).opcode Of
  7113. A_FADDP: taicpu(p).opcode := A_FADD;
  7114. A_FMULP: taicpu(p).opcode := A_FMUL;
  7115. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7116. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7117. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7118. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7119. else
  7120. internalerror(2019050533);
  7121. end;
  7122. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7123. RemoveInstruction(hp2);
  7124. end
  7125. else
  7126. ;
  7127. end
  7128. end
  7129. end;
  7130. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7131. begin
  7132. Result := condition_in(cond1, cond2) or
  7133. { Not strictly subsets due to the actual flags checked, but because we're
  7134. comparing integers, E is a subset of AE and GE and their aliases }
  7135. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7136. end;
  7137. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7138. var
  7139. v: TCGInt;
  7140. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7141. FirstMatch, TempBool: Boolean;
  7142. NewReg: TRegister;
  7143. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7144. begin
  7145. Result:=false;
  7146. { All these optimisations need a next instruction }
  7147. if not GetNextInstruction(p, hp1) then
  7148. Exit;
  7149. { Search for:
  7150. cmp ###,###
  7151. j(c1) @lbl1
  7152. ...
  7153. @lbl:
  7154. cmp ###,### (same comparison as above)
  7155. j(c2) @lbl2
  7156. If c1 is a subset of c2, change to:
  7157. cmp ###,###
  7158. j(c1) @lbl2
  7159. (@lbl1 may become a dead label as a result)
  7160. }
  7161. { Also handle cases where there are multiple jumps in a row }
  7162. p_jump := hp1;
  7163. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7164. begin
  7165. if IsJumpToLabel(taicpu(p_jump)) then
  7166. begin
  7167. { Do jump optimisations first in case the condition becomes
  7168. unnecessary }
  7169. TempBool := True;
  7170. if DoJumpOptimizations(p_jump, TempBool) or
  7171. not TempBool then
  7172. begin
  7173. if Assigned(p_jump) then
  7174. begin
  7175. { CollapseZeroDistJump will be set to the label or an align
  7176. before it after the jump if it optimises, whether or not
  7177. the label is live or dead }
  7178. if (p_jump.typ = ait_align) or
  7179. (
  7180. (p_jump.typ = ait_label) and
  7181. not (tai_label(p_jump).labsym.is_used)
  7182. ) then
  7183. GetNextInstruction(p_jump, p_jump);
  7184. end;
  7185. TransferUsedRegs(TmpUsedRegs);
  7186. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7187. if not Assigned(p_jump) or
  7188. (
  7189. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7190. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7191. ) then
  7192. begin
  7193. { No more conditional jumps; conditional statement is no longer required }
  7194. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7195. RemoveCurrentP(p);
  7196. Result := True;
  7197. Exit;
  7198. end;
  7199. hp1 := p_jump;
  7200. Include(OptsToCheck, aoc_ForceNewIteration);
  7201. Continue;
  7202. end;
  7203. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7204. if GetNextInstruction(p_jump, hp2) and
  7205. (
  7206. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7207. not TempBool
  7208. ) then
  7209. begin
  7210. hp1 := p_jump;
  7211. Include(OptsToCheck, aoc_ForceNewIteration);
  7212. Continue;
  7213. end;
  7214. p_label := nil;
  7215. if Assigned(JumpLabel) then
  7216. p_label := getlabelwithsym(JumpLabel);
  7217. if Assigned(p_label) and
  7218. GetNextInstruction(p_label, p_dist) and
  7219. MatchInstruction(p_dist, A_CMP, []) and
  7220. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7221. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7222. GetNextInstruction(p_dist, hp1_dist) and
  7223. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7224. begin
  7225. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7226. if JumpLabel = JumpLabel_dist then
  7227. { This is an infinite loop }
  7228. Exit;
  7229. { Best optimisation when the first condition is a subset (or equal) of the second }
  7230. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7231. begin
  7232. { Any registers used here will already be allocated }
  7233. if Assigned(JumpLabel) then
  7234. JumpLabel.DecRefs;
  7235. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7236. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7237. Result := True;
  7238. { Don't exit yet. Since p and p_jump haven't actually been
  7239. removed, we can check for more on this iteration }
  7240. end
  7241. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7242. GetNextInstruction(hp1_dist, hp1_label) and
  7243. (hp1_label.typ = ait_label) then
  7244. begin
  7245. JumpLabel_far := tai_label(hp1_label).labsym;
  7246. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7247. { This is an infinite loop }
  7248. Exit;
  7249. if Assigned(JumpLabel_far) then
  7250. begin
  7251. { In this situation, if the first jump branches, the second one will never,
  7252. branch so change the destination label to after the second jump }
  7253. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7254. if Assigned(JumpLabel) then
  7255. JumpLabel.DecRefs;
  7256. JumpLabel_far.IncRefs;
  7257. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7258. Result := True;
  7259. { Don't exit yet. Since p and p_jump haven't actually been
  7260. removed, we can check for more on this iteration }
  7261. Continue;
  7262. end;
  7263. end;
  7264. end;
  7265. end;
  7266. { Search for:
  7267. cmp ###,###
  7268. j(c1) @lbl1
  7269. cmp ###,### (same as first)
  7270. Remove second cmp
  7271. }
  7272. if GetNextInstruction(p_jump, hp2) and
  7273. (
  7274. (
  7275. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7276. (
  7277. (
  7278. MatchOpType(taicpu(p), top_const, top_reg) and
  7279. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7280. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7281. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7282. ) or (
  7283. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7284. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7285. )
  7286. )
  7287. ) or (
  7288. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7289. MatchOperand(taicpu(p).oper[0]^, 0) and
  7290. (taicpu(p).oper[1]^.typ = top_reg) and
  7291. MatchInstruction(hp2, A_TEST, []) and
  7292. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7293. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7294. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7295. )
  7296. ) then
  7297. begin
  7298. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7299. RemoveInstruction(hp2);
  7300. Result := True;
  7301. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7302. end;
  7303. GetNextInstruction(p_jump, p_jump);
  7304. end;
  7305. if (
  7306. { Don't call GetNextInstruction again if we already have it }
  7307. (hp1 = p_jump) or
  7308. GetNextInstruction(p, hp1)
  7309. ) and
  7310. MatchInstruction(hp1, A_Jcc, []) and
  7311. IsJumpToLabel(taicpu(hp1)) and
  7312. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7313. GetNextInstruction(hp1, hp2) then
  7314. begin
  7315. {
  7316. cmp x, y (or "cmp y, x")
  7317. je @lbl
  7318. mov x, y
  7319. @lbl:
  7320. (x and y can be constants, registers or references)
  7321. Change to:
  7322. mov x, y (x and y will always be equal in the end)
  7323. @lbl: (may beceome a dead label)
  7324. Also:
  7325. cmp x, y (or "cmp y, x")
  7326. jne @lbl
  7327. mov x, y
  7328. @lbl:
  7329. (x and y can be constants, registers or references)
  7330. Change to:
  7331. Absolutely nothing! (Except @lbl if it's still live)
  7332. }
  7333. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7334. (
  7335. (
  7336. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7337. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7338. ) or (
  7339. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7340. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7341. )
  7342. ) and
  7343. GetNextInstruction(hp2, hp1_label) and
  7344. (hp1_label.typ = ait_label) and
  7345. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7346. begin
  7347. tai_label(hp1_label).labsym.DecRefs;
  7348. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7349. begin
  7350. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7351. RemoveInstruction(hp2);
  7352. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7353. end
  7354. else
  7355. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7356. RemoveInstruction(hp1);
  7357. RemoveCurrentp(p, hp2);
  7358. Result := True;
  7359. Exit;
  7360. end;
  7361. {
  7362. Try to optimise the following:
  7363. cmp $x,### ($x and $y can be registers or constants)
  7364. je @lbl1 (only reference)
  7365. cmp $y,### (### are identical)
  7366. @Lbl:
  7367. sete %reg1
  7368. Change to:
  7369. cmp $x,###
  7370. sete %reg2 (allocate new %reg2)
  7371. cmp $y,###
  7372. sete %reg1
  7373. orb %reg2,%reg1
  7374. (dealloc %reg2)
  7375. This adds an instruction (so don't perform under -Os), but it removes
  7376. a conditional branch.
  7377. }
  7378. if not (cs_opt_size in current_settings.optimizerswitches) and
  7379. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7380. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7381. { The first operand of CMP instructions can only be a register or
  7382. immediate anyway, so no need to check }
  7383. GetNextInstruction(hp2, p_label) and
  7384. (p_label.typ = ait_label) and
  7385. (tai_label(p_label).labsym.getrefs = 1) and
  7386. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7387. GetNextInstruction(p_label, p_dist) and
  7388. MatchInstruction(p_dist, A_SETcc, []) and
  7389. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7390. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7391. begin
  7392. TransferUsedRegs(TmpUsedRegs);
  7393. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7394. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7395. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7396. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7397. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7398. { Get the instruction after the SETcc instruction so we can
  7399. allocate a new register over the entire range }
  7400. GetNextInstruction(p_dist, hp1_dist) then
  7401. begin
  7402. { Register can appear in p if it's not used afterwards, so only
  7403. allocate between hp1 and hp1_dist }
  7404. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7405. if NewReg <> NR_NO then
  7406. begin
  7407. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7408. { Change the jump instruction into a SETcc instruction }
  7409. taicpu(hp1).opcode := A_SETcc;
  7410. taicpu(hp1).opsize := S_B;
  7411. taicpu(hp1).loadreg(0, NewReg);
  7412. { This is now a dead label }
  7413. tai_label(p_label).labsym.decrefs;
  7414. { Prefer adding before the next instruction so the FLAGS
  7415. register is deallicated first }
  7416. AsmL.InsertBefore(
  7417. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7418. hp1_dist
  7419. );
  7420. Result := True;
  7421. { Don't exit yet, as p wasn't changed and hp1, while
  7422. modified, is still intact and might be optimised by the
  7423. SETcc optimisation below }
  7424. end;
  7425. end;
  7426. end;
  7427. end;
  7428. if taicpu(p).oper[0]^.typ = top_const then
  7429. begin
  7430. if (taicpu(p).oper[0]^.val = 0) and
  7431. (taicpu(p).oper[1]^.typ = top_reg) and
  7432. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7433. begin
  7434. hp2 := p;
  7435. FirstMatch := True;
  7436. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7437. anything meaningful once it's converted to "test %reg,%reg";
  7438. additionally, some jumps will always (or never) branch, so
  7439. evaluate every jump immediately following the
  7440. comparison, optimising the conditions if possible.
  7441. Similarly with SETcc... those that are always set to 0 or 1
  7442. are changed to MOV instructions }
  7443. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7444. (
  7445. GetNextInstruction(hp2, hp1) and
  7446. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7447. ) do
  7448. begin
  7449. FirstMatch := False;
  7450. case taicpu(hp1).condition of
  7451. C_B, C_C, C_NAE, C_O:
  7452. { For B/NAE:
  7453. Will never branch since an unsigned integer can never be below zero
  7454. For C/O:
  7455. Result cannot overflow because 0 is being subtracted
  7456. }
  7457. begin
  7458. if taicpu(hp1).opcode = A_Jcc then
  7459. begin
  7460. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7461. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7462. RemoveInstruction(hp1);
  7463. { Since hp1 was deleted, hp2 must not be updated }
  7464. Continue;
  7465. end
  7466. else
  7467. begin
  7468. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7469. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7470. taicpu(hp1).opcode := A_MOV;
  7471. taicpu(hp1).ops := 2;
  7472. taicpu(hp1).condition := C_None;
  7473. taicpu(hp1).opsize := S_B;
  7474. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7475. taicpu(hp1).loadconst(0, 0);
  7476. end;
  7477. end;
  7478. C_BE, C_NA:
  7479. begin
  7480. { Will only branch if equal to zero }
  7481. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7482. taicpu(hp1).condition := C_E;
  7483. end;
  7484. C_A, C_NBE:
  7485. begin
  7486. { Will only branch if not equal to zero }
  7487. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7488. taicpu(hp1).condition := C_NE;
  7489. end;
  7490. C_AE, C_NB, C_NC, C_NO:
  7491. begin
  7492. { Will always branch }
  7493. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7494. if taicpu(hp1).opcode = A_Jcc then
  7495. begin
  7496. MakeUnconditional(taicpu(hp1));
  7497. { Any jumps/set that follow will now be dead code }
  7498. RemoveDeadCodeAfterJump(taicpu(hp1));
  7499. Break;
  7500. end
  7501. else
  7502. begin
  7503. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7504. taicpu(hp1).opcode := A_MOV;
  7505. taicpu(hp1).ops := 2;
  7506. taicpu(hp1).condition := C_None;
  7507. taicpu(hp1).opsize := S_B;
  7508. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7509. taicpu(hp1).loadconst(0, 1);
  7510. end;
  7511. end;
  7512. C_None:
  7513. InternalError(2020012201);
  7514. C_P, C_PE, C_NP, C_PO:
  7515. { We can't handle parity checks and they should never be generated
  7516. after a general-purpose CMP (it's used in some floating-point
  7517. comparisons that don't use CMP) }
  7518. InternalError(2020012202);
  7519. else
  7520. { Zero/Equality, Sign, their complements and all of the
  7521. signed comparisons do not need to be converted };
  7522. end;
  7523. hp2 := hp1;
  7524. end;
  7525. { Convert the instruction to a TEST }
  7526. taicpu(p).opcode := A_TEST;
  7527. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7528. Result := True;
  7529. Exit;
  7530. end
  7531. else if (taicpu(p).oper[0]^.val = 1) and
  7532. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7533. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7534. begin
  7535. { Convert; To:
  7536. cmp $1,r/m cmp $0,r/m
  7537. jl @lbl jle @lbl
  7538. (Also do inverted conditions)
  7539. }
  7540. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7541. taicpu(p).oper[0]^.val := 0;
  7542. if taicpu(hp1).condition in [C_L, C_NGE] then
  7543. taicpu(hp1).condition := C_LE
  7544. else
  7545. taicpu(hp1).condition := C_NLE;
  7546. { If the instruction is now "cmp $0,%reg", convert it to a
  7547. TEST (and effectively do the work of the "cmp $0,%reg" in
  7548. the block above)
  7549. }
  7550. if (taicpu(p).oper[1]^.typ = top_reg) then
  7551. begin
  7552. taicpu(p).opcode := A_TEST;
  7553. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7554. end;
  7555. Result := True;
  7556. Exit;
  7557. end
  7558. else if (taicpu(p).oper[1]^.typ = top_reg)
  7559. {$ifdef x86_64}
  7560. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7561. {$endif x86_64}
  7562. then
  7563. begin
  7564. { cmp register,$8000 neg register
  7565. je target --> jo target
  7566. .... only if register is deallocated before jump.}
  7567. case Taicpu(p).opsize of
  7568. S_B: v:=$80;
  7569. S_W: v:=$8000;
  7570. S_L: v:=qword($80000000);
  7571. else
  7572. internalerror(2013112905);
  7573. end;
  7574. if (taicpu(p).oper[0]^.val=v) and
  7575. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7576. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7577. begin
  7578. TransferUsedRegs(TmpUsedRegs);
  7579. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7580. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7581. begin
  7582. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7583. Taicpu(p).opcode:=A_NEG;
  7584. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7585. Taicpu(p).clearop(1);
  7586. Taicpu(p).ops:=1;
  7587. if Taicpu(hp1).condition=C_E then
  7588. Taicpu(hp1).condition:=C_O
  7589. else
  7590. Taicpu(hp1).condition:=C_NO;
  7591. Result:=true;
  7592. exit;
  7593. end;
  7594. end;
  7595. end;
  7596. end;
  7597. if TrySwapMovCmp(p, hp1) then
  7598. begin
  7599. Result := True;
  7600. Exit;
  7601. end;
  7602. end;
  7603. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7604. var
  7605. hp1: tai;
  7606. begin
  7607. {
  7608. remove the second (v)pxor from
  7609. pxor reg,reg
  7610. ...
  7611. pxor reg,reg
  7612. }
  7613. Result:=false;
  7614. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7615. MatchOpType(taicpu(p),top_reg,top_reg) and
  7616. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7617. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7618. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7619. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7620. begin
  7621. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7622. RemoveInstruction(hp1);
  7623. Result:=true;
  7624. Exit;
  7625. end
  7626. {
  7627. replace
  7628. pxor reg1,reg1
  7629. movapd/s reg1,reg2
  7630. dealloc reg1
  7631. by
  7632. pxor reg2,reg2
  7633. }
  7634. else if GetNextInstruction(p,hp1) and
  7635. { we mix single and double opperations here because we assume that the compiler
  7636. generates vmovapd only after double operations and vmovaps only after single operations }
  7637. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7638. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7639. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7640. (taicpu(p).oper[0]^.typ=top_reg) then
  7641. begin
  7642. TransferUsedRegs(TmpUsedRegs);
  7643. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7644. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7645. begin
  7646. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7647. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7648. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7649. RemoveInstruction(hp1);
  7650. result:=true;
  7651. end;
  7652. end;
  7653. end;
  7654. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7655. var
  7656. hp1: tai;
  7657. begin
  7658. {
  7659. remove the second (v)pxor from
  7660. (v)pxor reg,reg
  7661. ...
  7662. (v)pxor reg,reg
  7663. }
  7664. Result:=false;
  7665. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7666. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7667. begin
  7668. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7669. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7670. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7671. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7672. begin
  7673. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7674. RemoveInstruction(hp1);
  7675. Result:=true;
  7676. Exit;
  7677. end;
  7678. {$ifdef x86_64}
  7679. {
  7680. replace
  7681. vpxor reg1,reg1,reg1
  7682. vmov reg,mem
  7683. by
  7684. movq $0,mem
  7685. }
  7686. if GetNextInstruction(p,hp1) and
  7687. MatchInstruction(hp1,A_VMOVSD,[]) and
  7688. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7689. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7690. begin
  7691. TransferUsedRegs(TmpUsedRegs);
  7692. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7693. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7694. begin
  7695. taicpu(hp1).loadconst(0,0);
  7696. taicpu(hp1).opcode:=A_MOV;
  7697. taicpu(hp1).opsize:=S_Q;
  7698. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7699. RemoveCurrentP(p);
  7700. result:=true;
  7701. Exit;
  7702. end;
  7703. end;
  7704. {$endif x86_64}
  7705. end
  7706. {
  7707. replace
  7708. vpxor reg1,reg1,reg2
  7709. by
  7710. vpxor reg2,reg2,reg2
  7711. to avoid unncessary data dependencies
  7712. }
  7713. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7714. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7715. begin
  7716. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7717. { avoid unncessary data dependency }
  7718. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7719. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7720. result:=true;
  7721. exit;
  7722. end;
  7723. Result:=OptPass1VOP(p);
  7724. end;
  7725. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7726. var
  7727. hp1 : tai;
  7728. begin
  7729. result:=false;
  7730. { replace
  7731. IMul const,%mreg1,%mreg2
  7732. Mov %reg2,%mreg3
  7733. dealloc %mreg3
  7734. by
  7735. Imul const,%mreg1,%mreg23
  7736. }
  7737. if (taicpu(p).ops=3) and
  7738. GetNextInstruction(p,hp1) and
  7739. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7740. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7741. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7742. begin
  7743. TransferUsedRegs(TmpUsedRegs);
  7744. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7745. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7746. begin
  7747. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7748. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7749. RemoveInstruction(hp1);
  7750. result:=true;
  7751. end;
  7752. end;
  7753. end;
  7754. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7755. var
  7756. hp1 : tai;
  7757. begin
  7758. result:=false;
  7759. { replace
  7760. IMul %reg0,%reg1,%reg2
  7761. Mov %reg2,%reg3
  7762. dealloc %reg2
  7763. by
  7764. Imul %reg0,%reg1,%reg3
  7765. }
  7766. if GetNextInstruction(p,hp1) and
  7767. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7768. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7769. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7770. begin
  7771. TransferUsedRegs(TmpUsedRegs);
  7772. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7773. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7774. begin
  7775. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7776. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7777. RemoveInstruction(hp1);
  7778. result:=true;
  7779. end;
  7780. end;
  7781. end;
  7782. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7783. var
  7784. hp1: tai;
  7785. begin
  7786. Result:=false;
  7787. { get rid of
  7788. (v)cvtss2sd reg0,<reg1,>reg2
  7789. (v)cvtss2sd reg2,<reg2,>reg0
  7790. }
  7791. if GetNextInstruction(p,hp1) and
  7792. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7793. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7794. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7795. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7796. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7797. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7798. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7799. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7800. )
  7801. ) then
  7802. begin
  7803. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7804. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7805. begin
  7806. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7807. RemoveCurrentP(p);
  7808. RemoveInstruction(hp1);
  7809. end
  7810. else
  7811. begin
  7812. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7813. if taicpu(hp1).opcode=A_CVTSD2SS then
  7814. begin
  7815. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7816. taicpu(p).opcode:=A_MOVAPS;
  7817. end
  7818. else
  7819. begin
  7820. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7821. taicpu(p).opcode:=A_VMOVAPS;
  7822. end;
  7823. taicpu(p).ops:=2;
  7824. RemoveInstruction(hp1);
  7825. end;
  7826. Result:=true;
  7827. Exit;
  7828. end;
  7829. end;
  7830. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7831. var
  7832. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7833. ThisReg: TRegister;
  7834. begin
  7835. Result := False;
  7836. if not GetNextInstruction(p,hp1) then
  7837. Exit;
  7838. {
  7839. convert
  7840. j<c> .L1
  7841. mov 1,reg
  7842. jmp .L2
  7843. .L1
  7844. mov 0,reg
  7845. .L2
  7846. into
  7847. mov 0,reg
  7848. set<not(c)> reg
  7849. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7850. would destroy the flag contents
  7851. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7852. executed at the same time as a previous comparison.
  7853. set<not(c)> reg
  7854. movzx reg, reg
  7855. }
  7856. if MatchInstruction(hp1,A_MOV,[]) and
  7857. (taicpu(hp1).oper[0]^.typ = top_const) and
  7858. (
  7859. (
  7860. (taicpu(hp1).oper[1]^.typ = top_reg)
  7861. {$ifdef i386}
  7862. { Under i386, ESI, EDI, EBP and ESP
  7863. don't have an 8-bit representation }
  7864. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7865. {$endif i386}
  7866. ) or (
  7867. {$ifdef i386}
  7868. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7869. {$endif i386}
  7870. (taicpu(hp1).opsize = S_B)
  7871. )
  7872. ) and
  7873. GetNextInstruction(hp1,hp2) and
  7874. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7875. GetNextInstruction(hp2,hp3) and
  7876. (hp3.typ=ait_label) and
  7877. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7878. GetNextInstruction(hp3,hp4) and
  7879. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7880. (taicpu(hp4).oper[0]^.typ = top_const) and
  7881. (
  7882. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7883. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7884. ) and
  7885. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7886. GetNextInstruction(hp4,hp5) and
  7887. (hp5.typ=ait_label) and
  7888. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7889. begin
  7890. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7891. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7892. tai_label(hp3).labsym.DecRefs;
  7893. { If this isn't the only reference to the middle label, we can
  7894. still make a saving - only that the first jump and everything
  7895. that follows will remain. }
  7896. if (tai_label(hp3).labsym.getrefs = 0) then
  7897. begin
  7898. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7899. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7900. else
  7901. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7902. { remove jump, first label and second MOV (also catching any aligns) }
  7903. repeat
  7904. if not GetNextInstruction(hp2, hp3) then
  7905. InternalError(2021040810);
  7906. RemoveInstruction(hp2);
  7907. hp2 := hp3;
  7908. until hp2 = hp5;
  7909. { Don't decrement reference count before the removal loop
  7910. above, otherwise GetNextInstruction won't stop on the
  7911. the label }
  7912. tai_label(hp5).labsym.DecRefs;
  7913. end
  7914. else
  7915. begin
  7916. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7917. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7918. else
  7919. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7920. end;
  7921. taicpu(p).opcode:=A_SETcc;
  7922. taicpu(p).opsize:=S_B;
  7923. taicpu(p).is_jmp:=False;
  7924. if taicpu(hp1).opsize=S_B then
  7925. begin
  7926. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7927. if taicpu(hp1).oper[1]^.typ = top_reg then
  7928. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7929. RemoveInstruction(hp1);
  7930. end
  7931. else
  7932. begin
  7933. { Will be a register because the size can't be S_B otherwise }
  7934. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7935. taicpu(p).loadreg(0, ThisReg);
  7936. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7937. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7938. begin
  7939. case taicpu(hp1).opsize of
  7940. S_W:
  7941. taicpu(hp1).opsize := S_BW;
  7942. S_L:
  7943. taicpu(hp1).opsize := S_BL;
  7944. {$ifdef x86_64}
  7945. S_Q:
  7946. begin
  7947. taicpu(hp1).opsize := S_BL;
  7948. { Change the destination register to 32-bit }
  7949. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7950. end;
  7951. {$endif x86_64}
  7952. else
  7953. InternalError(2021040820);
  7954. end;
  7955. taicpu(hp1).opcode := A_MOVZX;
  7956. taicpu(hp1).loadreg(0, ThisReg);
  7957. end
  7958. else
  7959. begin
  7960. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7961. { hp1 is already a MOV instruction with the correct register }
  7962. taicpu(hp1).loadconst(0, 0);
  7963. { Inserting it right before p will guarantee that the flags are also tracked }
  7964. asml.Remove(hp1);
  7965. asml.InsertBefore(hp1, p);
  7966. end;
  7967. end;
  7968. Result:=true;
  7969. exit;
  7970. end
  7971. else if (hp1.typ = ait_label) then
  7972. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7973. end;
  7974. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7975. var
  7976. hp1, hp2, hp3: tai;
  7977. SourceRef, TargetRef: TReference;
  7978. CurrentReg: TRegister;
  7979. begin
  7980. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7981. if not UseAVX then
  7982. InternalError(2021100501);
  7983. Result := False;
  7984. { Look for the following to simplify:
  7985. vmovdqa/u x(mem1), %xmmreg
  7986. vmovdqa/u %xmmreg, y(mem2)
  7987. vmovdqa/u x+16(mem1), %xmmreg
  7988. vmovdqa/u %xmmreg, y+16(mem2)
  7989. Change to:
  7990. vmovdqa/u x(mem1), %ymmreg
  7991. vmovdqa/u %ymmreg, y(mem2)
  7992. vpxor %ymmreg, %ymmreg, %ymmreg
  7993. ( The VPXOR instruction is to zero the upper half, thus removing the
  7994. need to call the potentially expensive VZEROUPPER instruction. Other
  7995. peephole optimisations can remove VPXOR if it's unnecessary )
  7996. }
  7997. TransferUsedRegs(TmpUsedRegs);
  7998. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7999. { NOTE: In the optimisations below, if the references dictate that an
  8000. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8001. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8002. if (taicpu(p).opsize = S_XMM) and
  8003. MatchOpType(taicpu(p), top_ref, top_reg) and
  8004. GetNextInstruction(p, hp1) and
  8005. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8006. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8007. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8008. begin
  8009. SourceRef := taicpu(p).oper[0]^.ref^;
  8010. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8011. if GetNextInstruction(hp1, hp2) and
  8012. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8013. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8014. begin
  8015. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8016. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8017. Inc(SourceRef.offset, 16);
  8018. { Reuse the register in the first block move }
  8019. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8020. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8021. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8022. begin
  8023. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8024. Inc(TargetRef.offset, 16);
  8025. if GetNextInstruction(hp2, hp3) and
  8026. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8027. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8028. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8029. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8030. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8031. begin
  8032. { Update the register tracking to the new size }
  8033. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8034. { Remember that the offsets are 16 ahead }
  8035. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8036. if not (
  8037. ((SourceRef.offset mod 32) = 16) and
  8038. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8039. ) then
  8040. taicpu(p).opcode := A_VMOVDQU;
  8041. taicpu(p).opsize := S_YMM;
  8042. taicpu(p).oper[1]^.reg := CurrentReg;
  8043. if not (
  8044. ((TargetRef.offset mod 32) = 16) and
  8045. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8046. ) then
  8047. taicpu(hp1).opcode := A_VMOVDQU;
  8048. taicpu(hp1).opsize := S_YMM;
  8049. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8050. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8051. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8052. if (pi_uses_ymm in current_procinfo.flags) then
  8053. RemoveInstruction(hp2)
  8054. else
  8055. begin
  8056. taicpu(hp2).opcode := A_VPXOR;
  8057. taicpu(hp2).opsize := S_YMM;
  8058. taicpu(hp2).loadreg(0, CurrentReg);
  8059. taicpu(hp2).loadreg(1, CurrentReg);
  8060. taicpu(hp2).loadreg(2, CurrentReg);
  8061. taicpu(hp2).ops := 3;
  8062. end;
  8063. RemoveInstruction(hp3);
  8064. Result := True;
  8065. Exit;
  8066. end;
  8067. end
  8068. else
  8069. begin
  8070. { See if the next references are 16 less rather than 16 greater }
  8071. Dec(SourceRef.offset, 32); { -16 the other way }
  8072. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8073. begin
  8074. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8075. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8076. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8077. GetNextInstruction(hp2, hp3) and
  8078. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8079. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8080. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8081. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8082. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8083. begin
  8084. { Update the register tracking to the new size }
  8085. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8086. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8087. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8088. if not(
  8089. ((SourceRef.offset mod 32) = 0) and
  8090. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8091. ) then
  8092. taicpu(hp2).opcode := A_VMOVDQU;
  8093. taicpu(hp2).opsize := S_YMM;
  8094. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8095. if not (
  8096. ((TargetRef.offset mod 32) = 0) and
  8097. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8098. ) then
  8099. taicpu(hp3).opcode := A_VMOVDQU;
  8100. taicpu(hp3).opsize := S_YMM;
  8101. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8102. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8103. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8104. if (pi_uses_ymm in current_procinfo.flags) then
  8105. RemoveInstruction(hp1)
  8106. else
  8107. begin
  8108. taicpu(hp1).opcode := A_VPXOR;
  8109. taicpu(hp1).opsize := S_YMM;
  8110. taicpu(hp1).loadreg(0, CurrentReg);
  8111. taicpu(hp1).loadreg(1, CurrentReg);
  8112. taicpu(hp1).loadreg(2, CurrentReg);
  8113. taicpu(hp1).ops := 3;
  8114. Asml.Remove(hp1);
  8115. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8116. end;
  8117. RemoveCurrentP(p, hp2);
  8118. Result := True;
  8119. Exit;
  8120. end;
  8121. end;
  8122. end;
  8123. end;
  8124. end;
  8125. end;
  8126. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8127. var
  8128. hp2, hp3, first_assignment: tai;
  8129. IncCount, OperIdx: Integer;
  8130. OrigLabel: TAsmLabel;
  8131. begin
  8132. Count := 0;
  8133. Result := False;
  8134. first_assignment := nil;
  8135. if (LoopCount >= 20) then
  8136. begin
  8137. { Guard against infinite loops }
  8138. Exit;
  8139. end;
  8140. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8141. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8142. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8143. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8144. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8145. Exit;
  8146. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8147. {
  8148. change
  8149. jmp .L1
  8150. ...
  8151. .L1:
  8152. mov ##, ## ( multiple movs possible )
  8153. jmp/ret
  8154. into
  8155. mov ##, ##
  8156. jmp/ret
  8157. }
  8158. if not Assigned(hp1) then
  8159. begin
  8160. hp1 := GetLabelWithSym(OrigLabel);
  8161. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8162. Exit;
  8163. end;
  8164. hp2 := hp1;
  8165. while Assigned(hp2) do
  8166. begin
  8167. if Assigned(hp2) and (hp2.typ = ait_label) then
  8168. SkipLabels(hp2,hp2);
  8169. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8170. Break;
  8171. case taicpu(hp2).opcode of
  8172. A_MOVSD:
  8173. begin
  8174. if taicpu(hp2).ops = 0 then
  8175. { Wrong MOVSD }
  8176. Break;
  8177. Inc(Count);
  8178. if Count >= 5 then
  8179. { Too many to be worthwhile }
  8180. Break;
  8181. GetNextInstruction(hp2, hp2);
  8182. Continue;
  8183. end;
  8184. A_MOV,
  8185. A_MOVD,
  8186. A_MOVQ,
  8187. A_MOVSX,
  8188. {$ifdef x86_64}
  8189. A_MOVSXD,
  8190. {$endif x86_64}
  8191. A_MOVZX,
  8192. A_MOVAPS,
  8193. A_MOVUPS,
  8194. A_MOVSS,
  8195. A_MOVAPD,
  8196. A_MOVUPD,
  8197. A_MOVDQA,
  8198. A_MOVDQU,
  8199. A_VMOVSS,
  8200. A_VMOVAPS,
  8201. A_VMOVUPS,
  8202. A_VMOVSD,
  8203. A_VMOVAPD,
  8204. A_VMOVUPD,
  8205. A_VMOVDQA,
  8206. A_VMOVDQU:
  8207. begin
  8208. Inc(Count);
  8209. if Count >= 5 then
  8210. { Too many to be worthwhile }
  8211. Break;
  8212. GetNextInstruction(hp2, hp2);
  8213. Continue;
  8214. end;
  8215. A_JMP:
  8216. begin
  8217. { Guard against infinite loops }
  8218. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8219. Exit;
  8220. { Analyse this jump first in case it also duplicates assignments }
  8221. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8222. begin
  8223. { Something did change! }
  8224. Result := True;
  8225. Inc(Count, IncCount);
  8226. if Count >= 5 then
  8227. begin
  8228. { Too many to be worthwhile }
  8229. Exit;
  8230. end;
  8231. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8232. Break;
  8233. end;
  8234. Result := True;
  8235. Break;
  8236. end;
  8237. A_RET:
  8238. begin
  8239. Result := True;
  8240. Break;
  8241. end;
  8242. else
  8243. Break;
  8244. end;
  8245. end;
  8246. if Result then
  8247. begin
  8248. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8249. if Count = 0 then
  8250. begin
  8251. Result := False;
  8252. Exit;
  8253. end;
  8254. hp3 := p;
  8255. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8256. while True do
  8257. begin
  8258. if Assigned(hp1) and (hp1.typ = ait_label) then
  8259. SkipLabels(hp1,hp1);
  8260. if (hp1.typ <> ait_instruction) then
  8261. InternalError(2021040720);
  8262. case taicpu(hp1).opcode of
  8263. A_JMP:
  8264. begin
  8265. { Change the original jump to the new destination }
  8266. OrigLabel.decrefs;
  8267. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8268. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8269. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8270. if not Assigned(first_assignment) then
  8271. InternalError(2021040810)
  8272. else
  8273. p := first_assignment;
  8274. Exit;
  8275. end;
  8276. A_RET:
  8277. begin
  8278. { Now change the jump into a RET instruction }
  8279. ConvertJumpToRET(p, hp1);
  8280. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8281. if not Assigned(first_assignment) then
  8282. InternalError(2021040811)
  8283. else
  8284. p := first_assignment;
  8285. Exit;
  8286. end;
  8287. else
  8288. begin
  8289. { Duplicate the MOV instruction }
  8290. hp3:=tai(hp1.getcopy);
  8291. if first_assignment = nil then
  8292. first_assignment := hp3;
  8293. asml.InsertBefore(hp3, p);
  8294. { Make sure the compiler knows about any final registers written here }
  8295. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8296. with taicpu(hp3).oper[OperIdx]^ do
  8297. begin
  8298. case typ of
  8299. top_ref:
  8300. begin
  8301. if (ref^.base <> NR_NO) and
  8302. (getsupreg(ref^.base) <> RS_ESP) and
  8303. (getsupreg(ref^.base) <> RS_EBP)
  8304. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8305. then
  8306. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8307. if (ref^.index <> NR_NO) and
  8308. (getsupreg(ref^.index) <> RS_ESP) and
  8309. (getsupreg(ref^.index) <> RS_EBP)
  8310. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8311. (ref^.index <> ref^.base) then
  8312. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8313. end;
  8314. top_reg:
  8315. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8316. else
  8317. ;
  8318. end;
  8319. end;
  8320. end;
  8321. end;
  8322. if not GetNextInstruction(hp1, hp1) then
  8323. { Should have dropped out earlier }
  8324. InternalError(2021040710);
  8325. end;
  8326. end;
  8327. end;
  8328. const
  8329. WriteOp: array[0..3] of set of TInsChange = (
  8330. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8331. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8332. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8333. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8334. RegWriteFlags: array[0..7] of set of TInsChange = (
  8335. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8336. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8337. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8338. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8339. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8340. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8341. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8342. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8343. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8344. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8345. var
  8346. hp2: tai;
  8347. X: Integer;
  8348. begin
  8349. { If we have something like:
  8350. op ###,###
  8351. mov ###,###
  8352. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8353. interfere in regards to what they write to.
  8354. NOTE: p must be a 2-operand instruction
  8355. }
  8356. Result := False;
  8357. if (hp1.typ <> ait_instruction) or
  8358. taicpu(hp1).is_jmp or
  8359. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8360. Exit;
  8361. { NOP is a pipeline fence, likely marking the beginning of the function
  8362. epilogue, so drop out. Similarly, drop out if POP or RET are
  8363. encountered }
  8364. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8365. Exit;
  8366. if (taicpu(hp1).opcode = A_MOVSD) and
  8367. (taicpu(hp1).ops = 0) then
  8368. { Wrong MOVSD }
  8369. Exit;
  8370. { Check for writes to specific registers first }
  8371. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8372. for X := 0 to 7 do
  8373. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8374. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8375. Exit;
  8376. for X := 0 to taicpu(hp1).ops - 1 do
  8377. begin
  8378. { Check to see if this operand writes to something }
  8379. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8380. { And matches something in the CMP/TEST instruction }
  8381. (
  8382. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8383. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8384. (
  8385. { If it's a register, make sure the register written to doesn't
  8386. appear in the cmp instruction as part of a reference }
  8387. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8388. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8389. )
  8390. ) then
  8391. Exit;
  8392. end;
  8393. { Check p to make sure it doesn't write to something that affects hp1 }
  8394. { Check for writes to specific registers first }
  8395. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8396. for X := 0 to 7 do
  8397. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8398. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8399. Exit;
  8400. for X := 0 to taicpu(p).ops - 1 do
  8401. begin
  8402. { Check to see if this operand writes to something }
  8403. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8404. { And matches something in hp1 }
  8405. (taicpu(p).oper[X]^.typ = top_reg) and
  8406. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8407. Exit;
  8408. end;
  8409. { The instruction can be safely moved }
  8410. asml.Remove(hp1);
  8411. { Try to insert after the last instructions where the FLAGS register is not
  8412. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8413. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8414. asml.InsertBefore(hp1, hp2)
  8415. { Failing that, try to insert after the last instructions where the
  8416. FLAGS register is not yet in use }
  8417. else if GetLastInstruction(p, hp2) and
  8418. (
  8419. (hp2.typ <> ait_instruction) or
  8420. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8421. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8422. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8423. ) then
  8424. asml.InsertAfter(hp1, hp2)
  8425. else
  8426. { Note, if p.Previous is nil (even if it should logically never be the
  8427. case), FindRegAllocBackward immediately exits with False and so we
  8428. safely land here (we can't just pass p because FindRegAllocBackward
  8429. immediately exits on an instruction). [Kit] }
  8430. asml.InsertBefore(hp1, p);
  8431. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8432. { We can't trust UsedRegs because we're looking backwards, although we
  8433. know the registers are allocated after p at the very least, so manually
  8434. create tai_regalloc objects if needed }
  8435. for X := 0 to taicpu(hp1).ops - 1 do
  8436. case taicpu(hp1).oper[X]^.typ of
  8437. top_reg:
  8438. begin
  8439. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8440. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8441. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8442. end;
  8443. top_ref:
  8444. begin
  8445. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8446. begin
  8447. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8448. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8449. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8450. end;
  8451. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8452. begin
  8453. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8454. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8455. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8456. end;
  8457. end;
  8458. else
  8459. ;
  8460. end;
  8461. Result := True;
  8462. end;
  8463. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8464. var
  8465. hp2: tai;
  8466. X: Integer;
  8467. begin
  8468. { If we have something like:
  8469. cmp ###,%reg1
  8470. mov 0,%reg2
  8471. And no modified registers are shared, move the instruction to before
  8472. the comparison as this means it can be optimised without worrying
  8473. about the FLAGS register. (CMP/MOV is generated by
  8474. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8475. As long as the second instruction doesn't use the flags or one of the
  8476. registers used by CMP or TEST (also check any references that use the
  8477. registers), then it can be moved prior to the comparison.
  8478. }
  8479. Result := False;
  8480. if not TrySwapMovOp(p, hp1) then
  8481. Exit;
  8482. if taicpu(hp1).opcode = A_LEA then
  8483. { The flags will be overwritten by the CMP/TEST instruction }
  8484. ConvertLEA(taicpu(hp1));
  8485. Result := True;
  8486. { Can we move it one further back? }
  8487. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8488. { Check to see if CMP/TEST is a comparison against zero }
  8489. (
  8490. (
  8491. (taicpu(p).opcode = A_CMP) and
  8492. MatchOperand(taicpu(p).oper[0]^, 0)
  8493. ) or
  8494. (
  8495. (taicpu(p).opcode = A_TEST) and
  8496. (
  8497. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8498. MatchOperand(taicpu(p).oper[0]^, -1)
  8499. )
  8500. )
  8501. ) and
  8502. { These instructions set the zero flag if the result is zero }
  8503. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8504. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8505. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8506. TrySwapMovOp(hp2, hp1);
  8507. end;
  8508. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8509. function IsXCHGAcceptable: Boolean; inline;
  8510. begin
  8511. { Always accept if optimising for size }
  8512. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8513. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8514. than 3, so it becomes a saving compared to three MOVs with two of
  8515. them able to execute simultaneously. [Kit] }
  8516. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8517. end;
  8518. var
  8519. NewRef: TReference;
  8520. hp1, hp2, hp3, hp4: Tai;
  8521. {$ifndef x86_64}
  8522. OperIdx: Integer;
  8523. {$endif x86_64}
  8524. NewInstr : Taicpu;
  8525. NewAligh : Tai_align;
  8526. DestLabel: TAsmLabel;
  8527. TempTracking: TAllUsedRegs;
  8528. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8529. var
  8530. NextInstr: tai;
  8531. begin
  8532. Result := False;
  8533. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8534. if not GetNextInstruction(InputInstr, NextInstr) or
  8535. (
  8536. { The FLAGS register isn't always tracked properly, so do not
  8537. perform this optimisation if a conditional statement follows }
  8538. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8539. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8540. ) then
  8541. begin
  8542. reference_reset(NewRef, 1, []);
  8543. NewRef.base := taicpu(p).oper[0]^.reg;
  8544. NewRef.scalefactor := 1;
  8545. if taicpu(InputInstr).opcode = A_ADD then
  8546. begin
  8547. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8548. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8549. end
  8550. else
  8551. begin
  8552. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8553. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8554. end;
  8555. taicpu(p).opcode := A_LEA;
  8556. taicpu(p).loadref(0, NewRef);
  8557. RemoveInstruction(InputInstr);
  8558. Result := True;
  8559. end;
  8560. end;
  8561. begin
  8562. Result:=false;
  8563. { This optimisation adds an instruction, so only do it for speed }
  8564. if not (cs_opt_size in current_settings.optimizerswitches) and
  8565. MatchOpType(taicpu(p), top_const, top_reg) and
  8566. (taicpu(p).oper[0]^.val = 0) then
  8567. begin
  8568. { To avoid compiler warning }
  8569. DestLabel := nil;
  8570. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8571. InternalError(2021040750);
  8572. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8573. Exit;
  8574. case hp1.typ of
  8575. ait_label:
  8576. begin
  8577. { Change:
  8578. mov $0,%reg mov $0,%reg
  8579. @Lbl1: @Lbl1:
  8580. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8581. je @Lbl2 jne @Lbl2
  8582. To: To:
  8583. mov $0,%reg mov $0,%reg
  8584. jmp @Lbl2 jmp @Lbl3
  8585. (align) (align)
  8586. @Lbl1: @Lbl1:
  8587. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8588. je @Lbl2 je @Lbl2
  8589. @Lbl3: <-- Only if label exists
  8590. (Not if it's optimised for size)
  8591. }
  8592. if not GetNextInstruction(hp1, hp2) then
  8593. Exit;
  8594. if (hp2.typ = ait_instruction) and
  8595. (
  8596. { Register sizes must exactly match }
  8597. (
  8598. (taicpu(hp2).opcode = A_CMP) and
  8599. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8600. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8601. ) or (
  8602. (taicpu(hp2).opcode = A_TEST) and
  8603. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8604. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8605. )
  8606. ) and GetNextInstruction(hp2, hp3) and
  8607. (hp3.typ = ait_instruction) and
  8608. (taicpu(hp3).opcode = A_JCC) and
  8609. (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
  8610. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8611. begin
  8612. { Check condition of jump }
  8613. { Always true? }
  8614. if condition_in(C_E, taicpu(hp3).condition) then
  8615. begin
  8616. { Copy label symbol and obtain matching label entry for the
  8617. conditional jump, as this will be our destination}
  8618. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8619. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8620. Result := True;
  8621. end
  8622. { Always false? }
  8623. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8624. begin
  8625. { This is only worth it if there's a jump to take }
  8626. case hp2.typ of
  8627. ait_instruction:
  8628. begin
  8629. if taicpu(hp2).opcode = A_JMP then
  8630. begin
  8631. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8632. { An unconditional jump follows the conditional jump which will always be false,
  8633. so use this jump's destination for the new jump }
  8634. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8635. Result := True;
  8636. end
  8637. else if taicpu(hp2).opcode = A_JCC then
  8638. begin
  8639. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8640. if condition_in(C_E, taicpu(hp2).condition) then
  8641. begin
  8642. { A second conditional jump follows the conditional jump which will always be false,
  8643. while the second jump is always True, so use this jump's destination for the new jump }
  8644. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8645. Result := True;
  8646. end;
  8647. { Don't risk it if the jump isn't always true (Result remains False) }
  8648. end;
  8649. end;
  8650. else
  8651. { If anything else don't optimise };
  8652. end;
  8653. end;
  8654. if Result then
  8655. begin
  8656. { Just so we have something to insert as a paremeter}
  8657. reference_reset(NewRef, 1, []);
  8658. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8659. { Now actually load the correct parameter (this also
  8660. increases the reference count) }
  8661. NewInstr.loadsymbol(0, DestLabel, 0);
  8662. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8663. begin
  8664. { Get instruction before original label (may not be p under -O3) }
  8665. if not GetLastInstruction(hp1, hp2) then
  8666. { Shouldn't fail here }
  8667. InternalError(2021040701);
  8668. end
  8669. else
  8670. hp2 := p;
  8671. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8672. AsmL.InsertAfter(NewInstr, hp2);
  8673. { Add new alignment field }
  8674. (* AsmL.InsertAfter(
  8675. cai_align.create_max(
  8676. current_settings.alignment.jumpalign,
  8677. current_settings.alignment.jumpalignskipmax
  8678. ),
  8679. NewInstr
  8680. ); *)
  8681. end;
  8682. Exit;
  8683. end;
  8684. end;
  8685. else
  8686. ;
  8687. end;
  8688. end;
  8689. if not GetNextInstruction(p, hp1) then
  8690. Exit;
  8691. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8692. and DoMovCmpMemOpt(p, hp1) then
  8693. begin
  8694. Result := True;
  8695. Exit;
  8696. end
  8697. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8698. begin
  8699. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8700. further, but we can't just put this jump optimisation in pass 1
  8701. because it tends to perform worse when conditional jumps are
  8702. nearby (e.g. when converting CMOV instructions). [Kit] }
  8703. CopyUsedRegs(TempTracking);
  8704. UpdateUsedRegs(tai(p.Next));
  8705. if OptPass2JMP(hp1) then
  8706. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8707. Result := OptPass1MOV(p);
  8708. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8709. returned True and the instruction is still a MOV, thus checking
  8710. the optimisations below }
  8711. { If OptPass2JMP returned False, no optimisations were done to
  8712. the jump and there are no further optimisations that can be done
  8713. to the MOV instruction on this pass }
  8714. { Restore register state }
  8715. RestoreUsedRegs(TempTracking);
  8716. ReleaseUsedRegs(TempTracking);
  8717. end
  8718. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8719. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8720. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8721. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8722. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8723. begin
  8724. { Change:
  8725. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8726. addl/q $x,%reg2 subl/q $x,%reg2
  8727. To:
  8728. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8729. }
  8730. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8731. { be lazy, checking separately for sub would be slightly better }
  8732. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8733. begin
  8734. TransferUsedRegs(TmpUsedRegs);
  8735. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8736. if TryMovArith2Lea(hp1) then
  8737. begin
  8738. Result := True;
  8739. Exit;
  8740. end
  8741. end
  8742. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8743. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8744. { Same as above, but also adds or subtracts to %reg2 in between.
  8745. It's still valid as long as the flags aren't in use }
  8746. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8747. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8748. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8749. { be lazy, checking separately for sub would be slightly better }
  8750. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8751. begin
  8752. TransferUsedRegs(TmpUsedRegs);
  8753. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8754. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8755. if TryMovArith2Lea(hp2) then
  8756. begin
  8757. Result := True;
  8758. Exit;
  8759. end;
  8760. end;
  8761. end
  8762. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8763. {$ifdef x86_64}
  8764. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8765. {$else x86_64}
  8766. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8767. {$endif x86_64}
  8768. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8769. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8770. { mov reg1, reg2 mov reg1, reg2
  8771. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8772. begin
  8773. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8774. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8775. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8776. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8777. TransferUsedRegs(TmpUsedRegs);
  8778. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8779. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8780. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8781. then
  8782. begin
  8783. RemoveCurrentP(p, hp1);
  8784. Result:=true;
  8785. end;
  8786. exit;
  8787. end
  8788. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8789. IsXCHGAcceptable and
  8790. { XCHG doesn't support 8-byte registers }
  8791. (taicpu(p).opsize <> S_B) and
  8792. MatchInstruction(hp1, A_MOV, []) and
  8793. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8794. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8795. GetNextInstruction(hp1, hp2) and
  8796. MatchInstruction(hp2, A_MOV, []) and
  8797. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8798. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8799. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8800. begin
  8801. { mov %reg1,%reg2
  8802. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8803. mov %reg2,%reg3
  8804. (%reg2 not used afterwards)
  8805. Note that xchg takes 3 cycles to execute, and generally mov's take
  8806. only one cycle apiece, but the first two mov's can be executed in
  8807. parallel, only taking 2 cycles overall. Older processors should
  8808. therefore only optimise for size. [Kit]
  8809. }
  8810. TransferUsedRegs(TmpUsedRegs);
  8811. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8812. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8813. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8814. begin
  8815. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8816. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8817. taicpu(hp1).opcode := A_XCHG;
  8818. RemoveCurrentP(p, hp1);
  8819. RemoveInstruction(hp2);
  8820. Result := True;
  8821. Exit;
  8822. end;
  8823. end
  8824. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8825. MatchInstruction(hp1, A_SAR, []) then
  8826. begin
  8827. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8828. begin
  8829. { the use of %edx also covers the opsize being S_L }
  8830. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8831. begin
  8832. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8833. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8834. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8835. begin
  8836. { Change:
  8837. movl %eax,%edx
  8838. sarl $31,%edx
  8839. To:
  8840. cltd
  8841. }
  8842. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8843. RemoveInstruction(hp1);
  8844. taicpu(p).opcode := A_CDQ;
  8845. taicpu(p).opsize := S_NO;
  8846. taicpu(p).clearop(1);
  8847. taicpu(p).clearop(0);
  8848. taicpu(p).ops:=0;
  8849. Result := True;
  8850. end
  8851. else if (cs_opt_size in current_settings.optimizerswitches) and
  8852. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8853. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8854. begin
  8855. { Change:
  8856. movl %edx,%eax
  8857. sarl $31,%edx
  8858. To:
  8859. movl %edx,%eax
  8860. cltd
  8861. Note that this creates a dependency between the two instructions,
  8862. so only perform if optimising for size.
  8863. }
  8864. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8865. taicpu(hp1).opcode := A_CDQ;
  8866. taicpu(hp1).opsize := S_NO;
  8867. taicpu(hp1).clearop(1);
  8868. taicpu(hp1).clearop(0);
  8869. taicpu(hp1).ops:=0;
  8870. end;
  8871. {$ifndef x86_64}
  8872. end
  8873. { Don't bother if CMOV is supported, because a more optimal
  8874. sequence would have been generated for the Abs() intrinsic }
  8875. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8876. { the use of %eax also covers the opsize being S_L }
  8877. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8878. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8879. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8880. GetNextInstruction(hp1, hp2) and
  8881. MatchInstruction(hp2, A_XOR, [S_L]) and
  8882. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8883. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8884. GetNextInstruction(hp2, hp3) and
  8885. MatchInstruction(hp3, A_SUB, [S_L]) and
  8886. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8887. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8888. begin
  8889. { Change:
  8890. movl %eax,%edx
  8891. sarl $31,%eax
  8892. xorl %eax,%edx
  8893. subl %eax,%edx
  8894. (Instruction that uses %edx)
  8895. (%eax deallocated)
  8896. (%edx deallocated)
  8897. To:
  8898. cltd
  8899. xorl %edx,%eax <-- Note the registers have swapped
  8900. subl %edx,%eax
  8901. (Instruction that uses %eax) <-- %eax rather than %edx
  8902. }
  8903. TransferUsedRegs(TmpUsedRegs);
  8904. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8905. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8906. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8907. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8908. begin
  8909. if GetNextInstruction(hp3, hp4) and
  8910. not RegModifiedByInstruction(NR_EDX, hp4) and
  8911. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8912. begin
  8913. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8914. taicpu(p).opcode := A_CDQ;
  8915. taicpu(p).clearop(1);
  8916. taicpu(p).clearop(0);
  8917. taicpu(p).ops:=0;
  8918. RemoveInstruction(hp1);
  8919. taicpu(hp2).loadreg(0, NR_EDX);
  8920. taicpu(hp2).loadreg(1, NR_EAX);
  8921. taicpu(hp3).loadreg(0, NR_EDX);
  8922. taicpu(hp3).loadreg(1, NR_EAX);
  8923. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8924. { Convert references in the following instruction (hp4) from %edx to %eax }
  8925. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8926. with taicpu(hp4).oper[OperIdx]^ do
  8927. case typ of
  8928. top_reg:
  8929. if getsupreg(reg) = RS_EDX then
  8930. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8931. top_ref:
  8932. begin
  8933. if getsupreg(reg) = RS_EDX then
  8934. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8935. if getsupreg(reg) = RS_EDX then
  8936. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8937. end;
  8938. else
  8939. ;
  8940. end;
  8941. end;
  8942. end;
  8943. {$else x86_64}
  8944. end;
  8945. end
  8946. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8947. { the use of %rdx also covers the opsize being S_Q }
  8948. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8949. begin
  8950. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8951. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8952. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8953. begin
  8954. { Change:
  8955. movq %rax,%rdx
  8956. sarq $63,%rdx
  8957. To:
  8958. cqto
  8959. }
  8960. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8961. RemoveInstruction(hp1);
  8962. taicpu(p).opcode := A_CQO;
  8963. taicpu(p).opsize := S_NO;
  8964. taicpu(p).clearop(1);
  8965. taicpu(p).clearop(0);
  8966. taicpu(p).ops:=0;
  8967. Result := True;
  8968. end
  8969. else if (cs_opt_size in current_settings.optimizerswitches) and
  8970. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8971. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8972. begin
  8973. { Change:
  8974. movq %rdx,%rax
  8975. sarq $63,%rdx
  8976. To:
  8977. movq %rdx,%rax
  8978. cqto
  8979. Note that this creates a dependency between the two instructions,
  8980. so only perform if optimising for size.
  8981. }
  8982. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8983. taicpu(hp1).opcode := A_CQO;
  8984. taicpu(hp1).opsize := S_NO;
  8985. taicpu(hp1).clearop(1);
  8986. taicpu(hp1).clearop(0);
  8987. taicpu(hp1).ops:=0;
  8988. {$endif x86_64}
  8989. end;
  8990. end;
  8991. end
  8992. else if MatchInstruction(hp1, A_MOV, []) and
  8993. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8994. { Though "GetNextInstruction" could be factored out, along with
  8995. the instructions that depend on hp2, it is an expensive call that
  8996. should be delayed for as long as possible, hence we do cheaper
  8997. checks first that are likely to be False. [Kit] }
  8998. begin
  8999. if (
  9000. (
  9001. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9002. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9003. (
  9004. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9005. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9006. )
  9007. ) or
  9008. (
  9009. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9010. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9011. (
  9012. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9013. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9014. )
  9015. )
  9016. ) and
  9017. GetNextInstruction(hp1, hp2) and
  9018. MatchInstruction(hp2, A_SAR, []) and
  9019. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9020. begin
  9021. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9022. begin
  9023. { Change:
  9024. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9025. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9026. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9027. To:
  9028. movl r/m,%eax <- Note the change in register
  9029. cltd
  9030. }
  9031. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9032. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9033. taicpu(p).loadreg(1, NR_EAX);
  9034. taicpu(hp1).opcode := A_CDQ;
  9035. taicpu(hp1).clearop(1);
  9036. taicpu(hp1).clearop(0);
  9037. taicpu(hp1).ops:=0;
  9038. RemoveInstruction(hp2);
  9039. (*
  9040. {$ifdef x86_64}
  9041. end
  9042. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9043. { This code sequence does not get generated - however it might become useful
  9044. if and when 128-bit signed integer types make an appearance, so the code
  9045. is kept here for when it is eventually needed. [Kit] }
  9046. (
  9047. (
  9048. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9049. (
  9050. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9051. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9052. )
  9053. ) or
  9054. (
  9055. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9056. (
  9057. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9058. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9059. )
  9060. )
  9061. ) and
  9062. GetNextInstruction(hp1, hp2) and
  9063. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9064. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9065. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9066. begin
  9067. { Change:
  9068. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9069. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9070. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9071. To:
  9072. movq r/m,%rax <- Note the change in register
  9073. cqto
  9074. }
  9075. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9076. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9077. taicpu(p).loadreg(1, NR_RAX);
  9078. taicpu(hp1).opcode := A_CQO;
  9079. taicpu(hp1).clearop(1);
  9080. taicpu(hp1).clearop(0);
  9081. taicpu(hp1).ops:=0;
  9082. RemoveInstruction(hp2);
  9083. {$endif x86_64}
  9084. *)
  9085. end;
  9086. end;
  9087. {$ifdef x86_64}
  9088. end
  9089. else if (taicpu(p).opsize = S_L) and
  9090. (taicpu(p).oper[1]^.typ = top_reg) and
  9091. (
  9092. MatchInstruction(hp1, A_MOV,[]) and
  9093. (taicpu(hp1).opsize = S_L) and
  9094. (taicpu(hp1).oper[1]^.typ = top_reg)
  9095. ) and (
  9096. GetNextInstruction(hp1, hp2) and
  9097. (tai(hp2).typ=ait_instruction) and
  9098. (taicpu(hp2).opsize = S_Q) and
  9099. (
  9100. (
  9101. MatchInstruction(hp2, A_ADD,[]) and
  9102. (taicpu(hp2).opsize = S_Q) and
  9103. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9104. (
  9105. (
  9106. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9107. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9108. ) or (
  9109. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9110. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9111. )
  9112. )
  9113. ) or (
  9114. MatchInstruction(hp2, A_LEA,[]) and
  9115. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9116. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9117. (
  9118. (
  9119. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9120. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9121. ) or (
  9122. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9123. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9124. )
  9125. ) and (
  9126. (
  9127. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9128. ) or (
  9129. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9130. )
  9131. )
  9132. )
  9133. )
  9134. ) and (
  9135. GetNextInstruction(hp2, hp3) and
  9136. MatchInstruction(hp3, A_SHR,[]) and
  9137. (taicpu(hp3).opsize = S_Q) and
  9138. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9139. (taicpu(hp3).oper[0]^.val = 1) and
  9140. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9141. ) then
  9142. begin
  9143. { Change movl x, reg1d movl x, reg1d
  9144. movl y, reg2d movl y, reg2d
  9145. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9146. shrq $1, reg1q shrq $1, reg1q
  9147. ( reg1d and reg2d can be switched around in the first two instructions )
  9148. To movl x, reg1d
  9149. addl y, reg1d
  9150. rcrl $1, reg1d
  9151. This corresponds to the common expression (x + y) shr 1, where
  9152. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9153. smaller code, but won't account for x + y causing an overflow). [Kit]
  9154. }
  9155. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9156. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9157. { Change first MOV command to have the same register as the final output }
  9158. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  9159. else
  9160. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9161. { Change second MOV command to an ADD command. This is easier than
  9162. converting the existing command because it means we don't have to
  9163. touch 'y', which might be a complicated reference, and also the
  9164. fact that the third command might either be ADD or LEA. [Kit] }
  9165. taicpu(hp1).opcode := A_ADD;
  9166. { Delete old ADD/LEA instruction }
  9167. RemoveInstruction(hp2);
  9168. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9169. taicpu(hp3).opcode := A_RCR;
  9170. taicpu(hp3).changeopsize(S_L);
  9171. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9172. {$endif x86_64}
  9173. end;
  9174. if FuncMov2Func(p, hp1) then
  9175. begin
  9176. Result := True;
  9177. Exit;
  9178. end;
  9179. end;
  9180. {$push}
  9181. {$q-}{$r-}
  9182. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9183. var
  9184. ThisReg: TRegister;
  9185. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9186. TargetSubReg: TSubRegister;
  9187. hp1, hp2: tai;
  9188. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9189. { Store list of found instructions so we don't have to call
  9190. GetNextInstructionUsingReg multiple times }
  9191. InstrList: array of taicpu;
  9192. InstrMax, Index: Integer;
  9193. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9194. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9195. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9196. WorkingValue: TCgInt;
  9197. PreMessage: string;
  9198. { Data flow analysis }
  9199. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9200. BitwiseOnly, OrXorUsed,
  9201. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9202. function CheckOverflowConditions: Boolean;
  9203. begin
  9204. Result := True;
  9205. if (TestValSignedMax > SignedUpperLimit) then
  9206. UpperSignedOverflow := True;
  9207. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9208. LowerSignedOverflow := True;
  9209. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9210. LowerUnsignedOverflow := True;
  9211. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9212. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9213. begin
  9214. { Absolute overflow }
  9215. Result := False;
  9216. Exit;
  9217. end;
  9218. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9219. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9220. ShiftDownOverflow := True;
  9221. if (TestValMin < 0) or (TestValMax < 0) then
  9222. begin
  9223. LowerUnsignedOverflow := True;
  9224. UpperUnsignedOverflow := True;
  9225. end;
  9226. end;
  9227. function AdjustInitialLoadAndSize: Boolean;
  9228. begin
  9229. Result := False;
  9230. if not p_removed then
  9231. begin
  9232. if TargetSize = MinSize then
  9233. begin
  9234. { Convert the input MOVZX to a MOV }
  9235. if (taicpu(p).oper[0]^.typ = top_reg) and
  9236. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9237. begin
  9238. { Or remove it completely! }
  9239. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9240. RemoveCurrentP(p);
  9241. p_removed := True;
  9242. end
  9243. else
  9244. begin
  9245. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9246. taicpu(p).opcode := A_MOV;
  9247. taicpu(p).oper[1]^.reg := ThisReg;
  9248. taicpu(p).opsize := TargetSize;
  9249. end;
  9250. Result := True;
  9251. end
  9252. else if TargetSize <> MaxSize then
  9253. begin
  9254. case MaxSize of
  9255. S_L:
  9256. if TargetSize = S_W then
  9257. begin
  9258. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9259. taicpu(p).opsize := S_BW;
  9260. taicpu(p).oper[1]^.reg := ThisReg;
  9261. Result := True;
  9262. end
  9263. else
  9264. InternalError(2020112341);
  9265. S_W:
  9266. if TargetSize = S_L then
  9267. begin
  9268. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9269. taicpu(p).opsize := S_BL;
  9270. taicpu(p).oper[1]^.reg := ThisReg;
  9271. Result := True;
  9272. end
  9273. else
  9274. InternalError(2020112342);
  9275. else
  9276. ;
  9277. end;
  9278. end
  9279. else if not hp1_removed and not RegInUse then
  9280. begin
  9281. { If we have something like:
  9282. movzbl (oper),%regd
  9283. add x, %regd
  9284. movzbl %regb, %regd
  9285. We can reduce the register size to the input of the final
  9286. movzbl instruction. Overflows won't have any effect.
  9287. }
  9288. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9289. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9290. begin
  9291. TargetSize := S_B;
  9292. setsubreg(ThisReg, R_SUBL);
  9293. Result := True;
  9294. end
  9295. else if (taicpu(p).opsize = S_WL) and
  9296. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9297. begin
  9298. TargetSize := S_W;
  9299. setsubreg(ThisReg, R_SUBW);
  9300. Result := True;
  9301. end;
  9302. if Result then
  9303. begin
  9304. { Convert the input MOVZX to a MOV }
  9305. if (taicpu(p).oper[0]^.typ = top_reg) and
  9306. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9307. begin
  9308. { Or remove it completely! }
  9309. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9310. RemoveCurrentP(p);
  9311. p_removed := True;
  9312. end
  9313. else
  9314. begin
  9315. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9316. taicpu(p).opcode := A_MOV;
  9317. taicpu(p).oper[1]^.reg := ThisReg;
  9318. taicpu(p).opsize := TargetSize;
  9319. end;
  9320. end;
  9321. end;
  9322. end;
  9323. end;
  9324. procedure AdjustFinalLoad;
  9325. begin
  9326. if not LowerUnsignedOverflow then
  9327. begin
  9328. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9329. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9330. begin
  9331. { Convert the output MOVZX to a MOV }
  9332. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9333. begin
  9334. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9335. if (MinSize = S_B) or
  9336. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9337. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9338. begin
  9339. { Remove it completely! }
  9340. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9341. { Be careful; if p = hp1 and p was also removed, p
  9342. will become a dangling pointer }
  9343. if p = hp1 then
  9344. begin
  9345. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9346. p_removed := True;
  9347. end
  9348. else
  9349. RemoveInstruction(hp1);
  9350. hp1_removed := True;
  9351. end;
  9352. end
  9353. else
  9354. begin
  9355. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9356. taicpu(hp1).opcode := A_MOV;
  9357. taicpu(hp1).oper[0]^.reg := ThisReg;
  9358. taicpu(hp1).opsize := TargetSize;
  9359. end;
  9360. end
  9361. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9362. begin
  9363. { Need to change the size of the output }
  9364. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9365. taicpu(hp1).oper[0]^.reg := ThisReg;
  9366. taicpu(hp1).opsize := S_BL;
  9367. end;
  9368. end;
  9369. end;
  9370. function CompressInstructions: Boolean;
  9371. var
  9372. LocalIndex: Integer;
  9373. begin
  9374. Result := False;
  9375. { The objective here is to try to find a combination that
  9376. removes one of the MOV/Z instructions. }
  9377. if (
  9378. (taicpu(p).oper[0]^.typ <> top_reg) or
  9379. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9380. ) and
  9381. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9382. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9383. begin
  9384. { Make a preference to remove the second MOVZX instruction }
  9385. case taicpu(hp1).opsize of
  9386. S_BL, S_WL:
  9387. begin
  9388. TargetSize := S_L;
  9389. TargetSubReg := R_SUBD;
  9390. end;
  9391. S_BW:
  9392. begin
  9393. TargetSize := S_W;
  9394. TargetSubReg := R_SUBW;
  9395. end;
  9396. else
  9397. InternalError(2020112302);
  9398. end;
  9399. end
  9400. else
  9401. begin
  9402. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9403. begin
  9404. { Exceeded lower bound but not upper bound }
  9405. TargetSize := MaxSize;
  9406. end
  9407. else if not LowerUnsignedOverflow then
  9408. begin
  9409. { Size didn't exceed lower bound }
  9410. TargetSize := MinSize;
  9411. end
  9412. else
  9413. Exit;
  9414. end;
  9415. case TargetSize of
  9416. S_B:
  9417. TargetSubReg := R_SUBL;
  9418. S_W:
  9419. TargetSubReg := R_SUBW;
  9420. S_L:
  9421. TargetSubReg := R_SUBD;
  9422. else
  9423. InternalError(2020112350);
  9424. end;
  9425. { Update the register to its new size }
  9426. setsubreg(ThisReg, TargetSubReg);
  9427. RegInUse := False;
  9428. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9429. begin
  9430. { Check to see if the active register is used afterwards;
  9431. if not, we can change it and make a saving. }
  9432. TransferUsedRegs(TmpUsedRegs);
  9433. { The target register may be marked as in use to cross
  9434. a jump to a distant label, so exclude it }
  9435. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9436. hp2 := p;
  9437. repeat
  9438. { Explicitly check for the excluded register (don't include the first
  9439. instruction as it may be reading from here }
  9440. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9441. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9442. begin
  9443. RegInUse := True;
  9444. Break;
  9445. end;
  9446. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9447. if not GetNextInstruction(hp2, hp2) then
  9448. InternalError(2020112340);
  9449. until (hp2 = hp1);
  9450. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9451. { We might still be able to get away with this }
  9452. RegInUse := not
  9453. (
  9454. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9455. (hp2.typ = ait_instruction) and
  9456. (
  9457. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9458. instruction that doesn't actually contain ThisReg }
  9459. (cs_opt_level3 in current_settings.optimizerswitches) or
  9460. RegInInstruction(ThisReg, hp2)
  9461. ) and
  9462. RegLoadedWithNewValue(ThisReg, hp2)
  9463. );
  9464. if not RegInUse then
  9465. begin
  9466. { Force the register size to the same as this instruction so it can be removed}
  9467. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9468. begin
  9469. TargetSize := S_L;
  9470. TargetSubReg := R_SUBD;
  9471. end
  9472. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9473. begin
  9474. TargetSize := S_W;
  9475. TargetSubReg := R_SUBW;
  9476. end;
  9477. ThisReg := taicpu(hp1).oper[1]^.reg;
  9478. setsubreg(ThisReg, TargetSubReg);
  9479. RegChanged := True;
  9480. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9481. TransferUsedRegs(TmpUsedRegs);
  9482. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9483. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9484. if p = hp1 then
  9485. begin
  9486. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9487. p_removed := True;
  9488. end
  9489. else
  9490. RemoveInstruction(hp1);
  9491. hp1_removed := True;
  9492. { Instruction will become "mov %reg,%reg" }
  9493. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9494. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9495. begin
  9496. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9497. RemoveCurrentP(p);
  9498. p_removed := True;
  9499. end
  9500. else
  9501. taicpu(p).oper[1]^.reg := ThisReg;
  9502. Result := True;
  9503. end
  9504. else
  9505. begin
  9506. if TargetSize <> MaxSize then
  9507. begin
  9508. { Since the register is in use, we have to force it to
  9509. MaxSize otherwise part of it may become undefined later on }
  9510. TargetSize := MaxSize;
  9511. case TargetSize of
  9512. S_B:
  9513. TargetSubReg := R_SUBL;
  9514. S_W:
  9515. TargetSubReg := R_SUBW;
  9516. S_L:
  9517. TargetSubReg := R_SUBD;
  9518. else
  9519. InternalError(2020112351);
  9520. end;
  9521. setsubreg(ThisReg, TargetSubReg);
  9522. end;
  9523. AdjustFinalLoad;
  9524. end;
  9525. end
  9526. else
  9527. AdjustFinalLoad;
  9528. Result := AdjustInitialLoadAndSize or Result;
  9529. { Now go through every instruction we found and change the
  9530. size. If TargetSize = MaxSize, then almost no changes are
  9531. needed and Result can remain False if it hasn't been set
  9532. yet.
  9533. If RegChanged is True, then the register requires changing
  9534. and so the point about TargetSize = MaxSize doesn't apply. }
  9535. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9536. begin
  9537. for LocalIndex := 0 to InstrMax do
  9538. begin
  9539. { If p_removed is true, then the original MOV/Z was removed
  9540. and removing the AND instruction may not be safe if it
  9541. appears first }
  9542. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9543. InternalError(2020112310);
  9544. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9545. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9546. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9547. InstrList[LocalIndex].opsize := TargetSize;
  9548. end;
  9549. Result := True;
  9550. end;
  9551. end;
  9552. begin
  9553. Result := False;
  9554. p_removed := False;
  9555. hp1_removed := False;
  9556. ThisReg := taicpu(p).oper[1]^.reg;
  9557. { Check for:
  9558. movs/z ###,%ecx (or %cx or %rcx)
  9559. ...
  9560. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9561. (dealloc %ecx)
  9562. Change to:
  9563. mov ###,%cl (if ### = %cl, then remove completely)
  9564. ...
  9565. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9566. }
  9567. if (getsupreg(ThisReg) = RS_ECX) and
  9568. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9569. (hp1.typ = ait_instruction) and
  9570. (
  9571. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9572. instruction that doesn't actually contain ECX }
  9573. (cs_opt_level3 in current_settings.optimizerswitches) or
  9574. RegInInstruction(NR_ECX, hp1) or
  9575. (
  9576. { It's common for the shift/rotate's read/write register to be
  9577. initialised in between, so under -O2 and under, search ahead
  9578. one more instruction
  9579. }
  9580. GetNextInstruction(hp1, hp1) and
  9581. (hp1.typ = ait_instruction) and
  9582. RegInInstruction(NR_ECX, hp1)
  9583. )
  9584. ) and
  9585. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9586. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9587. begin
  9588. TransferUsedRegs(TmpUsedRegs);
  9589. hp2 := p;
  9590. repeat
  9591. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9592. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9593. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9594. begin
  9595. case taicpu(p).opsize of
  9596. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9597. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9598. begin
  9599. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9600. RemoveCurrentP(p);
  9601. end
  9602. else
  9603. begin
  9604. taicpu(p).opcode := A_MOV;
  9605. taicpu(p).opsize := S_B;
  9606. taicpu(p).oper[1]^.reg := NR_CL;
  9607. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9608. end;
  9609. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9610. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9611. begin
  9612. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9613. RemoveCurrentP(p);
  9614. end
  9615. else
  9616. begin
  9617. taicpu(p).opcode := A_MOV;
  9618. taicpu(p).opsize := S_W;
  9619. taicpu(p).oper[1]^.reg := NR_CX;
  9620. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9621. end;
  9622. {$ifdef x86_64}
  9623. S_LQ:
  9624. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9625. begin
  9626. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9627. RemoveCurrentP(p);
  9628. end
  9629. else
  9630. begin
  9631. taicpu(p).opcode := A_MOV;
  9632. taicpu(p).opsize := S_L;
  9633. taicpu(p).oper[1]^.reg := NR_ECX;
  9634. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9635. end;
  9636. {$endif x86_64}
  9637. else
  9638. InternalError(2021120401);
  9639. end;
  9640. Result := True;
  9641. Exit;
  9642. end;
  9643. end;
  9644. { This is anything but quick! }
  9645. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9646. Exit;
  9647. SetLength(InstrList, 0);
  9648. InstrMax := -1;
  9649. case taicpu(p).opsize of
  9650. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9651. begin
  9652. {$if defined(i386) or defined(i8086)}
  9653. { If the target size is 8-bit, make sure we can actually encode it }
  9654. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9655. Exit;
  9656. {$endif i386 or i8086}
  9657. LowerLimit := $FF;
  9658. SignedLowerLimit := $7F;
  9659. SignedLowerLimitBottom := -128;
  9660. MinSize := S_B;
  9661. if taicpu(p).opsize = S_BW then
  9662. begin
  9663. MaxSize := S_W;
  9664. UpperLimit := $FFFF;
  9665. SignedUpperLimit := $7FFF;
  9666. SignedUpperLimitBottom := -32768;
  9667. end
  9668. else
  9669. begin
  9670. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9671. MaxSize := S_L;
  9672. UpperLimit := $FFFFFFFF;
  9673. SignedUpperLimit := $7FFFFFFF;
  9674. SignedUpperLimitBottom := -2147483648;
  9675. end;
  9676. end;
  9677. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9678. begin
  9679. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9680. LowerLimit := $FFFF;
  9681. SignedLowerLimit := $7FFF;
  9682. SignedLowerLimitBottom := -32768;
  9683. UpperLimit := $FFFFFFFF;
  9684. SignedUpperLimit := $7FFFFFFF;
  9685. SignedUpperLimitBottom := -2147483648;
  9686. MinSize := S_W;
  9687. MaxSize := S_L;
  9688. end;
  9689. {$ifdef x86_64}
  9690. S_LQ:
  9691. begin
  9692. { Both the lower and upper limits are set to 32-bit. If a limit
  9693. is breached, then optimisation is impossible }
  9694. LowerLimit := $FFFFFFFF;
  9695. SignedLowerLimit := $7FFFFFFF;
  9696. SignedLowerLimitBottom := -2147483648;
  9697. UpperLimit := $FFFFFFFF;
  9698. SignedUpperLimit := $7FFFFFFF;
  9699. SignedUpperLimitBottom := -2147483648;
  9700. MinSize := S_L;
  9701. MaxSize := S_L;
  9702. end;
  9703. {$endif x86_64}
  9704. else
  9705. InternalError(2020112301);
  9706. end;
  9707. TestValMin := 0;
  9708. TestValMax := LowerLimit;
  9709. TestValSignedMax := SignedLowerLimit;
  9710. TryShiftDownLimit := LowerLimit;
  9711. TryShiftDown := S_NO;
  9712. ShiftDownOverflow := False;
  9713. RegChanged := False;
  9714. BitwiseOnly := True;
  9715. OrXorUsed := False;
  9716. UpperSignedOverflow := False;
  9717. LowerSignedOverflow := False;
  9718. UpperUnsignedOverflow := False;
  9719. LowerUnsignedOverflow := False;
  9720. hp1 := p;
  9721. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9722. (hp1.typ = ait_instruction) and
  9723. (
  9724. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9725. instruction that doesn't actually contain ThisReg }
  9726. (cs_opt_level3 in current_settings.optimizerswitches) or
  9727. { This allows this Movx optimisation to work through the SETcc instructions
  9728. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9729. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9730. skip over these SETcc instructions). }
  9731. (taicpu(hp1).opcode = A_SETcc) or
  9732. RegInInstruction(ThisReg, hp1)
  9733. ) do
  9734. begin
  9735. case taicpu(hp1).opcode of
  9736. A_INC,A_DEC:
  9737. begin
  9738. { Has to be an exact match on the register }
  9739. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9740. Break;
  9741. if taicpu(hp1).opcode = A_INC then
  9742. begin
  9743. Inc(TestValMin);
  9744. Inc(TestValMax);
  9745. Inc(TestValSignedMax);
  9746. end
  9747. else
  9748. begin
  9749. Dec(TestValMin);
  9750. Dec(TestValMax);
  9751. Dec(TestValSignedMax);
  9752. end;
  9753. end;
  9754. A_TEST, A_CMP:
  9755. begin
  9756. if (
  9757. { Too high a risk of non-linear behaviour that breaks DFA
  9758. here, unless it's cmp $0,%reg, which is equivalent to
  9759. test %reg,%reg }
  9760. OrXorUsed and
  9761. (taicpu(hp1).opcode = A_CMP) and
  9762. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9763. ) or
  9764. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9765. { Has to be an exact match on the register }
  9766. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9767. (
  9768. { Permit "test %reg,%reg" }
  9769. (taicpu(hp1).opcode = A_TEST) and
  9770. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9771. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9772. ) or
  9773. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9774. { Make sure the comparison value is not smaller than the
  9775. smallest allowed signed value for the minimum size (e.g.
  9776. -128 for 8-bit) }
  9777. not (
  9778. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9779. { Is it in the negative range? }
  9780. (
  9781. (taicpu(hp1).oper[0]^.val < 0) and
  9782. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9783. )
  9784. ) then
  9785. Break;
  9786. { Check to see if the active register is used afterwards }
  9787. TransferUsedRegs(TmpUsedRegs);
  9788. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9789. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9790. begin
  9791. { Make sure the comparison or any previous instructions
  9792. hasn't pushed the test values outside of the range of
  9793. MinSize }
  9794. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9795. begin
  9796. { Exceeded lower bound but not upper bound }
  9797. Exit;
  9798. end
  9799. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9800. begin
  9801. { Size didn't exceed lower bound }
  9802. TargetSize := MinSize;
  9803. end
  9804. else
  9805. Break;
  9806. case TargetSize of
  9807. S_B:
  9808. TargetSubReg := R_SUBL;
  9809. S_W:
  9810. TargetSubReg := R_SUBW;
  9811. S_L:
  9812. TargetSubReg := R_SUBD;
  9813. else
  9814. InternalError(2021051002);
  9815. end;
  9816. if TargetSize <> MaxSize then
  9817. begin
  9818. { Update the register to its new size }
  9819. setsubreg(ThisReg, TargetSubReg);
  9820. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9821. taicpu(hp1).oper[1]^.reg := ThisReg;
  9822. taicpu(hp1).opsize := TargetSize;
  9823. { Convert the input MOVZX to a MOV if necessary }
  9824. AdjustInitialLoadAndSize;
  9825. if (InstrMax >= 0) then
  9826. begin
  9827. for Index := 0 to InstrMax do
  9828. begin
  9829. { If p_removed is true, then the original MOV/Z was removed
  9830. and removing the AND instruction may not be safe if it
  9831. appears first }
  9832. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9833. InternalError(2020112311);
  9834. if InstrList[Index].oper[0]^.typ = top_reg then
  9835. InstrList[Index].oper[0]^.reg := ThisReg;
  9836. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9837. InstrList[Index].opsize := MinSize;
  9838. end;
  9839. end;
  9840. Result := True;
  9841. end;
  9842. Exit;
  9843. end;
  9844. end;
  9845. A_SETcc:
  9846. begin
  9847. { This allows this Movx optimisation to work through the SETcc instructions
  9848. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9849. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9850. skip over these SETcc instructions). }
  9851. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9852. { Of course, break out if the current register is used }
  9853. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9854. Break
  9855. else
  9856. { We must use Continue so the instruction doesn't get added
  9857. to InstrList }
  9858. Continue;
  9859. end;
  9860. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9861. begin
  9862. if
  9863. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9864. { Has to be an exact match on the register }
  9865. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9866. (
  9867. (
  9868. (taicpu(hp1).oper[0]^.typ = top_const) and
  9869. (
  9870. (
  9871. (taicpu(hp1).opcode = A_SHL) and
  9872. (
  9873. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9874. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9875. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9876. )
  9877. ) or (
  9878. (taicpu(hp1).opcode <> A_SHL) and
  9879. (
  9880. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9881. { Is it in the negative range? }
  9882. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9883. )
  9884. )
  9885. )
  9886. ) or (
  9887. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9888. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9889. )
  9890. ) then
  9891. Break;
  9892. { Only process OR and XOR if there are only bitwise operations,
  9893. since otherwise they can too easily fool the data flow
  9894. analysis (they can cause non-linear behaviour) }
  9895. case taicpu(hp1).opcode of
  9896. A_ADD:
  9897. begin
  9898. if OrXorUsed then
  9899. { Too high a risk of non-linear behaviour that breaks DFA here }
  9900. Break
  9901. else
  9902. BitwiseOnly := False;
  9903. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9904. begin
  9905. TestValMin := TestValMin * 2;
  9906. TestValMax := TestValMax * 2;
  9907. TestValSignedMax := TestValSignedMax * 2;
  9908. end
  9909. else
  9910. begin
  9911. WorkingValue := taicpu(hp1).oper[0]^.val;
  9912. TestValMin := TestValMin + WorkingValue;
  9913. TestValMax := TestValMax + WorkingValue;
  9914. TestValSignedMax := TestValSignedMax + WorkingValue;
  9915. end;
  9916. end;
  9917. A_SUB:
  9918. begin
  9919. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9920. begin
  9921. TestValMin := 0;
  9922. TestValMax := 0;
  9923. TestValSignedMax := 0;
  9924. end
  9925. else
  9926. begin
  9927. if OrXorUsed then
  9928. { Too high a risk of non-linear behaviour that breaks DFA here }
  9929. Break
  9930. else
  9931. BitwiseOnly := False;
  9932. WorkingValue := taicpu(hp1).oper[0]^.val;
  9933. TestValMin := TestValMin - WorkingValue;
  9934. TestValMax := TestValMax - WorkingValue;
  9935. TestValSignedMax := TestValSignedMax - WorkingValue;
  9936. end;
  9937. end;
  9938. A_AND:
  9939. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9940. begin
  9941. { we might be able to go smaller if AND appears first }
  9942. if InstrMax = -1 then
  9943. case MinSize of
  9944. S_B:
  9945. ;
  9946. S_W:
  9947. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9948. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9949. begin
  9950. TryShiftDown := S_B;
  9951. TryShiftDownLimit := $FF;
  9952. end;
  9953. S_L:
  9954. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9955. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9956. begin
  9957. TryShiftDown := S_B;
  9958. TryShiftDownLimit := $FF;
  9959. end
  9960. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9961. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9962. begin
  9963. TryShiftDown := S_W;
  9964. TryShiftDownLimit := $FFFF;
  9965. end;
  9966. else
  9967. InternalError(2020112320);
  9968. end;
  9969. WorkingValue := taicpu(hp1).oper[0]^.val;
  9970. TestValMin := TestValMin and WorkingValue;
  9971. TestValMax := TestValMax and WorkingValue;
  9972. TestValSignedMax := TestValSignedMax and WorkingValue;
  9973. end;
  9974. A_OR:
  9975. begin
  9976. if not BitwiseOnly then
  9977. Break;
  9978. OrXorUsed := True;
  9979. WorkingValue := taicpu(hp1).oper[0]^.val;
  9980. TestValMin := TestValMin or WorkingValue;
  9981. TestValMax := TestValMax or WorkingValue;
  9982. TestValSignedMax := TestValSignedMax or WorkingValue;
  9983. end;
  9984. A_XOR:
  9985. begin
  9986. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9987. begin
  9988. TestValMin := 0;
  9989. TestValMax := 0;
  9990. TestValSignedMax := 0;
  9991. end
  9992. else
  9993. begin
  9994. if not BitwiseOnly then
  9995. Break;
  9996. OrXorUsed := True;
  9997. WorkingValue := taicpu(hp1).oper[0]^.val;
  9998. TestValMin := TestValMin xor WorkingValue;
  9999. TestValMax := TestValMax xor WorkingValue;
  10000. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10001. end;
  10002. end;
  10003. A_SHL:
  10004. begin
  10005. BitwiseOnly := False;
  10006. WorkingValue := taicpu(hp1).oper[0]^.val;
  10007. TestValMin := TestValMin shl WorkingValue;
  10008. TestValMax := TestValMax shl WorkingValue;
  10009. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10010. end;
  10011. A_SHR,
  10012. { The first instruction was MOVZX, so the value won't be negative }
  10013. A_SAR:
  10014. begin
  10015. if InstrMax <> -1 then
  10016. BitwiseOnly := False
  10017. else
  10018. { we might be able to go smaller if SHR appears first }
  10019. case MinSize of
  10020. S_B:
  10021. ;
  10022. S_W:
  10023. if (taicpu(hp1).oper[0]^.val >= 8) then
  10024. begin
  10025. TryShiftDown := S_B;
  10026. TryShiftDownLimit := $FF;
  10027. TryShiftDownSignedLimit := $7F;
  10028. TryShiftDownSignedLimitLower := -128;
  10029. end;
  10030. S_L:
  10031. if (taicpu(hp1).oper[0]^.val >= 24) then
  10032. begin
  10033. TryShiftDown := S_B;
  10034. TryShiftDownLimit := $FF;
  10035. TryShiftDownSignedLimit := $7F;
  10036. TryShiftDownSignedLimitLower := -128;
  10037. end
  10038. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10039. begin
  10040. TryShiftDown := S_W;
  10041. TryShiftDownLimit := $FFFF;
  10042. TryShiftDownSignedLimit := $7FFF;
  10043. TryShiftDownSignedLimitLower := -32768;
  10044. end;
  10045. else
  10046. InternalError(2020112321);
  10047. end;
  10048. WorkingValue := taicpu(hp1).oper[0]^.val;
  10049. if taicpu(hp1).opcode = A_SAR then
  10050. begin
  10051. TestValMin := SarInt64(TestValMin, WorkingValue);
  10052. TestValMax := SarInt64(TestValMax, WorkingValue);
  10053. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10054. end
  10055. else
  10056. begin
  10057. TestValMin := TestValMin shr WorkingValue;
  10058. TestValMax := TestValMax shr WorkingValue;
  10059. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10060. end;
  10061. end;
  10062. else
  10063. InternalError(2020112303);
  10064. end;
  10065. end;
  10066. (*
  10067. A_IMUL:
  10068. case taicpu(hp1).ops of
  10069. 2:
  10070. begin
  10071. if not MatchOpType(hp1, top_reg, top_reg) or
  10072. { Has to be an exact match on the register }
  10073. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10074. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10075. Break;
  10076. TestValMin := TestValMin * TestValMin;
  10077. TestValMax := TestValMax * TestValMax;
  10078. TestValSignedMax := TestValSignedMax * TestValMax;
  10079. end;
  10080. 3:
  10081. begin
  10082. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10083. { Has to be an exact match on the register }
  10084. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10085. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10086. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10087. { Is it in the negative range? }
  10088. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10089. Break;
  10090. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10091. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10092. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10093. end;
  10094. else
  10095. Break;
  10096. end;
  10097. A_IDIV:
  10098. case taicpu(hp1).ops of
  10099. 3:
  10100. begin
  10101. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10102. { Has to be an exact match on the register }
  10103. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10104. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10105. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10106. { Is it in the negative range? }
  10107. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10108. Break;
  10109. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10110. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10111. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10112. end;
  10113. else
  10114. Break;
  10115. end;
  10116. *)
  10117. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10118. begin
  10119. { If there are no instructions in between, then we might be able to make a saving }
  10120. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10121. Break;
  10122. { We have something like:
  10123. movzbw %dl,%dx
  10124. ...
  10125. movswl %dx,%edx
  10126. Change the latter to a zero-extension then enter the
  10127. A_MOVZX case branch.
  10128. }
  10129. {$ifdef x86_64}
  10130. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10131. begin
  10132. { this becomes a zero extension from 32-bit to 64-bit, but
  10133. the upper 32 bits are already zero, so just delete the
  10134. instruction }
  10135. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10136. RemoveInstruction(hp1);
  10137. Result := True;
  10138. Exit;
  10139. end
  10140. else
  10141. {$endif x86_64}
  10142. begin
  10143. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10144. taicpu(hp1).opcode := A_MOVZX;
  10145. {$ifdef x86_64}
  10146. case taicpu(hp1).opsize of
  10147. S_BQ:
  10148. begin
  10149. taicpu(hp1).opsize := S_BL;
  10150. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10151. end;
  10152. S_WQ:
  10153. begin
  10154. taicpu(hp1).opsize := S_WL;
  10155. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10156. end;
  10157. S_LQ:
  10158. begin
  10159. taicpu(hp1).opcode := A_MOV;
  10160. taicpu(hp1).opsize := S_L;
  10161. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10162. { In this instance, we need to break out because the
  10163. instruction is no longer MOVZX or MOVSXD }
  10164. Result := True;
  10165. Exit;
  10166. end;
  10167. else
  10168. ;
  10169. end;
  10170. {$endif x86_64}
  10171. Result := CompressInstructions;
  10172. Exit;
  10173. end;
  10174. end;
  10175. A_MOVZX:
  10176. begin
  10177. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10178. Break;
  10179. if (InstrMax = -1) then
  10180. begin
  10181. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10182. begin
  10183. { Optimise around i40003 }
  10184. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10185. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10186. {$ifndef x86_64}
  10187. and (
  10188. (taicpu(p).oper[0]^.typ <> top_reg) or
  10189. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10190. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10191. )
  10192. {$endif not x86_64}
  10193. then
  10194. begin
  10195. if (taicpu(p).oper[0]^.typ = top_reg) then
  10196. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10197. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10198. taicpu(p).opsize := S_BL;
  10199. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10200. RemoveInstruction(hp1);
  10201. Result := True;
  10202. Exit;
  10203. end;
  10204. end
  10205. else
  10206. begin
  10207. { Will return false if the second parameter isn't ThisReg
  10208. (can happen on -O2 and under) }
  10209. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10210. begin
  10211. { The two MOVZX instructions are adjacent, so remove the first one }
  10212. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10213. RemoveCurrentP(p);
  10214. Result := True;
  10215. Exit;
  10216. end;
  10217. Break;
  10218. end;
  10219. end;
  10220. Result := CompressInstructions;
  10221. Exit;
  10222. end;
  10223. else
  10224. { This includes ADC, SBB and IDIV }
  10225. Break;
  10226. end;
  10227. if not CheckOverflowConditions then
  10228. Break;
  10229. { Contains highest index (so instruction count - 1) }
  10230. Inc(InstrMax);
  10231. if InstrMax > High(InstrList) then
  10232. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10233. InstrList[InstrMax] := taicpu(hp1);
  10234. end;
  10235. end;
  10236. {$pop}
  10237. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10238. var
  10239. hp1 : tai;
  10240. begin
  10241. Result:=false;
  10242. if (taicpu(p).ops >= 2) and
  10243. ((taicpu(p).oper[0]^.typ = top_const) or
  10244. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10245. (taicpu(p).oper[1]^.typ = top_reg) and
  10246. ((taicpu(p).ops = 2) or
  10247. ((taicpu(p).oper[2]^.typ = top_reg) and
  10248. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10249. GetLastInstruction(p,hp1) and
  10250. MatchInstruction(hp1,A_MOV,[]) and
  10251. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10252. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10253. begin
  10254. TransferUsedRegs(TmpUsedRegs);
  10255. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10256. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10257. { change
  10258. mov reg1,reg2
  10259. imul y,reg2 to imul y,reg1,reg2 }
  10260. begin
  10261. taicpu(p).ops := 3;
  10262. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10263. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10264. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10265. RemoveInstruction(hp1);
  10266. result:=true;
  10267. end;
  10268. end;
  10269. end;
  10270. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10271. var
  10272. ThisLabel: TAsmLabel;
  10273. begin
  10274. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10275. ThisLabel.decrefs;
  10276. taicpu(p).condition := C_None;
  10277. taicpu(p).opcode := A_RET;
  10278. taicpu(p).is_jmp := false;
  10279. taicpu(p).ops := taicpu(ret_p).ops;
  10280. case taicpu(ret_p).ops of
  10281. 0:
  10282. taicpu(p).clearop(0);
  10283. 1:
  10284. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10285. else
  10286. internalerror(2016041301);
  10287. end;
  10288. { If the original label is now dead, it might turn out that the label
  10289. immediately follows p. As a result, everything beyond it, which will
  10290. be just some final register configuration and a RET instruction, is
  10291. now dead code. [Kit] }
  10292. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10293. running RemoveDeadCodeAfterJump for each RET instruction, because
  10294. this optimisation rarely happens and most RETs appear at the end of
  10295. routines where there is nothing that can be stripped. [Kit] }
  10296. if not ThisLabel.is_used then
  10297. RemoveDeadCodeAfterJump(p);
  10298. end;
  10299. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10300. var
  10301. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10302. Unconditional, PotentialModified: Boolean;
  10303. OperPtr: POper;
  10304. NewRef: TReference;
  10305. InstrList: array of taicpu;
  10306. InstrMax, Index: Integer;
  10307. const
  10308. {$ifdef DEBUG_AOPTCPU}
  10309. SNoFlags: shortstring = ' so the flags aren''t modified';
  10310. {$else DEBUG_AOPTCPU}
  10311. SNoFlags = '';
  10312. {$endif DEBUG_AOPTCPU}
  10313. begin
  10314. Result:=false;
  10315. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10316. begin
  10317. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10318. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10319. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10320. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10321. GetNextInstruction(hp1, hp2) and
  10322. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10323. { Change from: To:
  10324. set(C) %reg j(~C) label
  10325. test %reg,%reg/cmp $0,%reg
  10326. je label
  10327. set(C) %reg j(C) label
  10328. test %reg,%reg/cmp $0,%reg
  10329. jne label
  10330. (Also do something similar with sete/setne instead of je/jne)
  10331. }
  10332. begin
  10333. { Before we do anything else, we need to check the instructions
  10334. in between SETcc and TEST to make sure they don't modify the
  10335. FLAGS register - if -O2 or under, there won't be any
  10336. instructions between SET and TEST }
  10337. TransferUsedRegs(TmpUsedRegs);
  10338. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10339. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10340. begin
  10341. next := p;
  10342. SetLength(InstrList, 0);
  10343. InstrMax := -1;
  10344. PotentialModified := False;
  10345. { Make a note of every instruction that modifies the FLAGS
  10346. register }
  10347. while GetNextInstruction(next, next) and (next <> hp1) do
  10348. begin
  10349. if next.typ <> ait_instruction then
  10350. { GetNextInstructionUsingReg should have returned False }
  10351. InternalError(2021051701);
  10352. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10353. begin
  10354. case taicpu(next).opcode of
  10355. A_SETcc,
  10356. A_CMOVcc,
  10357. A_Jcc:
  10358. begin
  10359. if PotentialModified then
  10360. { Not safe because the flags were modified earlier }
  10361. Exit
  10362. else
  10363. { Condition is the same as the initial SETcc, so this is safe
  10364. (don't add to instruction list though) }
  10365. Continue;
  10366. end;
  10367. A_ADD:
  10368. begin
  10369. if (taicpu(next).opsize = S_B) or
  10370. { LEA doesn't support 8-bit operands }
  10371. (taicpu(next).oper[1]^.typ <> top_reg) or
  10372. { Must write to a register }
  10373. (taicpu(next).oper[0]^.typ = top_ref) then
  10374. { Require a constant or a register }
  10375. Exit;
  10376. PotentialModified := True;
  10377. end;
  10378. A_SUB:
  10379. begin
  10380. if (taicpu(next).opsize = S_B) or
  10381. { LEA doesn't support 8-bit operands }
  10382. (taicpu(next).oper[1]^.typ <> top_reg) or
  10383. { Must write to a register }
  10384. (taicpu(next).oper[0]^.typ <> top_const) or
  10385. (taicpu(next).oper[0]^.val = $80000000) then
  10386. { Can't subtract a register with LEA - also
  10387. check that the value isn't -2^31, as this
  10388. can't be negated }
  10389. Exit;
  10390. PotentialModified := True;
  10391. end;
  10392. A_SAL,
  10393. A_SHL:
  10394. begin
  10395. if (taicpu(next).opsize = S_B) or
  10396. { LEA doesn't support 8-bit operands }
  10397. (taicpu(next).oper[1]^.typ <> top_reg) or
  10398. { Must write to a register }
  10399. (taicpu(next).oper[0]^.typ <> top_const) or
  10400. (taicpu(next).oper[0]^.val < 0) or
  10401. (taicpu(next).oper[0]^.val > 3) then
  10402. Exit;
  10403. PotentialModified := True;
  10404. end;
  10405. A_IMUL:
  10406. begin
  10407. if (taicpu(next).ops <> 3) or
  10408. (taicpu(next).oper[1]^.typ <> top_reg) or
  10409. { Must write to a register }
  10410. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10411. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10412. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10413. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10414. Exit
  10415. else
  10416. PotentialModified := True;
  10417. end;
  10418. else
  10419. { Don't know how to change this, so abort }
  10420. Exit;
  10421. end;
  10422. { Contains highest index (so instruction count - 1) }
  10423. Inc(InstrMax);
  10424. if InstrMax > High(InstrList) then
  10425. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10426. InstrList[InstrMax] := taicpu(next);
  10427. end;
  10428. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10429. end;
  10430. if not Assigned(next) or (next <> hp1) then
  10431. { It should be equal to hp1 }
  10432. InternalError(2021051702);
  10433. { Cycle through each instruction and check to see if we can
  10434. change them to versions that don't modify the flags }
  10435. if (InstrMax >= 0) then
  10436. begin
  10437. for Index := 0 to InstrMax do
  10438. case InstrList[Index].opcode of
  10439. A_ADD:
  10440. begin
  10441. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10442. InstrList[Index].opcode := A_LEA;
  10443. reference_reset(NewRef, 1, []);
  10444. NewRef.base := InstrList[Index].oper[1]^.reg;
  10445. if InstrList[Index].oper[0]^.typ = top_reg then
  10446. begin
  10447. NewRef.index := InstrList[Index].oper[0]^.reg;
  10448. NewRef.scalefactor := 1;
  10449. end
  10450. else
  10451. NewRef.offset := InstrList[Index].oper[0]^.val;
  10452. InstrList[Index].loadref(0, NewRef);
  10453. end;
  10454. A_SUB:
  10455. begin
  10456. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10457. InstrList[Index].opcode := A_LEA;
  10458. reference_reset(NewRef, 1, []);
  10459. NewRef.base := InstrList[Index].oper[1]^.reg;
  10460. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10461. InstrList[Index].loadref(0, NewRef);
  10462. end;
  10463. A_SHL,
  10464. A_SAL:
  10465. begin
  10466. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10467. InstrList[Index].opcode := A_LEA;
  10468. reference_reset(NewRef, 1, []);
  10469. NewRef.index := InstrList[Index].oper[1]^.reg;
  10470. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10471. InstrList[Index].loadref(0, NewRef);
  10472. end;
  10473. A_IMUL:
  10474. begin
  10475. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10476. InstrList[Index].opcode := A_LEA;
  10477. reference_reset(NewRef, 1, []);
  10478. NewRef.index := InstrList[Index].oper[1]^.reg;
  10479. case InstrList[Index].oper[0]^.val of
  10480. 2, 4, 8:
  10481. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10482. else {3, 5 and 9}
  10483. begin
  10484. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10485. NewRef.base := InstrList[Index].oper[1]^.reg;
  10486. end;
  10487. end;
  10488. InstrList[Index].loadref(0, NewRef);
  10489. end;
  10490. else
  10491. InternalError(2021051710);
  10492. end;
  10493. end;
  10494. { Mark the FLAGS register as used across this whole block }
  10495. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10496. end;
  10497. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10498. JumpC := taicpu(hp2).condition;
  10499. Unconditional := False;
  10500. if conditions_equal(JumpC, C_E) then
  10501. SetC := inverse_cond(taicpu(p).condition)
  10502. else if conditions_equal(JumpC, C_NE) then
  10503. SetC := taicpu(p).condition
  10504. else
  10505. { We've got something weird here (and inefficent) }
  10506. begin
  10507. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10508. SetC := C_NONE;
  10509. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10510. if condition_in(C_AE, JumpC) then
  10511. Unconditional := True
  10512. else
  10513. { Not sure what to do with this jump - drop out }
  10514. Exit;
  10515. end;
  10516. RemoveInstruction(hp1);
  10517. if Unconditional then
  10518. MakeUnconditional(taicpu(hp2))
  10519. else
  10520. begin
  10521. if SetC = C_NONE then
  10522. InternalError(2018061402);
  10523. taicpu(hp2).SetCondition(SetC);
  10524. end;
  10525. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10526. TmpUsedRegs }
  10527. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10528. begin
  10529. RemoveCurrentp(p, hp2);
  10530. if taicpu(hp2).opcode = A_SETcc then
  10531. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10532. else
  10533. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10534. end
  10535. else
  10536. if taicpu(hp2).opcode = A_SETcc then
  10537. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10538. else
  10539. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10540. Result := True;
  10541. end
  10542. else if
  10543. { Make sure the instructions are adjacent }
  10544. (
  10545. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10546. GetNextInstruction(p, hp1)
  10547. ) and
  10548. MatchInstruction(hp1, A_MOV, [S_B]) and
  10549. { Writing to memory is allowed }
  10550. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10551. begin
  10552. {
  10553. Watch out for sequences such as:
  10554. set(c)b %regb
  10555. movb %regb,(ref)
  10556. movb $0,1(ref)
  10557. movb $0,2(ref)
  10558. movb $0,3(ref)
  10559. Much more efficient to turn it into:
  10560. movl $0,%regl
  10561. set(c)b %regb
  10562. movl %regl,(ref)
  10563. Or:
  10564. set(c)b %regb
  10565. movzbl %regb,%regl
  10566. movl %regl,(ref)
  10567. }
  10568. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10569. GetNextInstruction(hp1, hp2) and
  10570. MatchInstruction(hp2, A_MOV, [S_B]) and
  10571. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10572. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10573. begin
  10574. { Don't do anything else except set Result to True }
  10575. end
  10576. else
  10577. begin
  10578. if taicpu(p).oper[0]^.typ = top_reg then
  10579. begin
  10580. TransferUsedRegs(TmpUsedRegs);
  10581. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10582. end;
  10583. { If it's not a register, it's a memory address }
  10584. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10585. begin
  10586. { Even if the register is still in use, we can minimise the
  10587. pipeline stall by changing the MOV into another SETcc. }
  10588. taicpu(hp1).opcode := A_SETcc;
  10589. taicpu(hp1).condition := taicpu(p).condition;
  10590. if taicpu(hp1).oper[1]^.typ = top_ref then
  10591. begin
  10592. { Swapping the operand pointers like this is probably a
  10593. bit naughty, but it is far faster than using loadoper
  10594. to transfer the reference from oper[1] to oper[0] if
  10595. you take into account the extra procedure calls and
  10596. the memory allocation and deallocation required }
  10597. OperPtr := taicpu(hp1).oper[1];
  10598. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10599. taicpu(hp1).oper[0] := OperPtr;
  10600. end
  10601. else
  10602. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10603. taicpu(hp1).clearop(1);
  10604. taicpu(hp1).ops := 1;
  10605. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10606. end
  10607. else
  10608. begin
  10609. if taicpu(hp1).oper[1]^.typ = top_reg then
  10610. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10611. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10612. RemoveInstruction(hp1);
  10613. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10614. end
  10615. end;
  10616. Result := True;
  10617. end;
  10618. end;
  10619. end;
  10620. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  10621. var
  10622. hp2, hp3, pFirstMOV, pLastMOV, pCMOV: tai;
  10623. TargetReg: TRegister;
  10624. condition, inverted_condition: TAsmCond;
  10625. FoundMOV: Boolean;
  10626. begin
  10627. Result := False;
  10628. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  10629. create the most optimial instructions possible due to limited
  10630. register availability, and there are situations where two
  10631. complementary "simple" CMOV blocks are created which, after the fact
  10632. can be merged into a "double" block. For example:
  10633. movw $257,%ax
  10634. movw $2,%r8w
  10635. xorl r9d,%r9d
  10636. testw $16,18(%rcx)
  10637. cmovew %ax,%dx
  10638. cmovew %r8w,%bx
  10639. cmovel %r9d,%r14d
  10640. movw $1283,%ax
  10641. movw $4,%r8w
  10642. movl $9,%r9d
  10643. cmovnew %ax,%dx
  10644. cmovnew %r8w,%bx
  10645. cmovnel %r9d,%r14d
  10646. The CMOVNE instructions at the end can be removed, and the
  10647. destination registers copied into the MOV instructions directly
  10648. above them, before finally being moved to before the first CMOVE
  10649. instructions, to produce:
  10650. movw $257,%ax
  10651. movw $2,%r8w
  10652. xorl r9d,%r9d
  10653. testw $16,18(%rcx)
  10654. movw $1283,%dx
  10655. movw $4,%bx
  10656. movl $9,%r14d
  10657. cmovew %ax,%dx
  10658. cmovew %r8w,%bx
  10659. cmovel %r9d,%r14d
  10660. Which can then be later optimised to:
  10661. movw $257,%ax
  10662. movw $2,%r8w
  10663. xorl r9d,%r9d
  10664. movw $1283,%dx
  10665. movw $4,%bx
  10666. movl $9,%r14d
  10667. testw $16,18(%rcx)
  10668. cmovew %ax,%dx
  10669. cmovew %r8w,%bx
  10670. cmovel %r9d,%r14d
  10671. }
  10672. TargetReg := taicpu(hp1).oper[1]^.reg;
  10673. condition := taicpu(hp1).condition;
  10674. inverted_condition := inverse_cond(condition);
  10675. pFirstMov := nil;
  10676. pLastMov := nil;
  10677. pCMOV := nil;
  10678. if (
  10679. (taicpu(hp1).oper[0]^.typ = top_reg) or
  10680. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  10681. ) then
  10682. begin
  10683. { We have to tread carefully here, hence why we're not using
  10684. GetNextInstructionUsingReg... we can only accept MOV and other
  10685. CMOV instructions. Anything else and we must drop out}
  10686. hp2 := hp1;
  10687. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) and (hp2.typ = ait_instruction) do
  10688. begin
  10689. case taicpu(hp2).opcode of
  10690. A_MOV:
  10691. begin
  10692. if not Assigned(pFirstMov) then
  10693. pFirstMov := hp2;
  10694. pLastMOV := hp2;
  10695. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  10696. { Something different - drop out }
  10697. Exit;
  10698. { Otherwise, leave it for now }
  10699. end;
  10700. A_CMOVcc:
  10701. begin
  10702. if taicpu(hp2).condition = inverted_condition then
  10703. begin
  10704. { We found what we're looking for }
  10705. if taicpu(hp2).oper[1]^.reg = TargetReg then
  10706. begin
  10707. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  10708. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  10709. begin
  10710. pCMOV := hp2;
  10711. Break;
  10712. end
  10713. else
  10714. { Unsafe reference - drop out }
  10715. Exit;
  10716. end;
  10717. end
  10718. else if taicpu(hp2).condition <> condition then
  10719. { Something weird - drop out }
  10720. Exit;
  10721. end;
  10722. else
  10723. { Invalid }
  10724. Exit;
  10725. end;
  10726. end;
  10727. if not Assigned(pCMOV) then
  10728. { No complementary CMOV found }
  10729. Exit;
  10730. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  10731. begin
  10732. { Don't need to do anything special or search for a matching MOV }
  10733. Asml.Remove(pCMOV);
  10734. Asml.InsertBefore(pCMOV, p);
  10735. taicpu(pCMOV).opcode := A_MOV;
  10736. taicpu(pCMOV).condition := C_None;
  10737. { Don't need to worry about allocating new registers in these cases }
  10738. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  10739. Result := True;
  10740. Exit;
  10741. end
  10742. else
  10743. begin
  10744. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  10745. FoundMOV := False;
  10746. { Search for the MOV that sets the target register }
  10747. hp2 := pFirstMov;
  10748. repeat
  10749. if (taicpu(hp2).opcode = A_MOV) and
  10750. (taicpu(hp2).oper[1]^.typ = top_reg) and
  10751. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  10752. begin
  10753. { Change the destination }
  10754. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  10755. if not FoundMOV then
  10756. begin
  10757. FoundMOV := True;
  10758. { Make sure the register is allocated }
  10759. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  10760. end;
  10761. hp3 := tai(hp2.Previous);
  10762. Asml.Remove(hp2);
  10763. Asml.InsertBefore(hp2, p);
  10764. hp2 := hp3;
  10765. end;
  10766. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  10767. if FoundMOV then
  10768. { Delete the CMOV }
  10769. RemoveInstruction(pcMOV)
  10770. else
  10771. begin
  10772. { If no MOV was found, we have to actually move and transmute the CMOV }
  10773. Asml.Remove(pCMOV);
  10774. Asml.InsertBefore(pCMOV, p);
  10775. taicpu(pCMOV).opcode := A_MOV;
  10776. taicpu(pCMOV).condition := C_None;
  10777. end;
  10778. Result := True;
  10779. Exit;
  10780. end;
  10781. end;
  10782. end;
  10783. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  10784. var
  10785. hp1, hp2, pCond: tai;
  10786. begin
  10787. Result := False;
  10788. { Search ahead for CMOV instructions }
  10789. if (cs_opt_level2 in current_settings.optimizerswitches) then
  10790. begin
  10791. hp1 := p;
  10792. hp2 := p;
  10793. pCond := nil; { To prevent compiler warnings }
  10794. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  10795. DEFAULTFLAGS }
  10796. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  10797. (tai_regalloc(pCond).ratype = ra_dealloc) then
  10798. pCond := p;
  10799. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  10800. begin
  10801. if (hp1.typ = ait_instruction) then
  10802. begin
  10803. case taicpu(hp1).opcode of
  10804. A_MOV:
  10805. { Ignore regular MOVs unless they are obviously not related
  10806. to a CMOV block }
  10807. if taicpu(hp1).oper[1]^.typ <> top_reg then
  10808. Break;
  10809. A_CMOVcc:
  10810. if TryCmpCMovOpts(pCond, hp1) then
  10811. begin
  10812. hp1 := hp2;
  10813. { p itself isn't changed, and we're still inside a
  10814. while loop to catch subsequent CMOVs, so just flag
  10815. a new iteration }
  10816. Include(OptsToCheck, aoc_ForceNewIteration);
  10817. Continue;
  10818. end;
  10819. else
  10820. Break;
  10821. end;
  10822. end;
  10823. hp2 := hp1;
  10824. end;
  10825. end;
  10826. end;
  10827. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  10828. var
  10829. hp1, hp2, pCond: tai;
  10830. begin
  10831. Result := False;
  10832. { Search ahead for CMOV instructions }
  10833. if (cs_opt_level2 in current_settings.optimizerswitches) then
  10834. begin
  10835. hp1 := p;
  10836. hp2 := p;
  10837. pCond := nil; { To prevent compiler warnings }
  10838. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  10839. DEFAULTFLAGS }
  10840. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  10841. (tai_regalloc(pCond).ratype = ra_dealloc) then
  10842. pCond := p;
  10843. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  10844. begin
  10845. if (hp1.typ = ait_instruction) then
  10846. begin
  10847. case taicpu(hp1).opcode of
  10848. A_MOV:
  10849. { Ignore regular MOVs unless they are obviously not related
  10850. to a CMOV block }
  10851. if taicpu(hp1).oper[1]^.typ <> top_reg then
  10852. Break;
  10853. A_CMOVcc:
  10854. if TryCmpCMovOpts(pCond, hp1) then
  10855. begin
  10856. hp1 := hp2;
  10857. { p itself isn't changed, and we're still inside a
  10858. while loop to catch subsequent CMOVs, so just flag
  10859. a new iteration }
  10860. Include(OptsToCheck, aoc_ForceNewIteration);
  10861. Continue;
  10862. end;
  10863. else
  10864. Break;
  10865. end;
  10866. end;
  10867. hp2 := hp1;
  10868. end;
  10869. end;
  10870. end;
  10871. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  10872. var
  10873. hp1: tai;
  10874. Count: Integer;
  10875. OrigLabel: TAsmLabel;
  10876. begin
  10877. result := False;
  10878. { Sometimes, the optimisations below can permit this }
  10879. RemoveDeadCodeAfterJump(p);
  10880. 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
  10881. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  10882. begin
  10883. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10884. { Also a side-effect of optimisations }
  10885. if CollapseZeroDistJump(p, OrigLabel) then
  10886. begin
  10887. Result := True;
  10888. Exit;
  10889. end;
  10890. hp1 := GetLabelWithSym(OrigLabel);
  10891. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  10892. begin
  10893. if taicpu(hp1).opcode = A_RET then
  10894. begin
  10895. {
  10896. change
  10897. jmp .L1
  10898. ...
  10899. .L1:
  10900. ret
  10901. into
  10902. ret
  10903. }
  10904. begin
  10905. ConvertJumpToRET(p, hp1);
  10906. result:=true;
  10907. end;
  10908. end
  10909. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  10910. not (cs_opt_size in current_settings.optimizerswitches) and
  10911. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  10912. begin
  10913. Result := True;
  10914. Exit;
  10915. end;
  10916. end;
  10917. end;
  10918. end;
  10919. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  10920. begin
  10921. Result := assigned(p) and
  10922. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  10923. (taicpu(p).oper[1]^.typ = top_reg) and
  10924. (
  10925. (taicpu(p).oper[0]^.typ = top_reg) or
  10926. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  10927. it is not expected that this can cause a seg. violation }
  10928. (
  10929. (taicpu(p).oper[0]^.typ = top_ref) and
  10930. { TODO: Can we detect which references become constants at this
  10931. stage so we don't have to do a blanket ban? }
  10932. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  10933. (
  10934. IsRefSafe(taicpu(p).oper[0]^.ref) or
  10935. (
  10936. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  10937. not RefModified and
  10938. { If the reference also appears in the condition, then we know it's safe, otherwise
  10939. any kind of access violation would have occurred already }
  10940. Assigned(cond_p) and
  10941. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  10942. (cond_p.typ = ait_instruction) and
  10943. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  10944. { Just consider 2-operand comparison instructions for now to be safe }
  10945. (taicpu(cond_p).ops = 2) and
  10946. (
  10947. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  10948. (
  10949. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  10950. { Don't risk identical registers but different offsets, as we may have constructs
  10951. such as buffer streams with things like length fields that indicate whether
  10952. any more data follows. And there are probably some contrived examples where
  10953. writing to offsets behind the one being read also lead to access violations }
  10954. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  10955. (
  10956. { Check that we're not modifying a register that appears in the reference }
  10957. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  10958. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  10959. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  10960. )
  10961. )
  10962. )
  10963. )
  10964. )
  10965. )
  10966. );
  10967. end;
  10968. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  10969. begin
  10970. { Update integer registers, ignoring deallocations }
  10971. repeat
  10972. while assigned(p) and
  10973. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  10974. (p.typ = ait_label) or
  10975. ((p.typ = ait_marker) and
  10976. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  10977. p := tai(p.next);
  10978. while assigned(p) and
  10979. (p.typ=ait_RegAlloc) Do
  10980. begin
  10981. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  10982. begin
  10983. case tai_regalloc(p).ratype of
  10984. ra_alloc :
  10985. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  10986. else
  10987. ;
  10988. end;
  10989. end;
  10990. p := tai(p.next);
  10991. end;
  10992. until not(assigned(p)) or
  10993. (not(p.typ in SkipInstr) and
  10994. not((p.typ = ait_label) and
  10995. labelCanBeSkipped(tai_label(p))));
  10996. end;
  10997. {$ifndef 8086}
  10998. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  10999. begin
  11000. Result := False;
  11001. EndJump := nil;
  11002. BlockStop := nil;
  11003. while (BlockStart <> fOptimizer.BlockEnd) and
  11004. { stop on labels }
  11005. (BlockStart.typ <> ait_label) do
  11006. begin
  11007. { Keep track of all integer registers that are used }
  11008. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11009. if BlockStart.typ = ait_instruction then
  11010. begin
  11011. if (taicpu(BlockStart).opcode = A_JMP) then
  11012. begin
  11013. if not IsJumpToLabel(taicpu(BlockStart)) or
  11014. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11015. Exit;
  11016. EndJump := BlockStart;
  11017. Break;
  11018. end
  11019. { Check to see if we have a valid MOV instruction instead }
  11020. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11021. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11022. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11023. begin
  11024. Exit;
  11025. end
  11026. else
  11027. { This will be a valid MOV }
  11028. fAllocationRange := BlockStart;
  11029. end;
  11030. OneBeforeBlock := BlockStart;
  11031. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11032. end;
  11033. if (BlockStart = fOptimizer.BlockEnd) then
  11034. Exit;
  11035. BlockStop := BlockStart;
  11036. Result := True;
  11037. end;
  11038. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  11039. var
  11040. hp1: tai;
  11041. RefModified: Boolean;
  11042. begin
  11043. Result := 0;
  11044. hp1 := BlockStart;
  11045. RefModified := False; { As long as the condition is inverted, this can be reset }
  11046. while assigned(hp1) and
  11047. (hp1 <> BlockStop) do
  11048. begin
  11049. case hp1.typ of
  11050. ait_instruction:
  11051. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11052. begin
  11053. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  11054. begin
  11055. Inc(Result);
  11056. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11057. Assigned(fCondition) and
  11058. { Will have 2 operands }
  11059. (
  11060. (
  11061. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  11062. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  11063. ) or
  11064. (
  11065. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  11066. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  11067. )
  11068. ) then
  11069. { It is no longer safe to use the reference in the condition.
  11070. this prevents problems such as:
  11071. mov (%reg),%reg
  11072. mov (%reg),...
  11073. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11074. (fixes #40165)
  11075. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11076. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11077. }
  11078. RefModified := True;
  11079. end
  11080. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11081. { CMOV with constants grows the code size }
  11082. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  11083. begin
  11084. { Register was reserved by TryCMOVConst and
  11085. stored on ConstRegs }
  11086. end
  11087. else
  11088. begin
  11089. Result := -1;
  11090. Exit;
  11091. end;
  11092. end
  11093. else
  11094. begin
  11095. Result := -1;
  11096. Exit;
  11097. end;
  11098. else
  11099. { Most likely an align };
  11100. end;
  11101. fOptimizer.GetNextInstruction(hp1, hp1);
  11102. end;
  11103. end;
  11104. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  11105. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  11106. (this is done as a separate stage because the double types are extensions of the branching type,
  11107. but we can't discount the conditional jump until the last step) }
  11108. procedure EvaluateBranchingType;
  11109. begin
  11110. Inc(CMOVScore);
  11111. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  11112. { Too many instructions to be worthwhile }
  11113. fState := tsInvalid;
  11114. end;
  11115. var
  11116. hp1: tai;
  11117. Count: Integer;
  11118. begin
  11119. { Table of valid CMOV block types
  11120. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  11121. ---------- --------- --------- --------- --------- ---------
  11122. tsSimple X Yes X X X
  11123. tsDetour = 1st X X X X
  11124. tsBranching <> Mid Yes X X X
  11125. tsDouble End-label Yes * Yes X Yes
  11126. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  11127. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  11128. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  11129. * Only one reference allowed
  11130. }
  11131. hp1 := nil; { To prevent compiler warnings }
  11132. Optimizer.CopyUsedRegs(RegisterTracking);
  11133. fOptimizer := Optimizer;
  11134. fLabel := AFirstLabel;
  11135. CMOVScore := 0;
  11136. ConstCount := 0;
  11137. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11138. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11139. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11140. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11141. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11142. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11143. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11144. fInsertionPoint := p_initialjump;
  11145. fCondition := nil;
  11146. fInitialJump := p_initialjump;
  11147. fFirstMovBlock := p_initialmov;
  11148. fFirstMovBlockStop := nil;
  11149. fSecondJump := nil;
  11150. fSecondMovBlock := nil;
  11151. fSecondMovBlockStop := nil;
  11152. fMidLabel := nil;
  11153. fSecondJump := nil;
  11154. fSecondMovBlock := nil;
  11155. fEndLabel := nil;
  11156. fAllocationRange := nil;
  11157. { Assume it all goes horribly wrong! }
  11158. fState := tsInvalid;
  11159. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  11160. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  11161. 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
  11162. begin
  11163. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11164. for Count := 0 to 1 do
  11165. with taicpu(fCondition).oper[Count]^ do
  11166. case typ of
  11167. top_reg:
  11168. if getregtype(reg) = R_INTREGISTER then
  11169. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11170. top_ref:
  11171. begin
  11172. if
  11173. {$ifdef x86_64}
  11174. (ref^.base <> NR_RIP) and
  11175. {$endif x86_64}
  11176. (ref^.base <> NR_NO) then
  11177. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11178. if (ref^.index <> NR_NO) then
  11179. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11180. end
  11181. else
  11182. ;
  11183. end;
  11184. { When inserting instructions before hp_prev, try to insert them
  11185. before the allocation of the FLAGS register }
  11186. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  11187. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  11188. { If not found, set it equal to the condition so it's something sensible }
  11189. fInsertionPoint := fCondition;
  11190. { When dealing with a comparison against zero, take note of the
  11191. instruction before it to see if we can move instructions further
  11192. back in order to benefit PostPeepholeOptTestOr.
  11193. }
  11194. if (
  11195. (
  11196. (taicpu(fCondition).opcode = A_CMP) and
  11197. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  11198. ) or
  11199. (
  11200. (taicpu(fCondition).opcode = A_TEST) and
  11201. (
  11202. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  11203. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  11204. )
  11205. )
  11206. ) and
  11207. Optimizer.GetLastInstruction(fCondition, hp1) then
  11208. begin
  11209. { These instructions set the zero flag if the result is zero }
  11210. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11211. begin
  11212. fInsertionPoint := hp1;
  11213. { Also mark all the registers in this previous instruction
  11214. as 'in use', even if they've just been deallocated }
  11215. for Count := 0 to 1 do
  11216. with taicpu(hp1).oper[Count]^ do
  11217. case typ of
  11218. top_reg:
  11219. if getregtype(reg) = R_INTREGISTER then
  11220. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11221. top_ref:
  11222. begin
  11223. if
  11224. {$ifdef x86_64}
  11225. (ref^.base <> NR_RIP) and
  11226. {$endif x86_64}
  11227. (ref^.base <> NR_NO) then
  11228. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11229. if (ref^.index <> NR_NO) then
  11230. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11231. end
  11232. else
  11233. ;
  11234. end;
  11235. end;
  11236. end;
  11237. end
  11238. else
  11239. fCondition := nil;
  11240. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  11241. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  11242. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  11243. { If not found, set it equal to p so it's something sensible }
  11244. fInsertionPoint := hp1;
  11245. hp1 := p_initialmov;
  11246. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  11247. Exit;
  11248. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  11249. if (hp1.typ <> ait_label) then { should be on a jump }
  11250. begin
  11251. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  11252. { Need a label afterwards }
  11253. Exit;
  11254. end
  11255. else
  11256. fMidLabel := hp1;
  11257. if tai_label(fMidLabel).labsym <> AFirstLabel then
  11258. { Not the correct label }
  11259. fMidLabel := nil;
  11260. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  11261. { If there's neither a 2nd jump nor correct label, then it's invalid
  11262. (see above table) }
  11263. Exit;
  11264. { Analyse the first block of MOVs more closely }
  11265. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  11266. if Assigned(fSecondJump) then
  11267. begin
  11268. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  11269. begin
  11270. fState := tsDetour
  11271. end
  11272. else
  11273. begin
  11274. { Need the correct mid-label for this one }
  11275. if not Assigned(fMidLabel) then
  11276. Exit;
  11277. fState := tsBranching;
  11278. end;
  11279. end
  11280. else
  11281. { No jump. but mid-label is present }
  11282. fState := tsSimple;
  11283. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  11284. begin
  11285. { Invalid or too many instructions to be worthwhile }
  11286. fState := tsInvalid;
  11287. Exit;
  11288. end;
  11289. { check further for
  11290. jCC xxx
  11291. <several movs 1>
  11292. jmp yyy
  11293. xxx:
  11294. <several movs 2>
  11295. yyy:
  11296. etc.
  11297. }
  11298. if (fState = tsBranching) and
  11299. { Estimate for required savings for extra jump }
  11300. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  11301. { Only one reference is allowed for double blocks }
  11302. (AFirstLabel.getrefs = 1) then
  11303. begin
  11304. Optimizer.GetNextInstruction(fMidLabel, hp1);
  11305. fSecondMovBlock := hp1;
  11306. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  11307. begin
  11308. EvaluateBranchingType;
  11309. Exit;
  11310. end;
  11311. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  11312. if (hp1.typ <> ait_label) then { should be on a jump }
  11313. begin
  11314. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  11315. begin
  11316. { Need a label afterwards }
  11317. EvaluateBranchingType;
  11318. Exit;
  11319. end;
  11320. end
  11321. else
  11322. fEndLabel := hp1;
  11323. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  11324. { Second jump doesn't go to the end }
  11325. fEndLabel := nil;
  11326. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  11327. begin
  11328. { If there's neither a 3rd jump nor correct end label, then it's
  11329. not a invalid double block, but is a valid single branching
  11330. block (see above table) }
  11331. EvaluateBranchingType;
  11332. Exit;
  11333. end;
  11334. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  11335. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  11336. { Invalid or too many instructions to be worthwhile }
  11337. Exit;
  11338. Inc(CMOVScore, Count);
  11339. if Assigned(fThirdJump) then
  11340. begin
  11341. if not Assigned(fSecondJump) then
  11342. fState := tsDoubleSecondBranching
  11343. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  11344. fState := tsDoubleBranchSame
  11345. else
  11346. fState := tsDoubleBranchDifferent;
  11347. end
  11348. else
  11349. fState := tsDouble;
  11350. end;
  11351. if fState = tsBranching then
  11352. EvaluateBranchingType;
  11353. end;
  11354. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  11355. new register to store the constant }
  11356. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  11357. var
  11358. RegSize: TSubRegister;
  11359. CurrentVal: TCGInt;
  11360. ANewReg: TRegister;
  11361. X: ShortInt;
  11362. begin
  11363. Result := False;
  11364. if not MatchOpType(taicpu(p), top_const, top_reg) then
  11365. Exit;
  11366. if ConstCount >= MAX_CMOV_REGISTERS then
  11367. { Arrays are full }
  11368. Exit;
  11369. { Remember that CMOV can't encode 8-bit registers }
  11370. case taicpu(p).opsize of
  11371. S_W:
  11372. RegSize := R_SUBW;
  11373. S_L:
  11374. RegSize := R_SUBD;
  11375. {$ifdef x86_64}
  11376. S_Q:
  11377. RegSize := R_SUBQ;
  11378. {$endif x86_64}
  11379. else
  11380. InternalError(2021100401);
  11381. end;
  11382. { See if the value has already been reserved for another CMOV instruction }
  11383. CurrentVal := taicpu(p).oper[0]^.val;
  11384. for X := 0 to ConstCount - 1 do
  11385. if ConstVals[X] = CurrentVal then
  11386. begin
  11387. ConstRegs[ConstCount] := ConstRegs[X];
  11388. ConstSizes[ConstCount] := RegSize;
  11389. ConstVals[ConstCount] := CurrentVal;
  11390. Inc(ConstCount);
  11391. Inc(Count);
  11392. Result := True;
  11393. Exit;
  11394. end;
  11395. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  11396. if ANewReg = NR_NO then
  11397. { No free registers }
  11398. Exit;
  11399. { Reserve the register so subsequent TryCMOVConst calls don't all end
  11400. up vying for the same register }
  11401. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  11402. ConstRegs[ConstCount] := ANewReg;
  11403. ConstSizes[ConstCount] := RegSize;
  11404. ConstVals[ConstCount] := CurrentVal;
  11405. Inc(ConstCount);
  11406. Inc(Count);
  11407. Result := True;
  11408. end;
  11409. destructor TCMOVTracking.Done;
  11410. begin
  11411. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  11412. end;
  11413. procedure TCMOVTracking.Process(out new_p: tai);
  11414. var
  11415. Count, Writes: LongInt;
  11416. RegMatch: Boolean;
  11417. hp1, hp_new: tai;
  11418. inverted_condition, condition: TAsmCond;
  11419. begin
  11420. if (fState in [tsInvalid, tsProcessed]) then
  11421. InternalError(2023110701);
  11422. { Repurpose RegisterTracking to mark registers that we've defined }
  11423. RegisterTracking[R_INTREGISTER].Clear;
  11424. Count := 0;
  11425. Writes := 0;
  11426. condition := taicpu(fInitialJump).condition;
  11427. inverted_condition := inverse_cond(condition);
  11428. { Exclude tsDoubleBranchDifferent from this check, as the second block
  11429. doesn't get CMOVs in this case }
  11430. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  11431. begin
  11432. { Include the jump in the flag tracking }
  11433. if Assigned(fThirdJump) then
  11434. begin
  11435. if (fState = tsDoubleBranchSame) then
  11436. begin
  11437. { Will be an unconditional jump, so track to the instruction before it }
  11438. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  11439. InternalError(2023110710);
  11440. end
  11441. else
  11442. hp1 := fThirdJump;
  11443. end
  11444. else
  11445. hp1 := fSecondMovBlockStop;
  11446. end
  11447. else
  11448. begin
  11449. { Include a conditional jump in the flag tracking }
  11450. if Assigned(fSecondJump) then
  11451. begin
  11452. if (fState = tsDetour) then
  11453. begin
  11454. { Will be an unconditional jump, so track to the instruction before it }
  11455. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  11456. InternalError(2023110711);
  11457. end
  11458. else
  11459. hp1 := fSecondJump;
  11460. end
  11461. else
  11462. hp1 := fFirstMovBlockStop;
  11463. end;
  11464. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  11465. { Process the second set of MOVs first, because if a destination
  11466. register is shared between the first and second MOV sets, it is more
  11467. efficient to turn the first one into a MOV instruction and place it
  11468. before the CMP if possible, but we won't know which registers are
  11469. shared until we've processed at least one list, so we might as well
  11470. make it the second one since that won't be modified again. }
  11471. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  11472. begin
  11473. hp1 := fSecondMovBlock;
  11474. repeat
  11475. if not Assigned(hp1) then
  11476. InternalError(2018062902);
  11477. if (hp1.typ = ait_instruction) then
  11478. begin
  11479. { Extra safeguard }
  11480. if (taicpu(hp1).opcode <> A_MOV) then
  11481. InternalError(2018062903);
  11482. { Note: tsDoubleBranchDifferent is essentially identical to
  11483. tsBranching and the 2nd block is best left largely
  11484. untouched, but we need to evaluate which registers the MOVs
  11485. write to in order to track what would be complementary CMOV
  11486. pairs that can be further optimised. [Kit] }
  11487. if fState <> tsDoubleBranchDifferent then
  11488. begin
  11489. if taicpu(hp1).oper[0]^.typ = top_const then
  11490. begin
  11491. RegMatch := False;
  11492. for Count := 0 to ConstCount - 1 do
  11493. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  11494. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  11495. begin
  11496. RegMatch := True;
  11497. { If it's in RegisterTracking, then this register
  11498. is being used more than once and hence has
  11499. already had its value defined (it gets added to
  11500. UsedRegs through AllocRegBetween below) }
  11501. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  11502. begin
  11503. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  11504. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  11505. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  11506. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  11507. ConstMovs[Count] := hp_new;
  11508. end
  11509. else
  11510. { We just need an instruction between hp_prev and hp1
  11511. where we know the register is marked as in use }
  11512. hp_new := fSecondMovBlock;
  11513. { Keep track of largest write for this register so it can be optimised later }
  11514. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  11515. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11516. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  11517. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  11518. Break;
  11519. end;
  11520. if not RegMatch then
  11521. InternalError(2021100411);
  11522. end;
  11523. taicpu(hp1).opcode := A_CMOVcc;
  11524. taicpu(hp1).condition := condition;
  11525. end;
  11526. { Store these writes to search for duplicates later on }
  11527. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  11528. Inc(Writes);
  11529. end;
  11530. fOptimizer.GetNextInstruction(hp1, hp1);
  11531. until (hp1 = fSecondMovBlockStop);
  11532. end;
  11533. { Now do the first set of MOVs }
  11534. hp1 := fFirstMovBlock;
  11535. repeat
  11536. if not Assigned(hp1) then
  11537. InternalError(2018062904);
  11538. if (hp1.typ = ait_instruction) then
  11539. begin
  11540. RegMatch := False;
  11541. { Extra safeguard }
  11542. if (taicpu(hp1).opcode <> A_MOV) then
  11543. InternalError(2018062905);
  11544. { Search through the RegWrites list to see if there are any
  11545. opposing CMOV pairs that write to the same register }
  11546. for Count := 0 to Writes - 1 do
  11547. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  11548. begin
  11549. { We have a match. Keep this as a MOV }
  11550. { Move ahead in preparation }
  11551. fOptimizer.GetNextInstruction(hp1, hp1);
  11552. RegMatch := True;
  11553. Break;
  11554. end;
  11555. if RegMatch then
  11556. Continue;
  11557. if taicpu(hp1).oper[0]^.typ = top_const then
  11558. begin
  11559. for Count := 0 to ConstCount - 1 do
  11560. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  11561. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  11562. begin
  11563. RegMatch := True;
  11564. { If it's in RegisterTracking, then this register is
  11565. being used more than once and hence has already had
  11566. its value defined (it gets added to UsedRegs through
  11567. AllocRegBetween below) }
  11568. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  11569. begin
  11570. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  11571. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  11572. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  11573. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  11574. ConstMovs[Count] := hp_new;
  11575. end
  11576. else
  11577. { We just need an instruction between hp_prev and hp1
  11578. where we know the register is marked as in use }
  11579. hp_new := fFirstMovBlock;
  11580. { Keep track of largest write for this register so it can be optimised later }
  11581. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  11582. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11583. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  11584. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  11585. Break;
  11586. end;
  11587. if not RegMatch then
  11588. InternalError(2021100412);
  11589. end;
  11590. taicpu(hp1).opcode := A_CMOVcc;
  11591. taicpu(hp1).condition := inverted_condition;
  11592. if (fState = tsDoubleBranchDifferent) then
  11593. begin
  11594. { Store these writes to search for duplicates later on }
  11595. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  11596. Inc(Writes);
  11597. end;
  11598. end;
  11599. fOptimizer.GetNextInstruction(hp1, hp1);
  11600. until (hp1 = fFirstMovBlockStop);
  11601. { Update initialisation MOVs to the smallest possible size }
  11602. for Count := 0 to ConstCount - 1 do
  11603. if Assigned(ConstMovs[Count]) then
  11604. begin
  11605. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  11606. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  11607. end;
  11608. case fState of
  11609. tsSimple:
  11610. begin
  11611. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  11612. { No branch to delete }
  11613. end;
  11614. tsDetour:
  11615. begin
  11616. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  11617. { Preserve jump }
  11618. end;
  11619. tsBranching, tsDoubleBranchDifferent:
  11620. begin
  11621. if (fState = tsBranching) then
  11622. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  11623. else
  11624. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  11625. taicpu(fSecondJump).opcode := A_JCC;
  11626. taicpu(fSecondJump).condition := inverted_condition;
  11627. end;
  11628. tsDouble, tsDoubleBranchSame:
  11629. begin
  11630. if (fState = tsDouble) then
  11631. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  11632. else
  11633. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  11634. { Delete second jump }
  11635. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  11636. fOptimizer.RemoveInstruction(fSecondJump);
  11637. end;
  11638. tsDoubleSecondBranching:
  11639. begin
  11640. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  11641. { Delete second jump, preserve third jump as conditional }
  11642. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  11643. fOptimizer.RemoveInstruction(fSecondJump);
  11644. taicpu(fThirdJump).opcode := A_JCC;
  11645. taicpu(fThirdJump).condition := condition;
  11646. end;
  11647. else
  11648. InternalError(2023110720);
  11649. end;
  11650. { Now we can safely decrement the reference count }
  11651. tasmlabel(fLabel).decrefs;
  11652. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  11653. { Remove the original jump }
  11654. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  11655. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  11656. fState := tsProcessed;
  11657. end;
  11658. {$endif 8086}
  11659. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  11660. var
  11661. hp1,hp2: tai;
  11662. carryadd_opcode : TAsmOp;
  11663. symbol: TAsmSymbol;
  11664. increg, tmpreg: TRegister;
  11665. {$ifndef i8086}
  11666. CMOVTracking: PCMOVTracking;
  11667. hp3,hp4,hp5: tai;
  11668. {$endif i8086}
  11669. begin
  11670. result:=false;
  11671. if GetNextInstruction(p,hp1) then
  11672. begin
  11673. if (hp1.typ=ait_label) then
  11674. begin
  11675. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  11676. Exit;
  11677. end
  11678. else if (hp1.typ<>ait_instruction) then
  11679. Exit;
  11680. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11681. if (
  11682. (
  11683. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  11684. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  11685. (Taicpu(hp1).oper[0]^.val=1)
  11686. ) or
  11687. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  11688. ) and
  11689. GetNextInstruction(hp1,hp2) and
  11690. (hp2.typ = ait_label) and
  11691. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  11692. { jb @@1 cmc
  11693. inc/dec operand --> adc/sbb operand,0
  11694. @@1:
  11695. ... and ...
  11696. jnb @@1
  11697. inc/dec operand --> adc/sbb operand,0
  11698. @@1: }
  11699. begin
  11700. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  11701. begin
  11702. case taicpu(hp1).opcode of
  11703. A_INC,
  11704. A_ADD:
  11705. carryadd_opcode:=A_ADC;
  11706. A_DEC,
  11707. A_SUB:
  11708. carryadd_opcode:=A_SBB;
  11709. else
  11710. InternalError(2021011001);
  11711. end;
  11712. Taicpu(p).clearop(0);
  11713. Taicpu(p).ops:=0;
  11714. Taicpu(p).is_jmp:=false;
  11715. Taicpu(p).opcode:=A_CMC;
  11716. Taicpu(p).condition:=C_NONE;
  11717. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  11718. Taicpu(hp1).ops:=2;
  11719. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  11720. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  11721. else
  11722. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  11723. Taicpu(hp1).loadconst(0,0);
  11724. Taicpu(hp1).opcode:=carryadd_opcode;
  11725. result:=true;
  11726. exit;
  11727. end
  11728. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  11729. begin
  11730. case taicpu(hp1).opcode of
  11731. A_INC,
  11732. A_ADD:
  11733. carryadd_opcode:=A_ADC;
  11734. A_DEC,
  11735. A_SUB:
  11736. carryadd_opcode:=A_SBB;
  11737. else
  11738. InternalError(2021011002);
  11739. end;
  11740. Taicpu(hp1).ops:=2;
  11741. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  11742. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  11743. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  11744. else
  11745. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  11746. Taicpu(hp1).loadconst(0,0);
  11747. Taicpu(hp1).opcode:=carryadd_opcode;
  11748. RemoveCurrentP(p, hp1);
  11749. result:=true;
  11750. exit;
  11751. end
  11752. {
  11753. jcc @@1 setcc tmpreg
  11754. inc/dec/add/sub operand -> (movzx tmpreg)
  11755. @@1: add/sub tmpreg,operand
  11756. While this increases code size slightly, it makes the code much faster if the
  11757. jump is unpredictable
  11758. }
  11759. else if not(cs_opt_size in current_settings.optimizerswitches) then
  11760. begin
  11761. { search for an available register which is volatile }
  11762. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  11763. if increg <> NR_NO then
  11764. begin
  11765. { We don't need to check if tmpreg is in hp1 or not, because
  11766. it will be marked as in use at p (if not, this is
  11767. indictive of a compiler bug). }
  11768. TAsmLabel(symbol).decrefs;
  11769. Taicpu(p).clearop(0);
  11770. Taicpu(p).ops:=1;
  11771. Taicpu(p).is_jmp:=false;
  11772. Taicpu(p).opcode:=A_SETcc;
  11773. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  11774. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  11775. Taicpu(p).loadreg(0,increg);
  11776. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  11777. begin
  11778. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  11779. R_SUBW:
  11780. begin
  11781. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  11782. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  11783. end;
  11784. R_SUBD:
  11785. begin
  11786. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  11787. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  11788. end;
  11789. {$ifdef x86_64}
  11790. R_SUBQ:
  11791. begin
  11792. { MOVZX doesn't have a 64-bit variant, because
  11793. the 32-bit version implicitly zeroes the
  11794. upper 32-bits of the destination register }
  11795. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  11796. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  11797. setsubreg(tmpreg, R_SUBQ);
  11798. end;
  11799. {$endif x86_64}
  11800. else
  11801. Internalerror(2020030601);
  11802. end;
  11803. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  11804. asml.InsertAfter(hp2,p);
  11805. end
  11806. else
  11807. tmpreg := increg;
  11808. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  11809. begin
  11810. Taicpu(hp1).ops:=2;
  11811. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  11812. end;
  11813. Taicpu(hp1).loadreg(0,tmpreg);
  11814. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  11815. Result := True;
  11816. { p is no longer a Jcc instruction, so exit }
  11817. Exit;
  11818. end;
  11819. end;
  11820. end;
  11821. { Detect the following:
  11822. jmp<cond> @Lbl1
  11823. jmp @Lbl2
  11824. ...
  11825. @Lbl1:
  11826. ret
  11827. Change to:
  11828. jmp<inv_cond> @Lbl2
  11829. ret
  11830. }
  11831. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11832. begin
  11833. hp2:=getlabelwithsym(TAsmLabel(symbol));
  11834. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  11835. MatchInstruction(hp2,A_RET,[S_NO]) then
  11836. begin
  11837. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  11838. { Change label address to that of the unconditional jump }
  11839. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  11840. TAsmLabel(symbol).DecRefs;
  11841. taicpu(hp1).opcode := A_RET;
  11842. taicpu(hp1).is_jmp := false;
  11843. taicpu(hp1).ops := taicpu(hp2).ops;
  11844. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  11845. case taicpu(hp2).ops of
  11846. 0:
  11847. taicpu(hp1).clearop(0);
  11848. 1:
  11849. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  11850. else
  11851. internalerror(2016041302);
  11852. end;
  11853. end;
  11854. {$ifndef i8086}
  11855. end
  11856. {
  11857. convert
  11858. j<c> .L1
  11859. mov 1,reg
  11860. jmp .L2
  11861. .L1
  11862. mov 0,reg
  11863. .L2
  11864. into
  11865. mov 0,reg
  11866. set<not(c)> reg
  11867. take care of alignment and that the mov 0,reg is not converted into a xor as this
  11868. would destroy the flag contents
  11869. }
  11870. else if MatchInstruction(hp1,A_MOV,[]) and
  11871. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11872. {$ifdef i386}
  11873. (
  11874. { Under i386, ESI, EDI, EBP and ESP
  11875. don't have an 8-bit representation }
  11876. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  11877. ) and
  11878. {$endif i386}
  11879. (taicpu(hp1).oper[0]^.val=1) and
  11880. GetNextInstruction(hp1,hp2) and
  11881. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  11882. GetNextInstruction(hp2,hp3) and
  11883. (hp3.typ=ait_label) and
  11884. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  11885. (tai_label(hp3).labsym.getrefs=1) and
  11886. GetNextInstruction(hp3,hp4) and
  11887. MatchInstruction(hp4,A_MOV,[]) and
  11888. MatchOpType(taicpu(hp4),top_const,top_reg) and
  11889. (taicpu(hp4).oper[0]^.val=0) and
  11890. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  11891. GetNextInstruction(hp4,hp5) and
  11892. (hp5.typ=ait_label) and
  11893. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  11894. (tai_label(hp5).labsym.getrefs=1) then
  11895. begin
  11896. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  11897. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  11898. { remove last label }
  11899. RemoveInstruction(hp5);
  11900. { remove second label }
  11901. RemoveInstruction(hp3);
  11902. { remove jmp }
  11903. RemoveInstruction(hp2);
  11904. if taicpu(hp1).opsize=S_B then
  11905. RemoveInstruction(hp1)
  11906. else
  11907. taicpu(hp1).loadconst(0,0);
  11908. taicpu(hp4).opcode:=A_SETcc;
  11909. taicpu(hp4).opsize:=S_B;
  11910. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  11911. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  11912. taicpu(hp4).opercnt:=1;
  11913. taicpu(hp4).ops:=1;
  11914. taicpu(hp4).freeop(1);
  11915. RemoveCurrentP(p);
  11916. Result:=true;
  11917. exit;
  11918. end
  11919. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  11920. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  11921. begin
  11922. { check for
  11923. jCC xxx
  11924. <several movs>
  11925. xxx:
  11926. Also spot:
  11927. Jcc xxx
  11928. <several movs>
  11929. jmp xxx
  11930. Change to:
  11931. <several cmovs with inverted condition>
  11932. jmp xxx (only for the 2nd case)
  11933. }
  11934. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  11935. if CMOVTracking^.State <> tsInvalid then
  11936. begin
  11937. CMovTracking^.Process(p);
  11938. Result := True;
  11939. end;
  11940. CMOVTracking^.Done;
  11941. {$endif i8086}
  11942. end;
  11943. end;
  11944. end;
  11945. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  11946. var
  11947. hp1,hp2,hp3: tai;
  11948. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  11949. NewSize: TOpSize;
  11950. NewRegSize: TSubRegister;
  11951. Limit: TCgInt;
  11952. SwapOper: POper;
  11953. begin
  11954. result:=false;
  11955. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  11956. GetNextInstruction(p,hp1) and
  11957. (hp1.typ = ait_instruction);
  11958. if reg_and_hp1_is_instr and
  11959. (
  11960. (taicpu(hp1).opcode <> A_LEA) or
  11961. { If the LEA instruction can be converted into an arithmetic instruction,
  11962. it may be possible to then fold it. }
  11963. (
  11964. { If the flags register is in use, don't change the instruction
  11965. to an ADD otherwise this will scramble the flags. [Kit] }
  11966. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11967. ConvertLEA(taicpu(hp1))
  11968. )
  11969. ) and
  11970. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  11971. GetNextInstruction(hp1,hp2) and
  11972. MatchInstruction(hp2,A_MOV,[]) and
  11973. (taicpu(hp2).oper[0]^.typ = top_reg) and
  11974. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  11975. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  11976. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  11977. {$ifdef i386}
  11978. { not all registers have byte size sub registers on i386 }
  11979. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  11980. {$endif i386}
  11981. (((taicpu(hp1).ops=2) and
  11982. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  11983. ((taicpu(hp1).ops=1) and
  11984. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  11985. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  11986. begin
  11987. { change movsX/movzX reg/ref, reg2
  11988. add/sub/or/... reg3/$const, reg2
  11989. mov reg2 reg/ref
  11990. to add/sub/or/... reg3/$const, reg/ref }
  11991. { by example:
  11992. movswl %si,%eax movswl %si,%eax p
  11993. decl %eax addl %edx,%eax hp1
  11994. movw %ax,%si movw %ax,%si hp2
  11995. ->
  11996. movswl %si,%eax movswl %si,%eax p
  11997. decw %eax addw %edx,%eax hp1
  11998. movw %ax,%si movw %ax,%si hp2
  11999. }
  12000. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12001. {
  12002. ->
  12003. movswl %si,%eax movswl %si,%eax p
  12004. decw %si addw %dx,%si hp1
  12005. movw %ax,%si movw %ax,%si hp2
  12006. }
  12007. case taicpu(hp1).ops of
  12008. 1:
  12009. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12010. 2:
  12011. begin
  12012. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12013. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12014. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12015. end;
  12016. else
  12017. internalerror(2008042702);
  12018. end;
  12019. {
  12020. ->
  12021. decw %si addw %dx,%si p
  12022. }
  12023. DebugMsg(SPeepholeOptimization + 'var3',p);
  12024. RemoveCurrentP(p, hp1);
  12025. RemoveInstruction(hp2);
  12026. Result := True;
  12027. Exit;
  12028. end;
  12029. if reg_and_hp1_is_instr and
  12030. (taicpu(hp1).opcode = A_MOV) and
  12031. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12032. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12033. {$ifdef x86_64}
  12034. { check for implicit extension to 64 bit }
  12035. or
  12036. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12037. (taicpu(hp1).opsize=S_Q) and
  12038. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  12039. )
  12040. {$endif x86_64}
  12041. )
  12042. then
  12043. begin
  12044. { change
  12045. movx %reg1,%reg2
  12046. mov %reg2,%reg3
  12047. dealloc %reg2
  12048. into
  12049. movx %reg,%reg3
  12050. }
  12051. TransferUsedRegs(TmpUsedRegs);
  12052. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12053. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  12054. begin
  12055. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  12056. {$ifdef x86_64}
  12057. if (taicpu(p).opsize in [S_BL,S_WL]) and
  12058. (taicpu(hp1).opsize=S_Q) then
  12059. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  12060. else
  12061. {$endif x86_64}
  12062. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  12063. RemoveInstruction(hp1);
  12064. Result := True;
  12065. Exit;
  12066. end;
  12067. end;
  12068. if reg_and_hp1_is_instr and
  12069. ((taicpu(hp1).opcode=A_MOV) or
  12070. (taicpu(hp1).opcode=A_ADD) or
  12071. (taicpu(hp1).opcode=A_SUB) or
  12072. (taicpu(hp1).opcode=A_CMP) or
  12073. (taicpu(hp1).opcode=A_OR) or
  12074. (taicpu(hp1).opcode=A_XOR) or
  12075. (taicpu(hp1).opcode=A_AND)
  12076. ) and
  12077. (taicpu(hp1).oper[1]^.typ = top_reg) then
  12078. begin
  12079. AndTest := (taicpu(hp1).opcode=A_AND) and
  12080. GetNextInstruction(hp1, hp2) and
  12081. (hp2.typ = ait_instruction) and
  12082. (
  12083. (
  12084. (taicpu(hp2).opcode=A_TEST) and
  12085. (
  12086. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  12087. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  12088. (
  12089. { If the AND and TEST instructions share a constant, this is also valid }
  12090. (taicpu(hp1).oper[0]^.typ = top_const) and
  12091. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  12092. )
  12093. ) and
  12094. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12095. ) or
  12096. (
  12097. (taicpu(hp2).opcode=A_CMP) and
  12098. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  12099. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12100. )
  12101. );
  12102. { change
  12103. movx (oper),%reg2
  12104. and $x,%reg2
  12105. test %reg2,%reg2
  12106. dealloc %reg2
  12107. into
  12108. op %reg1,%reg3
  12109. if the second op accesses only the bits stored in reg1
  12110. }
  12111. if ((taicpu(p).oper[0]^.typ=top_reg) or
  12112. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  12113. (taicpu(hp1).oper[0]^.typ = top_const) and
  12114. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12115. AndTest then
  12116. begin
  12117. { Check if the AND constant is in range }
  12118. case taicpu(p).opsize of
  12119. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12120. begin
  12121. NewSize := S_B;
  12122. Limit := $FF;
  12123. end;
  12124. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12125. begin
  12126. NewSize := S_W;
  12127. Limit := $FFFF;
  12128. end;
  12129. {$ifdef x86_64}
  12130. S_LQ:
  12131. begin
  12132. NewSize := S_L;
  12133. Limit := $FFFFFFFF;
  12134. end;
  12135. {$endif x86_64}
  12136. else
  12137. InternalError(2021120303);
  12138. end;
  12139. if (
  12140. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  12141. { Check for negative operands }
  12142. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  12143. ) and
  12144. GetNextInstruction(hp2,hp3) and
  12145. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  12146. (taicpu(hp3).condition in [C_E,C_NE]) then
  12147. begin
  12148. TransferUsedRegs(TmpUsedRegs);
  12149. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12150. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12151. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  12152. begin
  12153. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  12154. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12155. taicpu(hp1).opcode := A_TEST;
  12156. taicpu(hp1).opsize := NewSize;
  12157. RemoveInstruction(hp2);
  12158. RemoveCurrentP(p, hp1);
  12159. Result:=true;
  12160. exit;
  12161. end;
  12162. end;
  12163. end;
  12164. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12165. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  12166. (taicpu(hp1).opsize=S_B)) or
  12167. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  12168. (taicpu(hp1).opsize=S_W))
  12169. {$ifdef x86_64}
  12170. or ((taicpu(p).opsize=S_LQ) and
  12171. (taicpu(hp1).opsize=S_L))
  12172. {$endif x86_64}
  12173. ) and
  12174. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  12175. begin
  12176. { change
  12177. movx %reg1,%reg2
  12178. op %reg2,%reg3
  12179. dealloc %reg2
  12180. into
  12181. op %reg1,%reg3
  12182. if the second op accesses only the bits stored in reg1
  12183. }
  12184. TransferUsedRegs(TmpUsedRegs);
  12185. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12186. if AndTest then
  12187. begin
  12188. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12189. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12190. end
  12191. else
  12192. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12193. if not RegUsed then
  12194. begin
  12195. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  12196. if taicpu(p).oper[0]^.typ=top_reg then
  12197. begin
  12198. case taicpu(hp1).opsize of
  12199. S_B:
  12200. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  12201. S_W:
  12202. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  12203. S_L:
  12204. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  12205. else
  12206. Internalerror(2020102301);
  12207. end;
  12208. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  12209. end
  12210. else
  12211. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  12212. RemoveCurrentP(p);
  12213. if AndTest then
  12214. RemoveInstruction(hp2);
  12215. result:=true;
  12216. exit;
  12217. end;
  12218. end
  12219. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12220. (
  12221. { Bitwise operations only }
  12222. (taicpu(hp1).opcode=A_AND) or
  12223. (taicpu(hp1).opcode=A_TEST) or
  12224. (
  12225. (taicpu(hp1).oper[0]^.typ = top_const) and
  12226. (
  12227. (taicpu(hp1).opcode=A_OR) or
  12228. (taicpu(hp1).opcode=A_XOR)
  12229. )
  12230. )
  12231. ) and
  12232. (
  12233. (taicpu(hp1).oper[0]^.typ = top_const) or
  12234. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  12235. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  12236. ) then
  12237. begin
  12238. { change
  12239. movx %reg2,%reg2
  12240. op const,%reg2
  12241. into
  12242. op const,%reg2 (smaller version)
  12243. movx %reg2,%reg2
  12244. also change
  12245. movx %reg1,%reg2
  12246. and/test (oper),%reg2
  12247. dealloc %reg2
  12248. into
  12249. and/test (oper),%reg1
  12250. }
  12251. case taicpu(p).opsize of
  12252. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12253. begin
  12254. NewSize := S_B;
  12255. NewRegSize := R_SUBL;
  12256. Limit := $FF;
  12257. end;
  12258. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12259. begin
  12260. NewSize := S_W;
  12261. NewRegSize := R_SUBW;
  12262. Limit := $FFFF;
  12263. end;
  12264. {$ifdef x86_64}
  12265. S_LQ:
  12266. begin
  12267. NewSize := S_L;
  12268. NewRegSize := R_SUBD;
  12269. Limit := $FFFFFFFF;
  12270. end;
  12271. {$endif x86_64}
  12272. else
  12273. Internalerror(2021120302);
  12274. end;
  12275. TransferUsedRegs(TmpUsedRegs);
  12276. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12277. if AndTest then
  12278. begin
  12279. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12280. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12281. end
  12282. else
  12283. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12284. if
  12285. (
  12286. (taicpu(p).opcode = A_MOVZX) and
  12287. (
  12288. (taicpu(hp1).opcode=A_AND) or
  12289. (taicpu(hp1).opcode=A_TEST)
  12290. ) and
  12291. not (
  12292. { If both are references, then the final instruction will have
  12293. both operands as references, which is not allowed }
  12294. (taicpu(p).oper[0]^.typ = top_ref) and
  12295. (taicpu(hp1).oper[0]^.typ = top_ref)
  12296. ) and
  12297. not RegUsed
  12298. ) or
  12299. (
  12300. (
  12301. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  12302. not RegUsed
  12303. ) and
  12304. (taicpu(p).oper[0]^.typ = top_reg) and
  12305. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12306. (taicpu(hp1).oper[0]^.typ = top_const) and
  12307. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  12308. ) then
  12309. begin
  12310. {$if defined(i386) or defined(i8086)}
  12311. { If the target size is 8-bit, make sure we can actually encode it }
  12312. 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
  12313. Exit;
  12314. {$endif i386 or i8086}
  12315. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  12316. taicpu(hp1).opsize := NewSize;
  12317. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12318. if AndTest then
  12319. begin
  12320. RemoveInstruction(hp2);
  12321. if not RegUsed then
  12322. begin
  12323. taicpu(hp1).opcode := A_TEST;
  12324. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  12325. begin
  12326. { Make sure the reference is the second operand }
  12327. SwapOper := taicpu(hp1).oper[0];
  12328. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  12329. taicpu(hp1).oper[1] := SwapOper;
  12330. end;
  12331. end;
  12332. end;
  12333. case taicpu(hp1).oper[0]^.typ of
  12334. top_reg:
  12335. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  12336. top_const:
  12337. { For the AND/TEST case }
  12338. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  12339. else
  12340. ;
  12341. end;
  12342. if RegUsed then
  12343. begin
  12344. AsmL.Remove(p);
  12345. AsmL.InsertAfter(p, hp1);
  12346. p := hp1;
  12347. end
  12348. else
  12349. RemoveCurrentP(p, hp1);
  12350. result:=true;
  12351. exit;
  12352. end;
  12353. end;
  12354. end;
  12355. if reg_and_hp1_is_instr and
  12356. (taicpu(p).oper[0]^.typ = top_reg) and
  12357. (
  12358. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  12359. ) and
  12360. (taicpu(hp1).oper[0]^.typ = top_const) and
  12361. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12362. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12363. { Minimum shift value allowed is the bit difference between the sizes }
  12364. (taicpu(hp1).oper[0]^.val >=
  12365. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12366. 8 * (
  12367. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  12368. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12369. )
  12370. ) then
  12371. begin
  12372. { For:
  12373. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  12374. shl/sal ##, %reg1
  12375. Remove the movsx/movzx instruction if the shift overwrites the
  12376. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  12377. }
  12378. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  12379. RemoveCurrentP(p, hp1);
  12380. Result := True;
  12381. Exit;
  12382. end
  12383. else if reg_and_hp1_is_instr and
  12384. (taicpu(p).oper[0]^.typ = top_reg) and
  12385. (
  12386. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  12387. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  12388. ) and
  12389. (taicpu(hp1).oper[0]^.typ = top_const) and
  12390. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12391. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12392. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  12393. (taicpu(hp1).oper[0]^.val <
  12394. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12395. 8 * (
  12396. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12397. )
  12398. ) then
  12399. begin
  12400. { For:
  12401. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  12402. sar ##, %reg1 shr ##, %reg1
  12403. Move the shift to before the movx instruction if the shift value
  12404. is not too large.
  12405. }
  12406. asml.Remove(hp1);
  12407. asml.InsertBefore(hp1, p);
  12408. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12409. case taicpu(p).opsize of
  12410. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  12411. taicpu(hp1).opsize := S_B;
  12412. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  12413. taicpu(hp1).opsize := S_W;
  12414. {$ifdef x86_64}
  12415. S_LQ:
  12416. taicpu(hp1).opsize := S_L;
  12417. {$endif}
  12418. else
  12419. InternalError(2020112401);
  12420. end;
  12421. if (taicpu(hp1).opcode = A_SHR) then
  12422. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  12423. else
  12424. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  12425. Result := True;
  12426. end;
  12427. if reg_and_hp1_is_instr and
  12428. (taicpu(p).oper[0]^.typ = top_reg) and
  12429. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12430. (
  12431. (taicpu(hp1).opcode = taicpu(p).opcode)
  12432. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  12433. {$ifdef x86_64}
  12434. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  12435. {$endif x86_64}
  12436. ) then
  12437. begin
  12438. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12439. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  12440. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12441. begin
  12442. {
  12443. For example:
  12444. movzbw %al,%ax
  12445. movzwl %ax,%eax
  12446. Compress into:
  12447. movzbl %al,%eax
  12448. }
  12449. RegUsed := False;
  12450. case taicpu(p).opsize of
  12451. S_BW:
  12452. case taicpu(hp1).opsize of
  12453. S_WL:
  12454. begin
  12455. taicpu(p).opsize := S_BL;
  12456. RegUsed := True;
  12457. end;
  12458. {$ifdef x86_64}
  12459. S_WQ:
  12460. begin
  12461. if taicpu(p).opcode = A_MOVZX then
  12462. begin
  12463. taicpu(p).opsize := S_BL;
  12464. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12465. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12466. end
  12467. else
  12468. taicpu(p).opsize := S_BQ;
  12469. RegUsed := True;
  12470. end;
  12471. {$endif x86_64}
  12472. else
  12473. ;
  12474. end;
  12475. {$ifdef x86_64}
  12476. S_BL:
  12477. case taicpu(hp1).opsize of
  12478. S_LQ:
  12479. begin
  12480. if taicpu(p).opcode = A_MOVZX then
  12481. begin
  12482. taicpu(p).opsize := S_BL;
  12483. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12484. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12485. end
  12486. else
  12487. taicpu(p).opsize := S_BQ;
  12488. RegUsed := True;
  12489. end;
  12490. else
  12491. ;
  12492. end;
  12493. S_WL:
  12494. case taicpu(hp1).opsize of
  12495. S_LQ:
  12496. begin
  12497. if taicpu(p).opcode = A_MOVZX then
  12498. begin
  12499. taicpu(p).opsize := S_WL;
  12500. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12501. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12502. end
  12503. else
  12504. taicpu(p).opsize := S_WQ;
  12505. RegUsed := True;
  12506. end;
  12507. else
  12508. ;
  12509. end;
  12510. {$endif x86_64}
  12511. else
  12512. ;
  12513. end;
  12514. if RegUsed then
  12515. begin
  12516. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  12517. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  12518. RemoveInstruction(hp1);
  12519. Result := True;
  12520. Exit;
  12521. end;
  12522. end;
  12523. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12524. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  12525. GetNextInstruction(hp1, hp2) and
  12526. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  12527. (
  12528. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  12529. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  12530. {$ifdef x86_64}
  12531. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  12532. {$endif x86_64}
  12533. ) and
  12534. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  12535. (
  12536. (
  12537. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  12538. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12539. ) or
  12540. (
  12541. { Only allow the operands in reverse order for TEST instructions }
  12542. (taicpu(hp2).opcode = A_TEST) and
  12543. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12544. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  12545. )
  12546. ) then
  12547. begin
  12548. {
  12549. For example:
  12550. movzbl %al,%eax
  12551. movzbl (ref),%edx
  12552. andl %edx,%eax
  12553. (%edx deallocated)
  12554. Change to:
  12555. andb (ref),%al
  12556. movzbl %al,%eax
  12557. Rules are:
  12558. - First two instructions have the same opcode and opsize
  12559. - First instruction's operands are the same super-register
  12560. - Second instruction operates on a different register
  12561. - Third instruction is AND, OR, XOR or TEST
  12562. - Third instruction's operands are the destination registers of the first two instructions
  12563. - Third instruction writes to the destination register of the first instruction (except with TEST)
  12564. - Second instruction's destination register is deallocated afterwards
  12565. }
  12566. TransferUsedRegs(TmpUsedRegs);
  12567. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12568. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12569. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  12570. begin
  12571. case taicpu(p).opsize of
  12572. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12573. NewSize := S_B;
  12574. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12575. NewSize := S_W;
  12576. {$ifdef x86_64}
  12577. S_LQ:
  12578. NewSize := S_L;
  12579. {$endif x86_64}
  12580. else
  12581. InternalError(2021120301);
  12582. end;
  12583. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  12584. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  12585. taicpu(hp2).opsize := NewSize;
  12586. RemoveInstruction(hp1);
  12587. { With TEST, it's best to keep the MOVX instruction at the top }
  12588. if (taicpu(hp2).opcode <> A_TEST) then
  12589. begin
  12590. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  12591. asml.Remove(p);
  12592. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  12593. asml.InsertAfter(p, hp2);
  12594. p := hp2;
  12595. end
  12596. else
  12597. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  12598. Result := True;
  12599. Exit;
  12600. end;
  12601. end;
  12602. end;
  12603. if taicpu(p).opcode=A_MOVZX then
  12604. begin
  12605. { removes superfluous And's after movzx's }
  12606. if reg_and_hp1_is_instr and
  12607. (taicpu(hp1).opcode = A_AND) and
  12608. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12609. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12610. {$ifdef x86_64}
  12611. { check for implicit extension to 64 bit }
  12612. or
  12613. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12614. (taicpu(hp1).opsize=S_Q) and
  12615. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12616. )
  12617. {$endif x86_64}
  12618. )
  12619. then
  12620. begin
  12621. case taicpu(p).opsize Of
  12622. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12623. if (taicpu(hp1).oper[0]^.val = $ff) then
  12624. begin
  12625. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12626. RemoveInstruction(hp1);
  12627. Result:=true;
  12628. exit;
  12629. end;
  12630. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12631. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12632. begin
  12633. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12634. RemoveInstruction(hp1);
  12635. Result:=true;
  12636. exit;
  12637. end;
  12638. {$ifdef x86_64}
  12639. S_LQ:
  12640. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12641. begin
  12642. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12643. RemoveInstruction(hp1);
  12644. Result:=true;
  12645. exit;
  12646. end;
  12647. {$endif x86_64}
  12648. else
  12649. ;
  12650. end;
  12651. { we cannot get rid of the and, but can we get rid of the movz ?}
  12652. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12653. begin
  12654. case taicpu(p).opsize Of
  12655. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12656. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12657. begin
  12658. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12659. RemoveCurrentP(p,hp1);
  12660. Result:=true;
  12661. exit;
  12662. end;
  12663. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12664. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12665. begin
  12666. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12667. RemoveCurrentP(p,hp1);
  12668. Result:=true;
  12669. exit;
  12670. end;
  12671. {$ifdef x86_64}
  12672. S_LQ:
  12673. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12674. begin
  12675. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12676. RemoveCurrentP(p,hp1);
  12677. Result:=true;
  12678. exit;
  12679. end;
  12680. {$endif x86_64}
  12681. else
  12682. ;
  12683. end;
  12684. end;
  12685. end;
  12686. { changes some movzx constructs to faster synonyms (all examples
  12687. are given with eax/ax, but are also valid for other registers)}
  12688. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12689. begin
  12690. case taicpu(p).opsize of
  12691. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12692. (the machine code is equivalent to movzbl %al,%eax), but the
  12693. code generator still generates that assembler instruction and
  12694. it is silently converted. This should probably be checked.
  12695. [Kit] }
  12696. S_BW:
  12697. begin
  12698. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12699. (
  12700. not IsMOVZXAcceptable
  12701. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12702. or (
  12703. (cs_opt_size in current_settings.optimizerswitches) and
  12704. (taicpu(p).oper[1]^.reg = NR_AX)
  12705. )
  12706. ) then
  12707. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12708. begin
  12709. DebugMsg(SPeepholeOptimization + 'var7',p);
  12710. taicpu(p).opcode := A_AND;
  12711. taicpu(p).changeopsize(S_W);
  12712. taicpu(p).loadConst(0,$ff);
  12713. Result := True;
  12714. end
  12715. else if not IsMOVZXAcceptable and
  12716. GetNextInstruction(p, hp1) and
  12717. (tai(hp1).typ = ait_instruction) and
  12718. (taicpu(hp1).opcode = A_AND) and
  12719. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12720. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12721. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12722. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12723. begin
  12724. DebugMsg(SPeepholeOptimization + 'var8',p);
  12725. taicpu(p).opcode := A_MOV;
  12726. taicpu(p).changeopsize(S_W);
  12727. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12728. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12729. Result := True;
  12730. end;
  12731. end;
  12732. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12733. S_BL:
  12734. if not IsMOVZXAcceptable then
  12735. begin
  12736. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12737. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  12738. begin
  12739. DebugMsg(SPeepholeOptimization + 'var9',p);
  12740. taicpu(p).opcode := A_AND;
  12741. taicpu(p).changeopsize(S_L);
  12742. taicpu(p).loadConst(0,$ff);
  12743. Result := True;
  12744. end
  12745. else if GetNextInstruction(p, hp1) and
  12746. (tai(hp1).typ = ait_instruction) and
  12747. (taicpu(hp1).opcode = A_AND) and
  12748. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12749. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12750. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  12751. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  12752. begin
  12753. DebugMsg(SPeepholeOptimization + 'var10',p);
  12754. taicpu(p).opcode := A_MOV;
  12755. taicpu(p).changeopsize(S_L);
  12756. { do not use R_SUBWHOLE
  12757. as movl %rdx,%eax
  12758. is invalid in assembler PM }
  12759. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12760. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12761. Result := True;
  12762. end;
  12763. end;
  12764. {$endif i8086}
  12765. S_WL:
  12766. if not IsMOVZXAcceptable then
  12767. begin
  12768. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12769. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  12770. begin
  12771. DebugMsg(SPeepholeOptimization + 'var11',p);
  12772. taicpu(p).opcode := A_AND;
  12773. taicpu(p).changeopsize(S_L);
  12774. taicpu(p).loadConst(0,$ffff);
  12775. Result := True;
  12776. end
  12777. else if GetNextInstruction(p, hp1) and
  12778. (tai(hp1).typ = ait_instruction) and
  12779. (taicpu(hp1).opcode = A_AND) and
  12780. (taicpu(hp1).oper[0]^.typ = top_const) and
  12781. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12782. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12783. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  12784. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  12785. begin
  12786. DebugMsg(SPeepholeOptimization + 'var12',p);
  12787. taicpu(p).opcode := A_MOV;
  12788. taicpu(p).changeopsize(S_L);
  12789. { do not use R_SUBWHOLE
  12790. as movl %rdx,%eax
  12791. is invalid in assembler PM }
  12792. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12793. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12794. Result := True;
  12795. end;
  12796. end;
  12797. else
  12798. InternalError(2017050705);
  12799. end;
  12800. end
  12801. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  12802. begin
  12803. if GetNextInstruction(p, hp1) and
  12804. (tai(hp1).typ = ait_instruction) and
  12805. (taicpu(hp1).opcode = A_AND) and
  12806. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12807. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12808. begin
  12809. //taicpu(p).opcode := A_MOV;
  12810. case taicpu(p).opsize Of
  12811. S_BL:
  12812. begin
  12813. DebugMsg(SPeepholeOptimization + 'var13',p);
  12814. taicpu(hp1).changeopsize(S_L);
  12815. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12816. end;
  12817. S_WL:
  12818. begin
  12819. DebugMsg(SPeepholeOptimization + 'var14',p);
  12820. taicpu(hp1).changeopsize(S_L);
  12821. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12822. end;
  12823. S_BW:
  12824. begin
  12825. DebugMsg(SPeepholeOptimization + 'var15',p);
  12826. taicpu(hp1).changeopsize(S_W);
  12827. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12828. end;
  12829. else
  12830. Internalerror(2017050704)
  12831. end;
  12832. Result := True;
  12833. end;
  12834. end;
  12835. end;
  12836. end;
  12837. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  12838. var
  12839. hp1, hp2 : tai;
  12840. MaskLength : Cardinal;
  12841. MaskedBits : TCgInt;
  12842. ActiveReg : TRegister;
  12843. begin
  12844. Result:=false;
  12845. { There are no optimisations for reference targets }
  12846. if (taicpu(p).oper[1]^.typ <> top_reg) then
  12847. Exit;
  12848. while GetNextInstruction(p, hp1) and
  12849. (hp1.typ = ait_instruction) do
  12850. begin
  12851. if (taicpu(p).oper[0]^.typ = top_const) then
  12852. begin
  12853. case taicpu(hp1).opcode of
  12854. A_AND:
  12855. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12856. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12857. { the second register must contain the first one, so compare their subreg types }
  12858. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  12859. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  12860. { change
  12861. and const1, reg
  12862. and const2, reg
  12863. to
  12864. and (const1 and const2), reg
  12865. }
  12866. begin
  12867. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  12868. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  12869. RemoveCurrentP(p, hp1);
  12870. Result:=true;
  12871. exit;
  12872. end;
  12873. A_CMP:
  12874. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  12875. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  12876. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12877. { Just check that the condition on the next instruction is compatible }
  12878. GetNextInstruction(hp1, hp2) and
  12879. (hp2.typ = ait_instruction) and
  12880. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  12881. then
  12882. { change
  12883. and 2^n, reg
  12884. cmp 2^n, reg
  12885. j(c) / set(c) / cmov(c) (c is equal or not equal)
  12886. to
  12887. and 2^n, reg
  12888. test reg, reg
  12889. j(~c) / set(~c) / cmov(~c)
  12890. }
  12891. begin
  12892. { Keep TEST instruction in, rather than remove it, because
  12893. it may trigger other optimisations such as MovAndTest2Test }
  12894. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  12895. taicpu(hp1).opcode := A_TEST;
  12896. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  12897. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  12898. Result := True;
  12899. Exit;
  12900. end
  12901. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  12902. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12903. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  12904. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  12905. { change
  12906. and $ff/$ff/$ffff, reg
  12907. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  12908. dealloc reg
  12909. to
  12910. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  12911. }
  12912. begin
  12913. TransferUsedRegs(TmpUsedRegs);
  12914. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12915. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  12916. begin
  12917. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  12918. case taicpu(p).oper[0]^.val of
  12919. $ff:
  12920. begin
  12921. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  12922. taicpu(hp1).opsize:=S_B;
  12923. end;
  12924. $ffff:
  12925. begin
  12926. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  12927. taicpu(hp1).opsize:=S_W;
  12928. end;
  12929. $ffffffff:
  12930. begin
  12931. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12932. taicpu(hp1).opsize:=S_L;
  12933. end;
  12934. else
  12935. Internalerror(2023030401);
  12936. end;
  12937. RemoveCurrentP(p);
  12938. Result := True;
  12939. Exit;
  12940. end;
  12941. end;
  12942. A_MOVZX:
  12943. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12944. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  12945. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12946. (
  12947. (
  12948. (taicpu(p).opsize=S_W) and
  12949. (taicpu(hp1).opsize=S_BW)
  12950. ) or
  12951. (
  12952. (taicpu(p).opsize=S_L) and
  12953. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  12954. )
  12955. {$ifdef x86_64}
  12956. or
  12957. (
  12958. (taicpu(p).opsize=S_Q) and
  12959. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  12960. )
  12961. {$endif x86_64}
  12962. ) then
  12963. begin
  12964. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12965. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  12966. ) or
  12967. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12968. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  12969. then
  12970. begin
  12971. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  12972. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  12973. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  12974. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  12975. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  12976. }
  12977. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  12978. RemoveInstruction(hp1);
  12979. { See if there are other optimisations possible }
  12980. Continue;
  12981. end;
  12982. end;
  12983. A_SHL:
  12984. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12985. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  12986. begin
  12987. {$ifopt R+}
  12988. {$define RANGE_WAS_ON}
  12989. {$R-}
  12990. {$endif}
  12991. { get length of potential and mask }
  12992. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  12993. { really a mask? }
  12994. {$ifdef RANGE_WAS_ON}
  12995. {$R+}
  12996. {$endif}
  12997. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  12998. { unmasked part shifted out? }
  12999. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13000. begin
  13001. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13002. RemoveCurrentP(p, hp1);
  13003. Result:=true;
  13004. exit;
  13005. end;
  13006. end;
  13007. A_SHR:
  13008. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13009. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13010. (taicpu(hp1).oper[0]^.val <= 63) then
  13011. begin
  13012. { Does SHR combined with the AND cover all the bits?
  13013. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13014. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13015. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13016. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13017. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13018. begin
  13019. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13020. RemoveCurrentP(p, hp1);
  13021. Result := True;
  13022. Exit;
  13023. end;
  13024. end;
  13025. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13026. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13027. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13028. begin
  13029. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13030. (
  13031. (
  13032. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13033. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  13034. ) or (
  13035. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13036. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  13037. {$ifdef x86_64}
  13038. ) or (
  13039. (taicpu(hp1).opsize = S_LQ) and
  13040. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  13041. {$endif x86_64}
  13042. )
  13043. ) then
  13044. begin
  13045. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  13046. begin
  13047. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  13048. RemoveInstruction(hp1);
  13049. { See if there are other optimisations possible }
  13050. Continue;
  13051. end;
  13052. { The super-registers are the same though.
  13053. Note that this change by itself doesn't improve
  13054. code speed, but it opens up other optimisations. }
  13055. {$ifdef x86_64}
  13056. { Convert 64-bit register to 32-bit }
  13057. case taicpu(hp1).opsize of
  13058. S_BQ:
  13059. begin
  13060. taicpu(hp1).opsize := S_BL;
  13061. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13062. end;
  13063. S_WQ:
  13064. begin
  13065. taicpu(hp1).opsize := S_WL;
  13066. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13067. end
  13068. else
  13069. ;
  13070. end;
  13071. {$endif x86_64}
  13072. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  13073. taicpu(hp1).opcode := A_MOVZX;
  13074. { See if there are other optimisations possible }
  13075. Continue;
  13076. end;
  13077. end;
  13078. else
  13079. ;
  13080. end;
  13081. end
  13082. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  13083. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13084. begin
  13085. {$ifdef x86_64}
  13086. if (taicpu(p).opsize = S_Q) then
  13087. begin
  13088. { Never necessary }
  13089. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  13090. RemoveCurrentP(p, hp1);
  13091. Result := True;
  13092. Exit;
  13093. end;
  13094. {$endif x86_64}
  13095. { Forward check to determine necessity of and %reg,%reg }
  13096. TransferUsedRegs(TmpUsedRegs);
  13097. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13098. { Saves on a bunch of dereferences }
  13099. ActiveReg := taicpu(p).oper[1]^.reg;
  13100. case taicpu(hp1).opcode of
  13101. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13102. if (
  13103. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13104. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13105. ) and
  13106. (
  13107. (taicpu(hp1).opcode <> A_MOV) or
  13108. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  13109. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  13110. ) and
  13111. not (
  13112. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  13113. (taicpu(hp1).opcode = A_MOV) and
  13114. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  13115. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  13116. ) and
  13117. (
  13118. (
  13119. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13120. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  13121. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  13122. ) or
  13123. (
  13124. {$ifdef x86_64}
  13125. (
  13126. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  13127. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  13128. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  13129. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  13130. ) and
  13131. {$endif x86_64}
  13132. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  13133. )
  13134. ) then
  13135. begin
  13136. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  13137. RemoveCurrentP(p, hp1);
  13138. Result := True;
  13139. Exit;
  13140. end;
  13141. A_ADD,
  13142. A_AND,
  13143. A_BSF,
  13144. A_BSR,
  13145. A_BTC,
  13146. A_BTR,
  13147. A_BTS,
  13148. A_OR,
  13149. A_SUB,
  13150. A_XOR:
  13151. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  13152. if (
  13153. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13154. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13155. ) and
  13156. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  13157. begin
  13158. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  13159. RemoveCurrentP(p, hp1);
  13160. Result := True;
  13161. Exit;
  13162. end;
  13163. A_CMP,
  13164. A_TEST:
  13165. if (
  13166. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13167. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13168. ) and
  13169. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  13170. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  13171. begin
  13172. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  13173. RemoveCurrentP(p, hp1);
  13174. Result := True;
  13175. Exit;
  13176. end;
  13177. A_BSWAP,
  13178. A_NEG,
  13179. A_NOT:
  13180. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  13181. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  13182. begin
  13183. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  13184. RemoveCurrentP(p, hp1);
  13185. Result := True;
  13186. Exit;
  13187. end;
  13188. else
  13189. ;
  13190. end;
  13191. end;
  13192. if (taicpu(hp1).is_jmp) and
  13193. (taicpu(hp1).opcode<>A_JMP) and
  13194. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  13195. begin
  13196. { change
  13197. and x, reg
  13198. jxx
  13199. to
  13200. test x, reg
  13201. jxx
  13202. if reg is deallocated before the
  13203. jump, but only if it's a conditional jump (PFV)
  13204. }
  13205. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  13206. taicpu(p).opcode := A_TEST;
  13207. Exit;
  13208. end;
  13209. Break;
  13210. end;
  13211. { Lone AND tests }
  13212. if (taicpu(p).oper[0]^.typ = top_const) then
  13213. begin
  13214. {
  13215. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  13216. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  13217. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  13218. }
  13219. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  13220. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  13221. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  13222. begin
  13223. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  13224. if taicpu(p).opsize = S_L then
  13225. begin
  13226. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  13227. Result := True;
  13228. end;
  13229. end;
  13230. end;
  13231. { Backward check to determine necessity of and %reg,%reg }
  13232. if (taicpu(p).oper[0]^.typ = top_reg) and
  13233. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13234. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13235. GetLastInstruction(p, hp2) and
  13236. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  13237. { Check size of adjacent instruction to determine if the AND is
  13238. effectively a null operation }
  13239. (
  13240. (taicpu(p).opsize = taicpu(hp2).opsize) or
  13241. { Note: Don't include S_Q }
  13242. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  13243. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  13244. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  13245. ) then
  13246. begin
  13247. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  13248. { If GetNextInstruction returned False, hp1 will be nil }
  13249. RemoveCurrentP(p, hp1);
  13250. Result := True;
  13251. Exit;
  13252. end;
  13253. end;
  13254. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  13255. var
  13256. hp1, hp2: tai;
  13257. NewRef: TReference;
  13258. Distance: Cardinal;
  13259. TempTracking: TAllUsedRegs;
  13260. { This entire nested function is used in an if-statement below, but we
  13261. want to avoid all the used reg transfers and GetNextInstruction calls
  13262. until we really have to check }
  13263. function MemRegisterNotUsedLater: Boolean; inline;
  13264. var
  13265. hp2: tai;
  13266. begin
  13267. TransferUsedRegs(TmpUsedRegs);
  13268. hp2 := p;
  13269. repeat
  13270. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13271. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13272. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  13273. end;
  13274. begin
  13275. Result := False;
  13276. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13277. (taicpu(p).oper[1]^.typ = top_reg) then
  13278. begin
  13279. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13280. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13281. (hp1.typ <> ait_instruction) or
  13282. not
  13283. (
  13284. (cs_opt_level3 in current_settings.optimizerswitches) or
  13285. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13286. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13287. ) then
  13288. Exit;
  13289. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13290. addq $x, %rax
  13291. movq %rax, %rdx
  13292. sarq $63, %rdx
  13293. (%rax still in use)
  13294. ...letting OptPass2ADD run its course (and without -Os) will produce:
  13295. leaq $x(%rax),%rdx
  13296. addq $x, %rax
  13297. sarq $63, %rdx
  13298. ...which is okay since it breaks the dependency chain between
  13299. addq and movq, but if OptPass2MOV is called first:
  13300. addq $x, %rax
  13301. cqto
  13302. ...which is better in all ways, taking only 2 cycles to execute
  13303. and much smaller in code size.
  13304. }
  13305. { The extra register tracking is quite strenuous }
  13306. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13307. MatchInstruction(hp1, A_MOV, []) then
  13308. begin
  13309. { Update the register tracking to the MOV instruction }
  13310. CopyUsedRegs(TempTracking);
  13311. hp2 := p;
  13312. repeat
  13313. UpdateUsedRegs(tai(hp2.Next));
  13314. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13315. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13316. OptPass2ADD get called again }
  13317. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13318. begin
  13319. { Reset the tracking to the current instruction }
  13320. RestoreUsedRegs(TempTracking);
  13321. ReleaseUsedRegs(TempTracking);
  13322. Result := True;
  13323. Exit;
  13324. end;
  13325. { Reset the tracking to the current instruction }
  13326. RestoreUsedRegs(TempTracking);
  13327. ReleaseUsedRegs(TempTracking);
  13328. { If OptPass2MOV returned True, we don't need to set Result to
  13329. True if hp1 didn't change because the ADD instruction didn't
  13330. get modified and we'll be evaluating hp1 again when the
  13331. peephole optimizer reaches it }
  13332. end;
  13333. { Change:
  13334. add %reg2,%reg1
  13335. (%reg2 not modified in between)
  13336. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  13337. To:
  13338. mov/s/z #(%reg1,%reg2),%reg1
  13339. }
  13340. if (taicpu(p).oper[0]^.typ = top_reg) and
  13341. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  13342. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  13343. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  13344. (
  13345. (
  13346. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  13347. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  13348. { r/esp cannot be an index }
  13349. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  13350. ) or (
  13351. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  13352. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  13353. )
  13354. ) and (
  13355. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  13356. (
  13357. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  13358. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13359. MemRegisterNotUsedLater
  13360. )
  13361. ) then
  13362. begin
  13363. if (
  13364. { Instructions are guaranteed to be adjacent on -O2 and under }
  13365. (cs_opt_level3 in current_settings.optimizerswitches) and
  13366. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  13367. ) then
  13368. begin
  13369. { If the other register is used in between, move the MOV
  13370. instruction to right after the ADD instruction so a
  13371. saving can still be made }
  13372. Asml.Remove(hp1);
  13373. Asml.InsertAfter(hp1, p);
  13374. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13375. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13376. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  13377. RemoveCurrentp(p, hp1);
  13378. end
  13379. else
  13380. begin
  13381. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  13382. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13383. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13384. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  13385. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13386. { hp1 may not be the immediate next instruction under -O3 }
  13387. RemoveCurrentp(p)
  13388. else
  13389. RemoveCurrentp(p, hp1);
  13390. end;
  13391. Result := True;
  13392. Exit;
  13393. end;
  13394. { Change:
  13395. addl/q $x,%reg1
  13396. movl/q %reg1,%reg2
  13397. To:
  13398. leal/q $x(%reg1),%reg2
  13399. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13400. Breaks the dependency chain.
  13401. }
  13402. if (taicpu(p).oper[0]^.typ = top_const) and
  13403. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13404. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13405. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13406. (
  13407. { Instructions are guaranteed to be adjacent on -O2 and under }
  13408. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13409. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13410. ) then
  13411. begin
  13412. TransferUsedRegs(TmpUsedRegs);
  13413. hp2 := p;
  13414. repeat
  13415. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13416. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13417. if (
  13418. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  13419. not (cs_opt_size in current_settings.optimizerswitches) or
  13420. (
  13421. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13422. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13423. )
  13424. ) then
  13425. begin
  13426. { Change the MOV instruction to a LEA instruction, and update the
  13427. first operand }
  13428. reference_reset(NewRef, 1, []);
  13429. NewRef.base := taicpu(p).oper[1]^.reg;
  13430. NewRef.scalefactor := 1;
  13431. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  13432. taicpu(hp1).opcode := A_LEA;
  13433. taicpu(hp1).loadref(0, NewRef);
  13434. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13435. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13436. begin
  13437. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13438. { Move what is now the LEA instruction to before the ADD instruction }
  13439. Asml.Remove(hp1);
  13440. Asml.InsertBefore(hp1, p);
  13441. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13442. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  13443. p := hp1;
  13444. end
  13445. else
  13446. begin
  13447. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13448. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  13449. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13450. { hp1 may not be the immediate next instruction under -O3 }
  13451. RemoveCurrentp(p)
  13452. else
  13453. RemoveCurrentp(p, hp1);
  13454. end;
  13455. Result := True;
  13456. end;
  13457. end;
  13458. end;
  13459. end;
  13460. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  13461. var
  13462. SubReg: TSubRegister;
  13463. begin
  13464. Result:=false;
  13465. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  13466. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13467. with taicpu(p).oper[0]^.ref^ do
  13468. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  13469. begin
  13470. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  13471. begin
  13472. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  13473. taicpu(p).opcode := A_ADD;
  13474. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  13475. Result := True;
  13476. end
  13477. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  13478. begin
  13479. if (base <> NR_NO) then
  13480. begin
  13481. if (scalefactor <= 1) then
  13482. begin
  13483. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  13484. taicpu(p).opcode := A_ADD;
  13485. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  13486. Result := True;
  13487. end;
  13488. end
  13489. else
  13490. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  13491. if (scalefactor in [2, 4, 8]) then
  13492. begin
  13493. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  13494. taicpu(p).loadconst(0, BsrByte(scalefactor));
  13495. taicpu(p).opcode := A_SHL;
  13496. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  13497. Result := True;
  13498. end;
  13499. end;
  13500. end;
  13501. end;
  13502. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  13503. var
  13504. hp1, hp2: tai;
  13505. NewRef: TReference;
  13506. Distance: Cardinal;
  13507. TempTracking: TAllUsedRegs;
  13508. begin
  13509. Result := False;
  13510. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13511. MatchOpType(taicpu(p),top_const,top_reg) then
  13512. begin
  13513. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13514. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13515. (hp1.typ <> ait_instruction) or
  13516. not
  13517. (
  13518. (cs_opt_level3 in current_settings.optimizerswitches) or
  13519. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13520. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13521. ) then
  13522. Exit;
  13523. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13524. subq $x, %rax
  13525. movq %rax, %rdx
  13526. sarq $63, %rdx
  13527. (%rax still in use)
  13528. ...letting OptPass2SUB run its course (and without -Os) will produce:
  13529. leaq $-x(%rax),%rdx
  13530. movq $x, %rax
  13531. sarq $63, %rdx
  13532. ...which is okay since it breaks the dependency chain between
  13533. subq and movq, but if OptPass2MOV is called first:
  13534. subq $x, %rax
  13535. cqto
  13536. ...which is better in all ways, taking only 2 cycles to execute
  13537. and much smaller in code size.
  13538. }
  13539. { The extra register tracking is quite strenuous }
  13540. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13541. MatchInstruction(hp1, A_MOV, []) then
  13542. begin
  13543. { Update the register tracking to the MOV instruction }
  13544. CopyUsedRegs(TempTracking);
  13545. hp2 := p;
  13546. repeat
  13547. UpdateUsedRegs(tai(hp2.Next));
  13548. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13549. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13550. OptPass2SUB get called again }
  13551. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13552. begin
  13553. { Reset the tracking to the current instruction }
  13554. RestoreUsedRegs(TempTracking);
  13555. ReleaseUsedRegs(TempTracking);
  13556. Result := True;
  13557. Exit;
  13558. end;
  13559. { Reset the tracking to the current instruction }
  13560. RestoreUsedRegs(TempTracking);
  13561. ReleaseUsedRegs(TempTracking);
  13562. { If OptPass2MOV returned True, we don't need to set Result to
  13563. True if hp1 didn't change because the SUB instruction didn't
  13564. get modified and we'll be evaluating hp1 again when the
  13565. peephole optimizer reaches it }
  13566. end;
  13567. { Change:
  13568. subl/q $x,%reg1
  13569. movl/q %reg1,%reg2
  13570. To:
  13571. leal/q $-x(%reg1),%reg2
  13572. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13573. Breaks the dependency chain and potentially permits the removal of
  13574. a CMP instruction if one follows.
  13575. }
  13576. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13577. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13578. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13579. (
  13580. { Instructions are guaranteed to be adjacent on -O2 and under }
  13581. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13582. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13583. ) then
  13584. begin
  13585. TransferUsedRegs(TmpUsedRegs);
  13586. hp2 := p;
  13587. repeat
  13588. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13589. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13590. if (
  13591. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  13592. not (cs_opt_size in current_settings.optimizerswitches) or
  13593. (
  13594. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13595. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13596. )
  13597. ) then
  13598. begin
  13599. { Change the MOV instruction to a LEA instruction, and update the
  13600. first operand }
  13601. reference_reset(NewRef, 1, []);
  13602. NewRef.base := taicpu(p).oper[1]^.reg;
  13603. NewRef.scalefactor := 1;
  13604. NewRef.offset := -taicpu(p).oper[0]^.val;
  13605. taicpu(hp1).opcode := A_LEA;
  13606. taicpu(hp1).loadref(0, NewRef);
  13607. TransferUsedRegs(TmpUsedRegs);
  13608. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13609. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13610. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13611. begin
  13612. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13613. { Move what is now the LEA instruction to before the SUB instruction }
  13614. Asml.Remove(hp1);
  13615. Asml.InsertBefore(hp1, p);
  13616. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13617. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  13618. p := hp1;
  13619. end
  13620. else
  13621. begin
  13622. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13623. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  13624. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13625. { hp1 may not be the immediate next instruction under -O3 }
  13626. RemoveCurrentp(p)
  13627. else
  13628. RemoveCurrentp(p, hp1);
  13629. end;
  13630. Result := True;
  13631. end;
  13632. end;
  13633. end;
  13634. end;
  13635. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  13636. begin
  13637. { we can skip all instructions not messing with the stack pointer }
  13638. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  13639. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  13640. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  13641. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  13642. ({(taicpu(hp1).ops=0) or }
  13643. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  13644. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  13645. ) and }
  13646. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  13647. )
  13648. ) do
  13649. GetNextInstruction(hp1,hp1);
  13650. Result:=assigned(hp1);
  13651. end;
  13652. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  13653. var
  13654. hp1, hp2, hp3, hp4, hp5: tai;
  13655. begin
  13656. Result:=false;
  13657. hp5:=nil;
  13658. { replace
  13659. leal(q) x(<stackpointer>),<stackpointer>
  13660. call procname
  13661. leal(q) -x(<stackpointer>),<stackpointer>
  13662. ret
  13663. by
  13664. jmp procname
  13665. but do it only on level 4 because it destroys stack back traces
  13666. }
  13667. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13668. MatchOpType(taicpu(p),top_ref,top_reg) and
  13669. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13670. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  13671. { the -8 or -24 are not required, but bail out early if possible,
  13672. higher values are unlikely }
  13673. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  13674. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  13675. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  13676. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  13677. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13678. GetNextInstruction(p, hp1) and
  13679. { Take a copy of hp1 }
  13680. SetAndTest(hp1, hp4) and
  13681. { trick to skip label }
  13682. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13683. SkipSimpleInstructions(hp1) and
  13684. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13685. GetNextInstruction(hp1, hp2) and
  13686. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  13687. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  13688. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  13689. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13690. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  13691. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  13692. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  13693. { Segment register will be NR_NO }
  13694. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13695. GetNextInstruction(hp2, hp3) and
  13696. { trick to skip label }
  13697. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13698. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13699. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13700. SetAndTest(hp3,hp5) and
  13701. GetNextInstruction(hp3,hp3) and
  13702. MatchInstruction(hp3,A_RET,[S_NO])
  13703. )
  13704. ) and
  13705. (taicpu(hp3).ops=0) then
  13706. begin
  13707. taicpu(hp1).opcode := A_JMP;
  13708. taicpu(hp1).is_jmp := true;
  13709. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  13710. RemoveCurrentP(p, hp4);
  13711. RemoveInstruction(hp2);
  13712. RemoveInstruction(hp3);
  13713. if Assigned(hp5) then
  13714. begin
  13715. AsmL.Remove(hp5);
  13716. ASmL.InsertBefore(hp5,hp1)
  13717. end;
  13718. Result:=true;
  13719. end;
  13720. end;
  13721. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  13722. {$ifdef x86_64}
  13723. var
  13724. hp1, hp2, hp3, hp4, hp5: tai;
  13725. {$endif x86_64}
  13726. begin
  13727. Result:=false;
  13728. {$ifdef x86_64}
  13729. hp5:=nil;
  13730. { replace
  13731. push %rax
  13732. call procname
  13733. pop %rcx
  13734. ret
  13735. by
  13736. jmp procname
  13737. but do it only on level 4 because it destroys stack back traces
  13738. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  13739. for all supported calling conventions
  13740. }
  13741. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13742. MatchOpType(taicpu(p),top_reg) and
  13743. (taicpu(p).oper[0]^.reg=NR_RAX) and
  13744. GetNextInstruction(p, hp1) and
  13745. { Take a copy of hp1 }
  13746. SetAndTest(hp1, hp4) and
  13747. { trick to skip label }
  13748. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13749. SkipSimpleInstructions(hp1) and
  13750. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13751. GetNextInstruction(hp1, hp2) and
  13752. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  13753. MatchOpType(taicpu(hp2),top_reg) and
  13754. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  13755. GetNextInstruction(hp2, hp3) and
  13756. { trick to skip label }
  13757. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13758. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13759. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13760. SetAndTest(hp3,hp5) and
  13761. GetNextInstruction(hp3,hp3) and
  13762. MatchInstruction(hp3,A_RET,[S_NO])
  13763. )
  13764. ) and
  13765. (taicpu(hp3).ops=0) then
  13766. begin
  13767. taicpu(hp1).opcode := A_JMP;
  13768. taicpu(hp1).is_jmp := true;
  13769. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  13770. RemoveCurrentP(p, hp4);
  13771. RemoveInstruction(hp2);
  13772. RemoveInstruction(hp3);
  13773. if Assigned(hp5) then
  13774. begin
  13775. AsmL.Remove(hp5);
  13776. ASmL.InsertBefore(hp5,hp1)
  13777. end;
  13778. Result:=true;
  13779. end;
  13780. {$endif x86_64}
  13781. end;
  13782. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  13783. var
  13784. Value, RegName: string;
  13785. hp1: tai;
  13786. begin
  13787. Result:=false;
  13788. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  13789. begin
  13790. case taicpu(p).oper[0]^.val of
  13791. 0:
  13792. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  13793. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  13794. (
  13795. { See if we can still convert the instruction }
  13796. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  13797. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  13798. ) then
  13799. begin
  13800. { change "mov $0,%reg" into "xor %reg,%reg" }
  13801. taicpu(p).opcode := A_XOR;
  13802. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  13803. Result := True;
  13804. {$ifdef x86_64}
  13805. end
  13806. else if (taicpu(p).opsize = S_Q) then
  13807. begin
  13808. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13809. { The actual optimization }
  13810. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13811. taicpu(p).changeopsize(S_L);
  13812. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13813. Result := True;
  13814. end;
  13815. $1..$FFFFFFFF:
  13816. begin
  13817. { Code size reduction by J. Gareth "Kit" Moreton }
  13818. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  13819. case taicpu(p).opsize of
  13820. S_Q:
  13821. begin
  13822. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13823. Value := debug_tostr(taicpu(p).oper[0]^.val);
  13824. { The actual optimization }
  13825. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13826. taicpu(p).changeopsize(S_L);
  13827. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13828. Result := True;
  13829. end;
  13830. else
  13831. { Do nothing };
  13832. end;
  13833. {$endif x86_64}
  13834. end;
  13835. -1:
  13836. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  13837. if (cs_opt_size in current_settings.optimizerswitches) and
  13838. (taicpu(p).opsize <> S_B) and
  13839. (
  13840. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  13841. (
  13842. { See if we can still convert the instruction }
  13843. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  13844. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  13845. )
  13846. ) then
  13847. begin
  13848. { change "mov $-1,%reg" into "or $-1,%reg" }
  13849. { NOTES:
  13850. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  13851. - This operation creates a false dependency on the register, so only do it when optimising for size
  13852. - 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
  13853. }
  13854. taicpu(p).opcode := A_OR;
  13855. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  13856. Result := True;
  13857. end;
  13858. else
  13859. { Do nothing };
  13860. end;
  13861. end;
  13862. end;
  13863. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  13864. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  13865. begin
  13866. Result := False;
  13867. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  13868. Exit;
  13869. { For sizes less than S_L, the byte size is equal or larger with BTx,
  13870. so don't bother optimising }
  13871. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  13872. Exit;
  13873. if (taicpu(p).oper[0]^.typ <> top_const) or
  13874. { If the value can fit into an 8-bit signed integer, a smaller
  13875. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  13876. falls within this range }
  13877. (
  13878. (taicpu(p).oper[0]^.val > -128) and
  13879. (taicpu(p).oper[0]^.val <= 127)
  13880. ) then
  13881. Exit;
  13882. { If we're optimising for size, this is acceptable }
  13883. if (cs_opt_size in current_settings.optimizerswitches) then
  13884. Exit(True);
  13885. if (taicpu(p).oper[1]^.typ = top_reg) and
  13886. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13887. Exit(True);
  13888. if (taicpu(p).oper[1]^.typ <> top_reg) and
  13889. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13890. Exit(True);
  13891. end;
  13892. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  13893. var
  13894. hp1: tai;
  13895. Value: TCGInt;
  13896. begin
  13897. Result := False;
  13898. if MatchOpType(taicpu(p), top_const, top_reg) then
  13899. begin
  13900. { Detect:
  13901. andw x, %ax (0 <= x < $8000)
  13902. ...
  13903. movzwl %ax,%eax
  13904. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13905. }
  13906. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  13907. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  13908. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  13909. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  13910. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  13911. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  13912. begin
  13913. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  13914. taicpu(hp1).opcode := A_CWDE;
  13915. taicpu(hp1).clearop(0);
  13916. taicpu(hp1).clearop(1);
  13917. taicpu(hp1).ops := 0;
  13918. { A change was made, but not with p, so don't set Result, but
  13919. notify the compiler that a change was made }
  13920. Include(OptsToCheck, aoc_ForceNewIteration);
  13921. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  13922. end;
  13923. end;
  13924. { If "not x" is a power of 2 (popcnt = 1), change:
  13925. and $x, %reg/ref
  13926. To:
  13927. btr lb(x), %reg/ref
  13928. }
  13929. if IsBTXAcceptable(p) and
  13930. (
  13931. { Make sure a TEST doesn't follow that plays with the register }
  13932. not GetNextInstruction(p, hp1) or
  13933. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  13934. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  13935. ) then
  13936. begin
  13937. {$push}{$R-}{$Q-}
  13938. { Value is a sign-extended 32-bit integer - just correct it
  13939. if it's represented as an unsigned value. Also, IsBTXAcceptable
  13940. checks to see if this operand is an immediate. }
  13941. Value := not taicpu(p).oper[0]^.val;
  13942. {$pop}
  13943. {$ifdef x86_64}
  13944. if taicpu(p).opsize = S_L then
  13945. {$endif x86_64}
  13946. Value := Value and $FFFFFFFF;
  13947. if (PopCnt(QWord(Value)) = 1) then
  13948. begin
  13949. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  13950. taicpu(p).opcode := A_BTR;
  13951. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  13952. Result := True;
  13953. Exit;
  13954. end;
  13955. end;
  13956. end;
  13957. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  13958. begin
  13959. Result := False;
  13960. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  13961. Exit;
  13962. { Convert:
  13963. movswl %ax,%eax -> cwtl
  13964. movslq %eax,%rax -> cdqe
  13965. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  13966. refer to the same opcode and depends only on the assembler's
  13967. current operand-size attribute. [Kit]
  13968. }
  13969. with taicpu(p) do
  13970. case opsize of
  13971. S_WL:
  13972. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  13973. begin
  13974. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  13975. opcode := A_CWDE;
  13976. clearop(0);
  13977. clearop(1);
  13978. ops := 0;
  13979. Result := True;
  13980. end;
  13981. {$ifdef x86_64}
  13982. S_LQ:
  13983. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  13984. begin
  13985. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  13986. opcode := A_CDQE;
  13987. clearop(0);
  13988. clearop(1);
  13989. ops := 0;
  13990. Result := True;
  13991. end;
  13992. {$endif x86_64}
  13993. else
  13994. ;
  13995. end;
  13996. end;
  13997. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  13998. var
  13999. hp1, hp2: tai;
  14000. IdentityMask, Shift: TCGInt;
  14001. LimitSize: Topsize;
  14002. DoNotMerge: Boolean;
  14003. begin
  14004. Result := False;
  14005. { All these optimisations work on "shr const,%reg" }
  14006. if not MatchOpType(taicpu(p), top_const, top_reg) then
  14007. Exit;
  14008. DoNotMerge := False;
  14009. Shift := taicpu(p).oper[0]^.val;
  14010. LimitSize := taicpu(p).opsize;
  14011. hp1 := p;
  14012. repeat
  14013. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  14014. Break;
  14015. { Detect:
  14016. shr x, %reg
  14017. and y, %reg
  14018. If and y, %reg doesn't actually change the value of %reg (e.g. with
  14019. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  14020. }
  14021. case taicpu(hp1).opcode of
  14022. A_AND:
  14023. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  14024. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14025. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14026. begin
  14027. { Make sure the FLAGS register isn't in use }
  14028. TransferUsedRegs(TmpUsedRegs);
  14029. hp2 := p;
  14030. repeat
  14031. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14032. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14033. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14034. begin
  14035. { Generate the identity mask }
  14036. case taicpu(p).opsize of
  14037. S_B:
  14038. IdentityMask := $FF shr Shift;
  14039. S_W:
  14040. IdentityMask := $FFFF shr Shift;
  14041. S_L:
  14042. IdentityMask := $FFFFFFFF shr Shift;
  14043. {$ifdef x86_64}
  14044. S_Q:
  14045. { We need to force the operands to be unsigned 64-bit
  14046. integers otherwise the wrong value is generated }
  14047. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  14048. {$endif x86_64}
  14049. else
  14050. InternalError(2022081501);
  14051. end;
  14052. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  14053. begin
  14054. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  14055. { All the possible 1 bits are covered, so we can remove the AND }
  14056. hp2 := tai(hp1.Previous);
  14057. RemoveInstruction(hp1);
  14058. { p wasn't actually changed, so don't set Result to True,
  14059. but a change was nonetheless made elsewhere }
  14060. Include(OptsToCheck, aoc_ForceNewIteration);
  14061. { Do another pass in case other AND or MOVZX instructions
  14062. follow }
  14063. hp1 := hp2;
  14064. Continue;
  14065. end;
  14066. end;
  14067. end;
  14068. A_TEST, A_CMP, A_Jcc:
  14069. { Skip over conditional jumps and relevant comparisons }
  14070. Continue;
  14071. A_MOVZX:
  14072. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14073. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  14074. begin
  14075. { Since the original register is being read as is, subsequent
  14076. SHRs must not be merged at this point }
  14077. DoNotMerge := True;
  14078. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  14079. begin
  14080. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14081. begin
  14082. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  14083. { All the possible 1 bits are covered, so we can remove the AND }
  14084. hp2 := tai(hp1.Previous);
  14085. RemoveInstruction(hp1);
  14086. hp1 := hp2;
  14087. end
  14088. else { Different register target }
  14089. begin
  14090. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  14091. taicpu(hp1).opcode := A_MOV;
  14092. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  14093. case taicpu(hp1).opsize of
  14094. S_BW:
  14095. taicpu(hp1).opsize := S_W;
  14096. S_BL, S_WL:
  14097. taicpu(hp1).opsize := S_L;
  14098. else
  14099. InternalError(2022081503);
  14100. end;
  14101. end;
  14102. end
  14103. else if (Shift > 0) and
  14104. (taicpu(p).opsize = S_W) and
  14105. (taicpu(hp1).opsize = S_WL) and
  14106. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  14107. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  14108. begin
  14109. { Detect:
  14110. shr x, %ax (x > 0)
  14111. ...
  14112. movzwl %ax,%eax
  14113. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14114. }
  14115. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  14116. taicpu(hp1).opcode := A_CWDE;
  14117. taicpu(hp1).clearop(0);
  14118. taicpu(hp1).clearop(1);
  14119. taicpu(hp1).ops := 0;
  14120. end;
  14121. { Move onto the next instruction }
  14122. Continue;
  14123. end;
  14124. A_SHL, A_SAL, A_SHR:
  14125. if (taicpu(hp1).opsize <= LimitSize) and
  14126. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14127. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  14128. begin
  14129. { Make sure the sizes don't exceed the register size limit
  14130. (measured by the shift value falling below the limit) }
  14131. if taicpu(hp1).opsize < LimitSize then
  14132. LimitSize := taicpu(hp1).opsize;
  14133. if taicpu(hp1).opcode = A_SHR then
  14134. Inc(Shift, taicpu(hp1).oper[0]^.val)
  14135. else
  14136. begin
  14137. Dec(Shift, taicpu(hp1).oper[0]^.val);
  14138. DoNotMerge := True;
  14139. end;
  14140. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  14141. Break;
  14142. { Since we've established that the combined shift is within
  14143. limits, we can actually combine the adjacent SHR
  14144. instructions even if they're different sizes }
  14145. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  14146. begin
  14147. hp2 := tai(hp1.Previous);
  14148. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  14149. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  14150. RemoveInstruction(hp1);
  14151. hp1 := hp2;
  14152. end;
  14153. { Move onto the next instruction }
  14154. Continue;
  14155. end;
  14156. else
  14157. ;
  14158. end;
  14159. Break;
  14160. until False;
  14161. { Detect the following (looking backwards):
  14162. shr %cl,%reg
  14163. shr x, %reg
  14164. Swap the two SHR instructions to minimise a pipeline stall.
  14165. }
  14166. if GetLastInstruction(p, hp1) and
  14167. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  14168. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14169. { First operand will be %cl }
  14170. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  14171. { Just to be sure }
  14172. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  14173. begin
  14174. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  14175. { Moving the entries this way ensures the register tracking remains correct }
  14176. Asml.Remove(p);
  14177. Asml.InsertBefore(p, hp1);
  14178. p := hp1;
  14179. { Don't set Result to True because the current instruction is now
  14180. "shr %cl,%reg" and there's nothing more we can do with it }
  14181. end;
  14182. end;
  14183. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  14184. var
  14185. hp1, hp2: tai;
  14186. Opposite, SecondOpposite: TAsmOp;
  14187. NewCond: TAsmCond;
  14188. begin
  14189. Result := False;
  14190. { Change:
  14191. add/sub 128,(dest)
  14192. To:
  14193. sub/add -128,(dest)
  14194. This generaally takes fewer bytes to encode because -128 can be stored
  14195. in a signed byte, whereas +128 cannot.
  14196. }
  14197. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  14198. begin
  14199. if taicpu(p).opcode = A_ADD then
  14200. Opposite := A_SUB
  14201. else
  14202. Opposite := A_ADD;
  14203. { Be careful if the flags are in use, because the CF flag inverts
  14204. when changing from ADD to SUB and vice versa }
  14205. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  14206. GetNextInstruction(p, hp1) then
  14207. begin
  14208. TransferUsedRegs(TmpUsedRegs);
  14209. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  14210. hp2 := hp1;
  14211. { Scan ahead to check if everything's safe }
  14212. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  14213. begin
  14214. if (hp1.typ <> ait_instruction) then
  14215. { Probably unsafe since the flags are still in use }
  14216. Exit;
  14217. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  14218. { Stop searching at an unconditional jump }
  14219. Break;
  14220. if not
  14221. (
  14222. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  14223. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  14224. ) and
  14225. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  14226. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  14227. Exit;
  14228. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14229. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  14230. { Move to the next instruction }
  14231. GetNextInstruction(hp1, hp1);
  14232. end;
  14233. while Assigned(hp2) and (hp2 <> hp1) do
  14234. begin
  14235. NewCond := C_None;
  14236. case taicpu(hp2).condition of
  14237. C_A, C_NBE:
  14238. NewCond := C_BE;
  14239. C_B, C_C, C_NAE:
  14240. NewCond := C_AE;
  14241. C_AE, C_NB, C_NC:
  14242. NewCond := C_B;
  14243. C_BE, C_NA:
  14244. NewCond := C_A;
  14245. else
  14246. { No change needed };
  14247. end;
  14248. if NewCond <> C_None then
  14249. begin
  14250. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  14251. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  14252. taicpu(hp2).condition := NewCond;
  14253. end
  14254. else
  14255. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  14256. begin
  14257. { Because of the flipping of the carry bit, to ensure
  14258. the operation remains equivalent, ADC becomes SBB
  14259. and vice versa, and the constant is not-inverted.
  14260. If multiple ADCs or SBBs appear in a row, each one
  14261. changed causes the carry bit to invert, so they all
  14262. need to be flipped }
  14263. if taicpu(hp2).opcode = A_ADC then
  14264. SecondOpposite := A_SBB
  14265. else
  14266. SecondOpposite := A_ADC;
  14267. if taicpu(hp2).oper[0]^.typ <> top_const then
  14268. { Should have broken out of this optimisation already }
  14269. InternalError(2021112901);
  14270. 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]^) + ' -> ' +
  14271. 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);
  14272. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  14273. taicpu(hp2).opcode := SecondOpposite;
  14274. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  14275. end;
  14276. { Move to the next instruction }
  14277. GetNextInstruction(hp2, hp2);
  14278. end;
  14279. if (hp2 <> hp1) then
  14280. InternalError(2021111501);
  14281. end;
  14282. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  14283. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  14284. taicpu(p).opcode := Opposite;
  14285. taicpu(p).oper[0]^.val := -128;
  14286. { No further optimisations can be made on this instruction, so move
  14287. onto the next one to save time }
  14288. p := tai(p.Next);
  14289. UpdateUsedRegs(p);
  14290. Result := True;
  14291. Exit;
  14292. end;
  14293. { Detect:
  14294. add/sub %reg2,(dest)
  14295. add/sub x, (dest)
  14296. (dest can be a register or a reference)
  14297. Swap the instructions to minimise a pipeline stall. This reverses the
  14298. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  14299. optimisations could be made.
  14300. }
  14301. if (taicpu(p).oper[0]^.typ = top_reg) and
  14302. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  14303. (
  14304. (
  14305. (taicpu(p).oper[1]^.typ = top_reg) and
  14306. { We can try searching further ahead if we're writing to a register }
  14307. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  14308. ) or
  14309. (
  14310. (taicpu(p).oper[1]^.typ = top_ref) and
  14311. GetNextInstruction(p, hp1)
  14312. )
  14313. ) and
  14314. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  14315. (taicpu(hp1).oper[0]^.typ = top_const) and
  14316. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  14317. begin
  14318. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  14319. TransferUsedRegs(TmpUsedRegs);
  14320. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  14321. hp2 := p;
  14322. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  14323. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  14324. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  14325. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14326. begin
  14327. asml.remove(hp1);
  14328. asml.InsertBefore(hp1, p);
  14329. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  14330. Result := True;
  14331. end;
  14332. end;
  14333. end;
  14334. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  14335. var
  14336. hp1: tai;
  14337. begin
  14338. Result:=false;
  14339. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  14340. while GetNextInstruction(p, hp1) and
  14341. TrySwapMovCmp(p, hp1) do
  14342. begin
  14343. if MatchInstruction(hp1, A_MOV, []) then
  14344. begin
  14345. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14346. begin
  14347. { A little hacky, but since CMP doesn't read the flags, only
  14348. modify them, it's safe if they get scrambled by MOV -> XOR }
  14349. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14350. Result := PostPeepholeOptMov(hp1);
  14351. {$ifdef x86_64}
  14352. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14353. { Used to shrink instruction size }
  14354. PostPeepholeOptXor(hp1);
  14355. {$endif x86_64}
  14356. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14357. end
  14358. else
  14359. begin
  14360. Result := PostPeepholeOptMov(hp1);
  14361. {$ifdef x86_64}
  14362. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14363. { Used to shrink instruction size }
  14364. PostPeepholeOptXor(hp1);
  14365. {$endif x86_64}
  14366. end;
  14367. end;
  14368. { Enabling this flag is actually a null operation, but it marks
  14369. the code as 'modified' during this pass }
  14370. Include(OptsToCheck, aoc_ForceNewIteration);
  14371. end;
  14372. { change "cmp $0, %reg" to "test %reg, %reg" }
  14373. if MatchOpType(taicpu(p),top_const,top_reg) and
  14374. (taicpu(p).oper[0]^.val = 0) then
  14375. begin
  14376. taicpu(p).opcode := A_TEST;
  14377. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  14378. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  14379. Result:=true;
  14380. end;
  14381. end;
  14382. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  14383. var
  14384. IsTestConstX, IsValid : Boolean;
  14385. hp1,hp2 : tai;
  14386. begin
  14387. Result:=false;
  14388. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  14389. if (taicpu(p).opcode = A_TEST) then
  14390. while GetNextInstruction(p, hp1) and
  14391. TrySwapMovCmp(p, hp1) do
  14392. begin
  14393. if MatchInstruction(hp1, A_MOV, []) then
  14394. begin
  14395. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14396. begin
  14397. { A little hacky, but since TEST doesn't read the flags, only
  14398. modify them, it's safe if they get scrambled by MOV -> XOR }
  14399. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14400. Result := PostPeepholeOptMov(hp1);
  14401. {$ifdef x86_64}
  14402. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14403. { Used to shrink instruction size }
  14404. PostPeepholeOptXor(hp1);
  14405. {$endif x86_64}
  14406. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14407. end
  14408. else
  14409. begin
  14410. Result := PostPeepholeOptMov(hp1);
  14411. {$ifdef x86_64}
  14412. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14413. { Used to shrink instruction size }
  14414. PostPeepholeOptXor(hp1);
  14415. {$endif x86_64}
  14416. end;
  14417. end;
  14418. { Enabling this flag is actually a null operation, but it marks
  14419. the code as 'modified' during this pass }
  14420. Include(OptsToCheck, aoc_ForceNewIteration);
  14421. end;
  14422. { If x is a power of 2 (popcnt = 1), change:
  14423. or $x, %reg/ref
  14424. To:
  14425. bts lb(x), %reg/ref
  14426. }
  14427. if (taicpu(p).opcode = A_OR) and
  14428. IsBTXAcceptable(p) and
  14429. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14430. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14431. (
  14432. { Don't optimise if a test instruction follows }
  14433. not GetNextInstruction(p, hp1) or
  14434. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14435. ) then
  14436. begin
  14437. 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);
  14438. taicpu(p).opcode := A_BTS;
  14439. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14440. Result := True;
  14441. Exit;
  14442. end;
  14443. { If x is a power of 2 (popcnt = 1), change:
  14444. test $x, %reg/ref
  14445. je / sete / cmove (or jne / setne)
  14446. To:
  14447. bt lb(x), %reg/ref
  14448. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  14449. }
  14450. if (taicpu(p).opcode = A_TEST) and
  14451. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  14452. (taicpu(p).oper[0]^.typ = top_const) and
  14453. (
  14454. (cs_opt_size in current_settings.optimizerswitches) or
  14455. (
  14456. (taicpu(p).oper[1]^.typ = top_reg) and
  14457. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14458. ) or
  14459. (
  14460. (taicpu(p).oper[1]^.typ <> top_reg) and
  14461. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14462. )
  14463. ) and
  14464. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14465. { For sizes less than S_L, the byte size is equal or larger with BT,
  14466. so don't bother optimising }
  14467. (taicpu(p).opsize >= S_L) then
  14468. begin
  14469. IsValid := True;
  14470. { Check the next set of instructions, watching the FLAGS register
  14471. and the conditions used }
  14472. TransferUsedRegs(TmpUsedRegs);
  14473. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14474. hp1 := p;
  14475. hp2 := nil;
  14476. while GetNextInstruction(hp1, hp1) do
  14477. begin
  14478. if not Assigned(hp2) then
  14479. { The first instruction after TEST }
  14480. hp2 := hp1;
  14481. if (hp1.typ <> ait_instruction) then
  14482. begin
  14483. { If the flags are no longer in use, everything is fine }
  14484. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14485. IsValid := False;
  14486. Break;
  14487. end;
  14488. case taicpu(hp1).condition of
  14489. C_None:
  14490. begin
  14491. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14492. { Something is not quite normal, so play safe and don't change }
  14493. IsValid := False;
  14494. Break;
  14495. end;
  14496. C_E, C_Z, C_NE, C_NZ:
  14497. { This is fine };
  14498. else
  14499. begin
  14500. { Unsupported condition }
  14501. IsValid := False;
  14502. Break;
  14503. end;
  14504. end;
  14505. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  14506. end;
  14507. if IsValid then
  14508. begin
  14509. while hp2 <> hp1 do
  14510. begin
  14511. case taicpu(hp2).condition of
  14512. C_Z, C_E:
  14513. taicpu(hp2).condition := C_NC;
  14514. C_NZ, C_NE:
  14515. taicpu(hp2).condition := C_C;
  14516. else
  14517. { Should not get this by this point }
  14518. InternalError(2022110701);
  14519. end;
  14520. GetNextInstruction(hp2, hp2);
  14521. end;
  14522. 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);
  14523. taicpu(p).opcode := A_BT;
  14524. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14525. Result := True;
  14526. Exit;
  14527. end;
  14528. end;
  14529. { removes the line marked with (x) from the sequence
  14530. and/or/xor/add/sub/... $x, %y
  14531. test/or %y, %y | test $-1, %y (x)
  14532. j(n)z _Label
  14533. as the first instruction already adjusts the ZF
  14534. %y operand may also be a reference }
  14535. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  14536. MatchOperand(taicpu(p).oper[0]^,-1);
  14537. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  14538. GetLastInstruction(p, hp1) and
  14539. (tai(hp1).typ = ait_instruction) and
  14540. GetNextInstruction(p,hp2) and
  14541. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  14542. case taicpu(hp1).opcode Of
  14543. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  14544. { These two instructions set the zero flag if the result is zero }
  14545. A_POPCNT, A_LZCNT:
  14546. begin
  14547. if (
  14548. { With POPCNT, an input of zero will set the zero flag
  14549. because the population count of zero is zero }
  14550. (taicpu(hp1).opcode = A_POPCNT) and
  14551. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  14552. (
  14553. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  14554. { Faster than going through the second half of the 'or'
  14555. condition below }
  14556. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  14557. )
  14558. ) or (
  14559. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  14560. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14561. { and in case of carry for A(E)/B(E)/C/NC }
  14562. (
  14563. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  14564. (
  14565. (taicpu(hp1).opcode <> A_ADD) and
  14566. (taicpu(hp1).opcode <> A_SUB) and
  14567. (taicpu(hp1).opcode <> A_LZCNT)
  14568. )
  14569. )
  14570. ) then
  14571. begin
  14572. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  14573. RemoveCurrentP(p, hp2);
  14574. Result:=true;
  14575. Exit;
  14576. end;
  14577. end;
  14578. A_SHL, A_SAL, A_SHR, A_SAR:
  14579. begin
  14580. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  14581. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  14582. { therefore, it's only safe to do this optimization for }
  14583. { shifts by a (nonzero) constant }
  14584. (taicpu(hp1).oper[0]^.typ = top_const) and
  14585. (taicpu(hp1).oper[0]^.val <> 0) and
  14586. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14587. { and in case of carry for A(E)/B(E)/C/NC }
  14588. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14589. begin
  14590. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  14591. RemoveCurrentP(p, hp2);
  14592. Result:=true;
  14593. Exit;
  14594. end;
  14595. end;
  14596. A_DEC, A_INC, A_NEG:
  14597. begin
  14598. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  14599. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14600. { and in case of carry for A(E)/B(E)/C/NC }
  14601. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14602. begin
  14603. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  14604. RemoveCurrentP(p, hp2);
  14605. Result:=true;
  14606. Exit;
  14607. end;
  14608. end;
  14609. A_ANDN, A_BZHI:
  14610. begin
  14611. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14612. { Only the zero and sign flags are consistent with what the result is }
  14613. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  14614. begin
  14615. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  14616. RemoveCurrentP(p, hp2);
  14617. Result:=true;
  14618. Exit;
  14619. end;
  14620. end;
  14621. A_BEXTR:
  14622. begin
  14623. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14624. { Only the zero flag is set }
  14625. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14626. begin
  14627. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  14628. RemoveCurrentP(p, hp2);
  14629. Result:=true;
  14630. Exit;
  14631. end;
  14632. end;
  14633. else
  14634. ;
  14635. end; { case }
  14636. { change "test $-1,%reg" into "test %reg,%reg" }
  14637. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  14638. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  14639. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  14640. if MatchInstruction(p, A_OR, []) and
  14641. { Can only match if they're both registers }
  14642. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  14643. begin
  14644. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  14645. taicpu(p).opcode := A_TEST;
  14646. { No need to set Result to True, as we've done all the optimisations we can }
  14647. end;
  14648. end;
  14649. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  14650. var
  14651. hp1,hp3 : tai;
  14652. {$ifndef x86_64}
  14653. hp2 : taicpu;
  14654. {$endif x86_64}
  14655. begin
  14656. Result:=false;
  14657. hp3:=nil;
  14658. {$ifndef x86_64}
  14659. { don't do this on modern CPUs, this really hurts them due to
  14660. broken call/ret pairing }
  14661. if (current_settings.optimizecputype < cpu_Pentium2) and
  14662. not(cs_create_pic in current_settings.moduleswitches) and
  14663. GetNextInstruction(p, hp1) and
  14664. MatchInstruction(hp1,A_JMP,[S_NO]) and
  14665. MatchOpType(taicpu(hp1),top_ref) and
  14666. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  14667. begin
  14668. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  14669. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14670. InsertLLItem(p.previous, p, hp2);
  14671. taicpu(p).opcode := A_JMP;
  14672. taicpu(p).is_jmp := true;
  14673. RemoveInstruction(hp1);
  14674. Result:=true;
  14675. end
  14676. else
  14677. {$endif x86_64}
  14678. { replace
  14679. call procname
  14680. ret
  14681. by
  14682. jmp procname
  14683. but do it only on level 4 because it destroys stack back traces
  14684. else if the subroutine is marked as no return, remove the ret
  14685. }
  14686. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  14687. (po_noreturn in current_procinfo.procdef.procoptions)) and
  14688. GetNextInstruction(p, hp1) and
  14689. (MatchInstruction(hp1,A_RET,[S_NO]) or
  14690. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  14691. SetAndTest(hp1,hp3) and
  14692. GetNextInstruction(hp1,hp1) and
  14693. MatchInstruction(hp1,A_RET,[S_NO])
  14694. )
  14695. ) and
  14696. (taicpu(hp1).ops=0) then
  14697. begin
  14698. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14699. { we might destroy stack alignment here if we do not do a call }
  14700. (target_info.stackalign<=sizeof(SizeUInt)) then
  14701. begin
  14702. taicpu(p).opcode := A_JMP;
  14703. taicpu(p).is_jmp := true;
  14704. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  14705. end
  14706. else
  14707. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  14708. RemoveInstruction(hp1);
  14709. if Assigned(hp3) then
  14710. begin
  14711. AsmL.Remove(hp3);
  14712. AsmL.InsertBefore(hp3,p)
  14713. end;
  14714. Result:=true;
  14715. end;
  14716. end;
  14717. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  14718. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  14719. begin
  14720. case OpSize of
  14721. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  14722. Result := (Val <= $FF) and (Val >= -128);
  14723. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  14724. Result := (Val <= $FFFF) and (Val >= -32768);
  14725. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  14726. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  14727. else
  14728. Result := True;
  14729. end;
  14730. end;
  14731. var
  14732. hp1, hp2 : tai;
  14733. SizeChange: Boolean;
  14734. PreMessage: string;
  14735. begin
  14736. Result := False;
  14737. if (taicpu(p).oper[0]^.typ = top_reg) and
  14738. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  14739. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  14740. begin
  14741. { Change (using movzbl %al,%eax as an example):
  14742. movzbl %al, %eax movzbl %al, %eax
  14743. cmpl x, %eax testl %eax,%eax
  14744. To:
  14745. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  14746. movzbl %al, %eax movzbl %al, %eax
  14747. Smaller instruction and minimises pipeline stall as the CPU
  14748. doesn't have to wait for the register to get zero-extended. [Kit]
  14749. Also allow if the smaller of the two registers is being checked,
  14750. as this still removes the false dependency.
  14751. }
  14752. if
  14753. (
  14754. (
  14755. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  14756. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  14757. ) or (
  14758. { If MatchOperand returns True, they must both be registers }
  14759. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  14760. )
  14761. ) and
  14762. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  14763. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  14764. begin
  14765. 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);
  14766. asml.Remove(hp1);
  14767. asml.InsertBefore(hp1, p);
  14768. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  14769. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  14770. begin
  14771. taicpu(hp1).opcode := A_TEST;
  14772. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  14773. end;
  14774. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  14775. case taicpu(p).opsize of
  14776. S_BW, S_BL:
  14777. begin
  14778. SizeChange := taicpu(hp1).opsize <> S_B;
  14779. taicpu(hp1).changeopsize(S_B);
  14780. end;
  14781. S_WL:
  14782. begin
  14783. SizeChange := taicpu(hp1).opsize <> S_W;
  14784. taicpu(hp1).changeopsize(S_W);
  14785. end
  14786. else
  14787. InternalError(2020112701);
  14788. end;
  14789. UpdateUsedRegs(tai(p.Next));
  14790. { Check if the register is used aferwards - if not, we can
  14791. remove the movzx instruction completely }
  14792. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  14793. begin
  14794. { Hp1 is a better position than p for debugging purposes }
  14795. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  14796. RemoveCurrentp(p, hp1);
  14797. Result := True;
  14798. end;
  14799. if SizeChange then
  14800. DebugMsg(SPeepholeOptimization + PreMessage +
  14801. 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)
  14802. else
  14803. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  14804. Exit;
  14805. end;
  14806. { Change (using movzwl %ax,%eax as an example):
  14807. movzwl %ax, %eax
  14808. movb %al, (dest) (Register is smaller than read register in movz)
  14809. To:
  14810. movb %al, (dest) (Move one back to avoid a false dependency)
  14811. movzwl %ax, %eax
  14812. }
  14813. if (taicpu(hp1).opcode = A_MOV) and
  14814. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14815. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  14816. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  14817. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  14818. begin
  14819. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  14820. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  14821. asml.Remove(hp1);
  14822. asml.InsertBefore(hp1, p);
  14823. if taicpu(hp1).oper[1]^.typ = top_reg then
  14824. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14825. { Check if the register is used aferwards - if not, we can
  14826. remove the movzx instruction completely }
  14827. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  14828. begin
  14829. { Hp1 is a better position than p for debugging purposes }
  14830. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  14831. RemoveCurrentp(p, hp1);
  14832. Result := True;
  14833. end;
  14834. Exit;
  14835. end;
  14836. end;
  14837. end;
  14838. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  14839. var
  14840. hp1: tai;
  14841. {$ifdef x86_64}
  14842. PreMessage, RegName: string;
  14843. {$endif x86_64}
  14844. begin
  14845. Result := False;
  14846. { If x is a power of 2 (popcnt = 1), change:
  14847. xor $x, %reg/ref
  14848. To:
  14849. btc lb(x), %reg/ref
  14850. }
  14851. if IsBTXAcceptable(p) and
  14852. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14853. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14854. (
  14855. { Don't optimise if a test instruction follows }
  14856. not GetNextInstruction(p, hp1) or
  14857. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14858. ) then
  14859. begin
  14860. 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);
  14861. taicpu(p).opcode := A_BTC;
  14862. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14863. Result := True;
  14864. Exit;
  14865. end;
  14866. {$ifdef x86_64}
  14867. { Code size reduction by J. Gareth "Kit" Moreton }
  14868. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  14869. as this removes the REX prefix }
  14870. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  14871. Exit;
  14872. if taicpu(p).oper[0]^.typ <> top_reg then
  14873. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  14874. InternalError(2018011500);
  14875. case taicpu(p).opsize of
  14876. S_Q:
  14877. begin
  14878. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  14879. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  14880. { The actual optimization }
  14881. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14882. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14883. taicpu(p).changeopsize(S_L);
  14884. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  14885. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  14886. end;
  14887. else
  14888. ;
  14889. end;
  14890. {$endif x86_64}
  14891. end;
  14892. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  14893. var
  14894. XReg: TRegister;
  14895. begin
  14896. Result := False;
  14897. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  14898. Smaller encoding and slightly faster on some platforms (also works for
  14899. ZMM-sized registers) }
  14900. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  14901. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  14902. begin
  14903. XReg := taicpu(p).oper[0]^.reg;
  14904. if (taicpu(p).oper[1]^.reg = XReg) then
  14905. begin
  14906. taicpu(p).changeopsize(S_XMM);
  14907. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  14908. if (cs_opt_size in current_settings.optimizerswitches) then
  14909. begin
  14910. { Change input registers to %xmm0 to reduce size. Note that
  14911. there's a risk of a false dependency doing this, so only
  14912. optimise for size here }
  14913. XReg := NR_XMM0;
  14914. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  14915. end
  14916. else
  14917. begin
  14918. setsubreg(XReg, R_SUBMMX);
  14919. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  14920. end;
  14921. taicpu(p).oper[0]^.reg := XReg;
  14922. taicpu(p).oper[1]^.reg := XReg;
  14923. Result := True;
  14924. end;
  14925. end;
  14926. end;
  14927. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  14928. var
  14929. OperIdx: Integer;
  14930. begin
  14931. for OperIdx := 0 to p.ops - 1 do
  14932. if p.oper[OperIdx]^.typ = top_ref then
  14933. optimize_ref(p.oper[OperIdx]^.ref^, False);
  14934. end;
  14935. end.