aoptx86.pas 735 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration,
  34. aoc_DoPass2JccOpts
  35. );
  36. TX86AsmOptimizer = class(TAsmOptimizer)
  37. { some optimizations are very expensive to check, so the
  38. pre opt pass can be used to set some flags, depending on the found
  39. instructions if it is worth to check a certain optimization }
  40. OptsToCheck : set of TOptsToCheck;
  41. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  42. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  43. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  44. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  45. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  46. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  47. how many instructions away that Next is from Current is.
  48. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  49. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  50. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  51. potentially allowing further optimisation (although it might need to know if
  52. it crossed a conditional jump. }
  53. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  54. {
  55. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  56. the use of a register by allocs/dealloc, so it can ignore calls.
  57. In the following example, GetNextInstructionUsingReg will return the second movq,
  58. GetNextInstructionUsingRegTrackingUse won't.
  59. movq %rdi,%rax
  60. # Register rdi released
  61. # Register rdi allocated
  62. movq %rax,%rdi
  63. While in this example:
  64. movq %rdi,%rax
  65. call proc
  66. movq %rdi,%rax
  67. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  68. won't.
  69. }
  70. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  71. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  72. private
  73. function SkipSimpleInstructions(var hp1: tai): Boolean;
  74. protected
  75. class function IsMOVZXAcceptable: Boolean; static; inline;
  76. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  77. { Attempts to allocate a volatile integer register for use between p and hp,
  78. using AUsedRegs for the current register usage information. Returns NR_NO
  79. if no free register could be found }
  80. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  81. { Attempts to allocate a volatile MM register for use between p and hp,
  82. using AUsedRegs for the current register usage information. Returns NR_NO
  83. if no free register could be found }
  84. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  85. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  86. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  87. { checks whether reading the value in reg1 depends on the value of reg2. This
  88. is very similar to SuperRegisterEquals, except it takes into account that
  89. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  90. depend on the value in AH). }
  91. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  92. { Replaces all references to AOldReg in a memory reference to ANewReg }
  93. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  94. { Replaces all references to AOldReg in an operand to ANewReg }
  95. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  96. { Replaces all references to AOldReg in an instruction to ANewReg,
  97. except where the register is being written }
  98. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  99. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  100. or writes to a global symbol }
  101. class function IsRefSafe(const ref: PReference): Boolean; static;
  102. { Returns true if the given MOV instruction can be safely converted to CMOV }
  103. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  104. { Like UpdateUsedRegs, but ignores deallocations }
  105. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  106. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  107. class function IsBTXAcceptable(p : tai) : boolean; static;
  108. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  109. conversion was successful }
  110. function ConvertLEA(const p : taicpu): Boolean;
  111. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  112. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  113. procedure DebugMsg(const s : string; p : tai);inline;
  114. class function IsExitCode(p : tai) : boolean; static;
  115. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  116. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  117. procedure RemoveLastDeallocForFuncRes(p : tai);
  118. function DoArithCombineOpt(var p : tai) : Boolean;
  119. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  120. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  121. function PrePeepholeOptSxx(var p : tai) : boolean;
  122. function PrePeepholeOptIMUL(var p : tai) : boolean;
  123. function PrePeepholeOptAND(var p : tai) : boolean;
  124. function OptPass1Test(var p: tai): boolean;
  125. function OptPass1Add(var p: tai): boolean;
  126. function OptPass1AND(var p : tai) : boolean;
  127. function OptPass1CMOVcc(var p: tai): Boolean;
  128. function OptPass1_V_MOVAP(var p : tai) : boolean;
  129. function OptPass1VOP(var p : tai) : boolean;
  130. function OptPass1MOV(var p : tai) : boolean;
  131. function OptPass1Movx(var p : tai) : boolean;
  132. function OptPass1MOVXX(var p : tai) : boolean;
  133. function OptPass1OP(var p : tai) : boolean;
  134. function OptPass1LEA(var p : tai) : boolean;
  135. function OptPass1Sub(var p : tai) : boolean;
  136. function OptPass1SHLSAL(var p : tai) : boolean;
  137. function OptPass1SHR(var p : tai) : boolean;
  138. function OptPass1FSTP(var p : tai) : boolean;
  139. function OptPass1FLD(var p : tai) : boolean;
  140. function OptPass1Cmp(var p : tai) : boolean;
  141. function OptPass1PXor(var p : tai) : boolean;
  142. function OptPass1VPXor(var p: tai): boolean;
  143. function OptPass1Imul(var p : tai) : boolean;
  144. function OptPass1Jcc(var p : tai) : boolean;
  145. function OptPass1SHXX(var p: tai): boolean;
  146. function OptPass1VMOVDQ(var p: tai): Boolean;
  147. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  148. function OptPass1STCCLC(var p: tai): Boolean;
  149. function OptPass2STCCLC(var p: tai): Boolean;
  150. function OptPass2CMOVcc(var p: tai): Boolean;
  151. function OptPass2Movx(var p : tai): Boolean;
  152. function OptPass2MOV(var p : tai) : boolean;
  153. function OptPass2Imul(var p : tai) : boolean;
  154. function OptPass2Jmp(var p : tai) : boolean;
  155. function OptPass2Jcc(var p : tai) : boolean;
  156. function OptPass2Lea(var p: tai): Boolean;
  157. function OptPass2SUB(var p: tai): Boolean;
  158. function OptPass2ADD(var p : tai): Boolean;
  159. function OptPass2SETcc(var p : tai) : boolean;
  160. function OptPass2Cmp(var p: tai): Boolean;
  161. function OptPass2Test(var p: tai): Boolean;
  162. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  163. function PostPeepholeOptMov(var p : tai) : Boolean;
  164. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  165. function PostPeepholeOptXor(var p : tai) : Boolean;
  166. function PostPeepholeOptAnd(var p : tai) : boolean;
  167. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  168. function PostPeepholeOptCmp(var p : tai) : Boolean;
  169. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  170. function PostPeepholeOptCall(var p : tai) : Boolean;
  171. function PostPeepholeOptLea(var p : tai) : Boolean;
  172. function PostPeepholeOptPush(var p: tai): Boolean;
  173. function PostPeepholeOptShr(var p : tai) : boolean;
  174. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  175. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  176. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  177. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  178. function TrySwapMovOp(var p, hp1: tai): Boolean;
  179. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  180. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  181. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  182. { Processor-dependent reference optimisation }
  183. class procedure OptimizeRefs(var p: taicpu); static;
  184. end;
  185. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  186. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  187. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  188. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  189. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  190. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  191. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  192. {$if max_operands>2}
  193. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  194. {$endif max_operands>2}
  195. function RefsEqual(const r1, r2: treference): boolean;
  196. { Note that Result is set to True if the references COULD overlap but the
  197. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  198. might still overlap because %reg2 could be equal to %reg1-4 }
  199. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  200. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  201. { returns true, if ref is a reference using only the registers passed as base and index
  202. and having an offset }
  203. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  204. implementation
  205. uses
  206. cutils,verbose,
  207. systems,
  208. globals,
  209. cpuinfo,
  210. procinfo,
  211. paramgr,
  212. aasmbase,
  213. aoptbase,aoptutils,
  214. symconst,symsym,
  215. cgx86,
  216. itcpugas;
  217. {$ifndef 8086}
  218. const
  219. MAX_CMOV_INSTRUCTIONS = 4;
  220. MAX_CMOV_REGISTERS = 8;
  221. type
  222. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  223. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  224. tsProcessed);
  225. { For OptPass2Jcc }
  226. TCMOVTracking = object
  227. private
  228. CMOVScore, ConstCount: LongInt;
  229. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  230. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  231. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  232. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  233. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  234. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  235. fOptimizer: TX86AsmOptimizer;
  236. fLabel: TAsmSymbol;
  237. fInsertionPoint,
  238. fCondition,
  239. fInitialJump,
  240. fFirstMovBlock,
  241. fFirstMovBlockStop,
  242. fSecondJump,
  243. fThirdJump,
  244. fSecondMovBlock,
  245. fSecondMovBlockStop,
  246. fMidLabel,
  247. fEndLabel,
  248. fAllocationRange: tai;
  249. fState: TCMovTrackingState;
  250. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  251. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  252. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  253. public
  254. RegisterTracking: TAllUsedRegs;
  255. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  256. destructor Done;
  257. procedure Process(out new_p: tai);
  258. property State: TCMovTrackingState read fState;
  259. end;
  260. PCMOVTracking = ^TCMOVTracking;
  261. {$endif 8086}
  262. {$ifdef DEBUG_AOPTCPU}
  263. const
  264. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  265. {$else DEBUG_AOPTCPU}
  266. { Empty strings help the optimizer to remove string concatenations that won't
  267. ever appear to the user on release builds. [Kit] }
  268. const
  269. SPeepholeOptimization = '';
  270. {$endif DEBUG_AOPTCPU}
  271. LIST_STEP_SIZE = 4;
  272. type
  273. TJumpTrackingItem = class(TLinkedListItem)
  274. private
  275. FSymbol: TAsmSymbol;
  276. FRefs: LongInt;
  277. public
  278. constructor Create(ASymbol: TAsmSymbol);
  279. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  280. property Symbol: TAsmSymbol read FSymbol;
  281. property Refs: LongInt read FRefs;
  282. end;
  283. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  284. begin
  285. inherited Create;
  286. FSymbol := ASymbol;
  287. FRefs := 0;
  288. end;
  289. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  290. begin
  291. Inc(FRefs);
  292. end;
  293. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  294. begin
  295. result :=
  296. (instr.typ = ait_instruction) and
  297. (taicpu(instr).opcode = op) and
  298. ((opsize = []) or (taicpu(instr).opsize in opsize));
  299. end;
  300. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  301. begin
  302. result :=
  303. (instr.typ = ait_instruction) and
  304. ((taicpu(instr).opcode = op1) or
  305. (taicpu(instr).opcode = op2)
  306. ) and
  307. ((opsize = []) or (taicpu(instr).opsize in opsize));
  308. end;
  309. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  310. begin
  311. result :=
  312. (instr.typ = ait_instruction) and
  313. ((taicpu(instr).opcode = op1) or
  314. (taicpu(instr).opcode = op2) or
  315. (taicpu(instr).opcode = op3)
  316. ) and
  317. ((opsize = []) or (taicpu(instr).opsize in opsize));
  318. end;
  319. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  320. const opsize : topsizes) : boolean;
  321. var
  322. op : TAsmOp;
  323. begin
  324. result:=false;
  325. if (instr.typ <> ait_instruction) or
  326. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  327. exit;
  328. for op in ops do
  329. begin
  330. if taicpu(instr).opcode = op then
  331. begin
  332. result:=true;
  333. exit;
  334. end;
  335. end;
  336. end;
  337. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  338. begin
  339. result := (oper.typ = top_reg) and (oper.reg = reg);
  340. end;
  341. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  342. begin
  343. result := (oper.typ = top_const) and (oper.val = a);
  344. end;
  345. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  346. begin
  347. result := oper1.typ = oper2.typ;
  348. if result then
  349. case oper1.typ of
  350. top_const:
  351. Result:=oper1.val = oper2.val;
  352. top_reg:
  353. Result:=oper1.reg = oper2.reg;
  354. top_ref:
  355. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  356. else
  357. internalerror(2013102801);
  358. end
  359. end;
  360. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  361. begin
  362. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  363. if result then
  364. case oper1.typ of
  365. top_const:
  366. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  367. top_reg:
  368. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  369. top_ref:
  370. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  371. else
  372. internalerror(2020052401);
  373. end
  374. end;
  375. function RefsEqual(const r1, r2: treference): boolean;
  376. begin
  377. RefsEqual :=
  378. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  379. (r1.relsymbol = r2.relsymbol) and
  380. (r1.segment = r2.segment) and (r1.base = r2.base) and
  381. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  382. (r1.offset = r2.offset) and
  383. (r1.volatility + r2.volatility = []);
  384. end;
  385. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  386. begin
  387. if (r1.symbol<>r2.symbol) then
  388. { If the index registers are different, there's a chance one could
  389. be set so it equals the other symbol }
  390. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  391. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  392. (r1.relsymbol = r2.relsymbol) and
  393. (r1.segment = r2.segment) and (r1.base = r2.base) and
  394. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  395. (r1.volatility + r2.volatility = []) then
  396. { In this case, it all depends on the offsets }
  397. Exit(abs(r1.offset - r2.offset) < Range);
  398. { There's a chance things MIGHT overlap, so take no chances }
  399. Result := True;
  400. end;
  401. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  402. begin
  403. Result:=(ref.offset=0) and
  404. (ref.scalefactor in [0,1]) and
  405. (ref.segment=NR_NO) and
  406. (ref.symbol=nil) and
  407. (ref.relsymbol=nil) and
  408. ((base=NR_INVALID) or
  409. (ref.base=base)) and
  410. ((index=NR_INVALID) or
  411. (ref.index=index)) and
  412. (ref.volatility=[]);
  413. end;
  414. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  415. begin
  416. Result:=(ref.scalefactor in [0,1]) and
  417. (ref.segment=NR_NO) and
  418. (ref.symbol=nil) and
  419. (ref.relsymbol=nil) and
  420. ((base=NR_INVALID) or
  421. (ref.base=base)) and
  422. ((index=NR_INVALID) or
  423. (ref.index=index)) and
  424. (ref.volatility=[]);
  425. end;
  426. function InstrReadsFlags(p: tai): boolean;
  427. begin
  428. InstrReadsFlags := true;
  429. case p.typ of
  430. ait_instruction:
  431. if InsProp[taicpu(p).opcode].Ch*
  432. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  433. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  434. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  435. exit;
  436. ait_label:
  437. exit;
  438. else
  439. ;
  440. end;
  441. InstrReadsFlags := false;
  442. end;
  443. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  444. begin
  445. Next:=Current;
  446. repeat
  447. Result:=GetNextInstruction(Next,Next);
  448. until not (Result) or
  449. not(cs_opt_level3 in current_settings.optimizerswitches) or
  450. (Next.typ<>ait_instruction) or
  451. RegInInstruction(reg,Next) or
  452. is_calljmp(taicpu(Next).opcode);
  453. end;
  454. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  455. var
  456. GetNextResult: Boolean;
  457. begin
  458. Result:=0;
  459. Next:=Current;
  460. repeat
  461. GetNextResult := GetNextInstruction(Next,Next);
  462. if GetNextResult then
  463. Inc(Result)
  464. else
  465. { Must return zero upon hitting the end of the linked list without a match }
  466. Result := 0;
  467. until not (GetNextResult) or
  468. not(cs_opt_level3 in current_settings.optimizerswitches) or
  469. (Next.typ<>ait_instruction) or
  470. RegInInstruction(reg,Next) or
  471. is_calljmp(taicpu(Next).opcode);
  472. end;
  473. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  474. procedure TrackJump(Symbol: TAsmSymbol);
  475. var
  476. Search: TJumpTrackingItem;
  477. begin
  478. { See if an entry already exists in our jump tracking list
  479. (faster to search backwards due to the higher chance of
  480. matching destinations) }
  481. Search := TJumpTrackingItem(JumpTracking.Last);
  482. while Assigned(Search) do
  483. begin
  484. if Search.Symbol = Symbol then
  485. begin
  486. { Found it - remove it so it can be pushed to the front }
  487. JumpTracking.Remove(Search);
  488. Break;
  489. end;
  490. Search := TJumpTrackingItem(Search.Previous);
  491. end;
  492. if not Assigned(Search) then
  493. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  494. JumpTracking.Concat(Search);
  495. Search.IncRefs;
  496. end;
  497. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  498. var
  499. Search: TJumpTrackingItem;
  500. begin
  501. Result := False;
  502. { See if this label appears in the tracking list }
  503. Search := TJumpTrackingItem(JumpTracking.Last);
  504. while Assigned(Search) do
  505. begin
  506. if Search.Symbol = Symbol then
  507. begin
  508. { Found it - let's see what we can discover }
  509. if Search.Symbol.getrefs = Search.Refs then
  510. begin
  511. { Success - all the references are accounted for }
  512. JumpTracking.Remove(Search);
  513. Search.Free;
  514. { It is logically impossible for CrossJump to be false here
  515. because we must have run into a conditional jump for
  516. this label at some point }
  517. if not CrossJump then
  518. InternalError(2022041710);
  519. if JumpTracking.First = nil then
  520. { Tracking list is now empty - no more cross jumps }
  521. CrossJump := False;
  522. Result := True;
  523. Exit;
  524. end;
  525. { If the references don't match, it's possible to enter
  526. this label through other means, so drop out }
  527. Exit;
  528. end;
  529. Search := TJumpTrackingItem(Search.Previous);
  530. end;
  531. end;
  532. var
  533. Next_Label: tai;
  534. begin
  535. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  536. Next := Current;
  537. repeat
  538. Result := GetNextInstruction(Next,Next);
  539. if not Result then
  540. Break;
  541. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  542. if is_calljmpuncondret(taicpu(Next).opcode) then
  543. begin
  544. if (taicpu(Next).opcode = A_JMP) and
  545. { Remove dead code now to save time }
  546. RemoveDeadCodeAfterJump(taicpu(Next)) then
  547. { A jump was removed, but not the current instruction, and
  548. Result doesn't necessarily translate into an optimisation
  549. routine's Result, so use the "Force New Iteration" flag so
  550. mark a new pass }
  551. Include(OptsToCheck, aoc_ForceNewIteration);
  552. if not Assigned(JumpTracking) then
  553. begin
  554. { Cross-label optimisations often causes other optimisations
  555. to perform worse because they're not given the chance to
  556. optimise locally. In this case, don't do the cross-label
  557. optimisations yet, but flag them as a potential possibility
  558. for the next iteration of Pass 1 }
  559. if not NotFirstIteration then
  560. Include(OptsToCheck, aoc_ForceNewIteration);
  561. end
  562. else if IsJumpToLabel(taicpu(Next)) and
  563. GetNextInstruction(Next, Next_Label) then
  564. begin
  565. { If we have JMP .lbl, and the label after it has all of its
  566. references tracked, then this is probably an if-else style of
  567. block and we can keep tracking. If the label for this jump
  568. then appears later and is fully tracked, then it's the end
  569. of the if-else blocks and the code paths converge (thus
  570. marking the end of the cross-jump) }
  571. if (Next_Label.typ = ait_label) then
  572. begin
  573. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  574. begin
  575. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  576. Next := Next_Label;
  577. { CrossJump gets set to false by LabelAccountedFor if the
  578. list is completely emptied (as it indicates that all
  579. code paths have converged). We could avoid this nuance
  580. by moving the TrackJump call to before the
  581. LabelAccountedFor call, but this is slower in situations
  582. where LabelAccountedFor would return False due to the
  583. creation of a new object that is not used and destroyed
  584. soon after. }
  585. CrossJump := True;
  586. Continue;
  587. end;
  588. end
  589. else if (Next_Label.typ <> ait_marker) then
  590. { We just did a RemoveDeadCodeAfterJump, so either we find
  591. a label, the end of the procedure or some kind of marker}
  592. InternalError(2022041720);
  593. end;
  594. Result := False;
  595. Exit;
  596. end
  597. else
  598. begin
  599. if not Assigned(JumpTracking) then
  600. begin
  601. { Cross-label optimisations often causes other optimisations
  602. to perform worse because they're not given the chance to
  603. optimise locally. In this case, don't do the cross-label
  604. optimisations yet, but flag them as a potential possibility
  605. for the next iteration of Pass 1 }
  606. if not NotFirstIteration then
  607. Include(OptsToCheck, aoc_ForceNewIteration);
  608. end
  609. else if IsJumpToLabel(taicpu(Next)) then
  610. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  611. else
  612. { Conditional jumps should always be a jump to label }
  613. InternalError(2022041701);
  614. CrossJump := True;
  615. Continue;
  616. end;
  617. if Next.typ = ait_label then
  618. begin
  619. if not Assigned(JumpTracking) then
  620. begin
  621. { Cross-label optimisations often causes other optimisations
  622. to perform worse because they're not given the chance to
  623. optimise locally. In this case, don't do the cross-label
  624. optimisations yet, but flag them as a potential possibility
  625. for the next iteration of Pass 1 }
  626. if not NotFirstIteration then
  627. Include(OptsToCheck, aoc_ForceNewIteration);
  628. end
  629. else if LabelAccountedFor(tai_label(Next).labsym) then
  630. Continue;
  631. { If we reach here, we're at a label that hasn't been seen before
  632. (or JumpTracking was nil) }
  633. Break;
  634. end;
  635. until not Result or
  636. not (cs_opt_level3 in current_settings.optimizerswitches) or
  637. not (Next.typ in [ait_label, ait_instruction]) or
  638. RegInInstruction(reg,Next);
  639. end;
  640. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  641. begin
  642. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  643. begin
  644. Result:=GetNextInstruction(Current,Next);
  645. exit;
  646. end;
  647. Next:=tai(Current.Next);
  648. Result:=false;
  649. while assigned(Next) do
  650. begin
  651. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  652. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  653. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  654. exit
  655. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  656. begin
  657. Result:=true;
  658. exit;
  659. end;
  660. Next:=tai(Next.Next);
  661. end;
  662. end;
  663. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  664. begin
  665. Result:=RegReadByInstruction(reg,hp);
  666. end;
  667. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  668. var
  669. p: taicpu;
  670. opcount: longint;
  671. begin
  672. RegReadByInstruction := false;
  673. if hp.typ <> ait_instruction then
  674. exit;
  675. p := taicpu(hp);
  676. case p.opcode of
  677. A_CALL:
  678. regreadbyinstruction := true;
  679. A_IMUL:
  680. case p.ops of
  681. 1:
  682. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  683. (
  684. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  685. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  686. );
  687. 2,3:
  688. regReadByInstruction :=
  689. reginop(reg,p.oper[0]^) or
  690. reginop(reg,p.oper[1]^);
  691. else
  692. InternalError(2019112801);
  693. end;
  694. A_MUL:
  695. begin
  696. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  697. (
  698. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  699. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  700. );
  701. end;
  702. A_IDIV,A_DIV:
  703. begin
  704. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  705. (
  706. (getregtype(reg)=R_INTREGISTER) and
  707. (
  708. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  709. )
  710. );
  711. end;
  712. else
  713. begin
  714. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  715. begin
  716. RegReadByInstruction := false;
  717. exit;
  718. end;
  719. for opcount := 0 to p.ops-1 do
  720. if (p.oper[opCount]^.typ = top_ref) and
  721. RegInRef(reg,p.oper[opcount]^.ref^) then
  722. begin
  723. RegReadByInstruction := true;
  724. exit
  725. end;
  726. { special handling for SSE MOVSD }
  727. if (p.opcode=A_MOVSD) and (p.ops>0) then
  728. begin
  729. if p.ops<>2 then
  730. internalerror(2017042702);
  731. regReadByInstruction := reginop(reg,p.oper[0]^) or
  732. (
  733. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  734. );
  735. exit;
  736. end;
  737. with insprop[p.opcode] do
  738. begin
  739. case getregtype(reg) of
  740. R_INTREGISTER:
  741. begin
  742. case getsupreg(reg) of
  743. RS_EAX:
  744. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  745. begin
  746. RegReadByInstruction := true;
  747. exit
  748. end;
  749. RS_ECX:
  750. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  751. begin
  752. RegReadByInstruction := true;
  753. exit
  754. end;
  755. RS_EDX:
  756. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  757. begin
  758. RegReadByInstruction := true;
  759. exit
  760. end;
  761. RS_EBX:
  762. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  763. begin
  764. RegReadByInstruction := true;
  765. exit
  766. end;
  767. RS_ESP:
  768. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  769. begin
  770. RegReadByInstruction := true;
  771. exit
  772. end;
  773. RS_EBP:
  774. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  775. begin
  776. RegReadByInstruction := true;
  777. exit
  778. end;
  779. RS_ESI:
  780. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  781. begin
  782. RegReadByInstruction := true;
  783. exit
  784. end;
  785. RS_EDI:
  786. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  787. begin
  788. RegReadByInstruction := true;
  789. exit
  790. end;
  791. end;
  792. end;
  793. R_MMREGISTER:
  794. begin
  795. case getsupreg(reg) of
  796. RS_XMM0:
  797. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  798. begin
  799. RegReadByInstruction := true;
  800. exit
  801. end;
  802. end;
  803. end;
  804. else
  805. ;
  806. end;
  807. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  808. begin
  809. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  810. begin
  811. case p.condition of
  812. C_A,C_NBE, { CF=0 and ZF=0 }
  813. C_BE,C_NA: { CF=1 or ZF=1 }
  814. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  815. C_AE,C_NB,C_NC, { CF=0 }
  816. C_B,C_NAE,C_C: { CF=1 }
  817. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  818. C_NE,C_NZ, { ZF=0 }
  819. C_E,C_Z: { ZF=1 }
  820. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  821. C_G,C_NLE, { ZF=0 and SF=OF }
  822. C_LE,C_NG: { ZF=1 or SF<>OF }
  823. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  824. C_GE,C_NL, { SF=OF }
  825. C_L,C_NGE: { SF<>OF }
  826. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  827. C_NO, { OF=0 }
  828. C_O: { OF=1 }
  829. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  830. C_NP,C_PO, { PF=0 }
  831. C_P,C_PE: { PF=1 }
  832. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  833. C_NS, { SF=0 }
  834. C_S: { SF=1 }
  835. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  836. else
  837. internalerror(2017042701);
  838. end;
  839. if RegReadByInstruction then
  840. exit;
  841. end;
  842. case getsubreg(reg) of
  843. R_SUBW,R_SUBD,R_SUBQ:
  844. RegReadByInstruction :=
  845. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  846. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  847. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  848. R_SUBFLAGCARRY:
  849. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  850. R_SUBFLAGPARITY:
  851. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  852. R_SUBFLAGAUXILIARY:
  853. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  854. R_SUBFLAGZERO:
  855. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  856. R_SUBFLAGSIGN:
  857. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  858. R_SUBFLAGOVERFLOW:
  859. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  860. R_SUBFLAGINTERRUPT:
  861. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  862. R_SUBFLAGDIRECTION:
  863. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  864. else
  865. internalerror(2017042601);
  866. end;
  867. exit;
  868. end;
  869. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  870. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  871. (p.oper[0]^.reg=p.oper[1]^.reg) then
  872. exit;
  873. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  874. begin
  875. RegReadByInstruction := true;
  876. exit
  877. end;
  878. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  879. begin
  880. RegReadByInstruction := true;
  881. exit
  882. end;
  883. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  884. begin
  885. RegReadByInstruction := true;
  886. exit
  887. end;
  888. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  889. begin
  890. RegReadByInstruction := true;
  891. exit
  892. end;
  893. end;
  894. end;
  895. end;
  896. end;
  897. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  898. begin
  899. result:=false;
  900. if p1.typ<>ait_instruction then
  901. exit;
  902. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  903. exit(true);
  904. if (getregtype(reg)=R_INTREGISTER) and
  905. { change information for xmm movsd are not correct }
  906. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  907. begin
  908. { Handle instructions that behave differently depending on the size and operand count }
  909. case taicpu(p1).opcode of
  910. A_MUL, A_DIV, A_IDIV:
  911. if taicpu(p1).opsize = S_B then
  912. Result := (getsupreg(Reg) = RS_EAX)
  913. else
  914. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  915. A_IMUL:
  916. if taicpu(p1).ops = 1 then
  917. begin
  918. if taicpu(p1).opsize = S_B then
  919. Result := (getsupreg(Reg) = RS_EAX)
  920. else
  921. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  922. end;
  923. { If ops are greater than 1, call inherited method }
  924. else
  925. case getsupreg(reg) of
  926. { RS_EAX = RS_RAX on x86-64 }
  927. RS_EAX:
  928. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  929. RS_ECX:
  930. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  931. RS_EDX:
  932. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  933. RS_EBX:
  934. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  935. RS_ESP:
  936. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  937. RS_EBP:
  938. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  939. RS_ESI:
  940. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  941. RS_EDI:
  942. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  943. else
  944. ;
  945. end;
  946. end;
  947. if result then
  948. exit;
  949. end
  950. else if getregtype(reg)=R_MMREGISTER then
  951. begin
  952. case getsupreg(reg) of
  953. RS_XMM0:
  954. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  955. else
  956. ;
  957. end;
  958. if result then
  959. exit;
  960. end
  961. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  962. begin
  963. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  964. exit(true);
  965. case getsubreg(reg) of
  966. R_SUBFLAGCARRY:
  967. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  968. R_SUBFLAGPARITY:
  969. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  970. R_SUBFLAGAUXILIARY:
  971. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  972. R_SUBFLAGZERO:
  973. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  974. R_SUBFLAGSIGN:
  975. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  976. R_SUBFLAGOVERFLOW:
  977. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  978. R_SUBFLAGINTERRUPT:
  979. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  980. R_SUBFLAGDIRECTION:
  981. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  982. R_SUBW,R_SUBD,R_SUBQ:
  983. { Everything except the direction bits }
  984. Result:=
  985. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  986. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  987. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  988. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  989. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  990. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  991. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  992. else
  993. ;
  994. end;
  995. if result then
  996. exit;
  997. end
  998. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  999. exit(true);
  1000. Result:=inherited RegInInstruction(Reg, p1);
  1001. end;
  1002. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1003. const
  1004. WriteOps: array[0..3] of set of TInsChange =
  1005. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1006. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1007. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1008. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1009. var
  1010. OperIdx: Integer;
  1011. begin
  1012. Result := False;
  1013. if p1.typ <> ait_instruction then
  1014. exit;
  1015. with insprop[taicpu(p1).opcode] do
  1016. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1017. begin
  1018. case getsubreg(reg) of
  1019. R_SUBW,R_SUBD,R_SUBQ:
  1020. Result :=
  1021. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1022. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1023. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1024. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1025. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1026. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1027. R_SUBFLAGCARRY:
  1028. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1029. R_SUBFLAGPARITY:
  1030. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1031. R_SUBFLAGAUXILIARY:
  1032. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1033. R_SUBFLAGZERO:
  1034. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1035. R_SUBFLAGSIGN:
  1036. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1037. R_SUBFLAGOVERFLOW:
  1038. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1039. R_SUBFLAGINTERRUPT:
  1040. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1041. R_SUBFLAGDIRECTION:
  1042. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1043. else
  1044. internalerror(2017042602);
  1045. end;
  1046. exit;
  1047. end;
  1048. case taicpu(p1).opcode of
  1049. A_CALL:
  1050. { We could potentially set Result to False if the register in
  1051. question is non-volatile for the subroutine's calling convention,
  1052. but this would require detecting the calling convention in use and
  1053. also assuming that the routine doesn't contain malformed assembly
  1054. language, for example... so it could only be done under -O4 as it
  1055. would be considered a side-effect. [Kit] }
  1056. Result := True;
  1057. A_MOVSD:
  1058. { special handling for SSE MOVSD }
  1059. if (taicpu(p1).ops>0) then
  1060. begin
  1061. if taicpu(p1).ops<>2 then
  1062. internalerror(2017042703);
  1063. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1064. end;
  1065. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1066. so fix it here (FK)
  1067. }
  1068. A_VMOVSS,
  1069. A_VMOVSD:
  1070. begin
  1071. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1072. exit;
  1073. end;
  1074. A_MUL, A_DIV, A_IDIV:
  1075. begin
  1076. if taicpu(p1).opsize = S_B then
  1077. Result := (getsupreg(Reg) = RS_EAX)
  1078. else
  1079. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1080. end;
  1081. A_IMUL:
  1082. begin
  1083. if taicpu(p1).ops = 1 then
  1084. begin
  1085. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1086. end
  1087. else
  1088. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1089. Exit;
  1090. end;
  1091. else
  1092. ;
  1093. end;
  1094. if Result then
  1095. exit;
  1096. with insprop[taicpu(p1).opcode] do
  1097. begin
  1098. if getregtype(reg)=R_INTREGISTER then
  1099. begin
  1100. case getsupreg(reg) of
  1101. RS_EAX:
  1102. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1103. begin
  1104. Result := True;
  1105. exit
  1106. end;
  1107. RS_ECX:
  1108. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1109. begin
  1110. Result := True;
  1111. exit
  1112. end;
  1113. RS_EDX:
  1114. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1115. begin
  1116. Result := True;
  1117. exit
  1118. end;
  1119. RS_EBX:
  1120. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1121. begin
  1122. Result := True;
  1123. exit
  1124. end;
  1125. RS_ESP:
  1126. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1127. begin
  1128. Result := True;
  1129. exit
  1130. end;
  1131. RS_EBP:
  1132. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1133. begin
  1134. Result := True;
  1135. exit
  1136. end;
  1137. RS_ESI:
  1138. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1139. begin
  1140. Result := True;
  1141. exit
  1142. end;
  1143. RS_EDI:
  1144. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1145. begin
  1146. Result := True;
  1147. exit
  1148. end;
  1149. end;
  1150. end;
  1151. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1152. if (WriteOps[OperIdx]*Ch<>[]) and
  1153. { The register doesn't get modified inside a reference }
  1154. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1155. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1156. begin
  1157. Result := true;
  1158. exit
  1159. end;
  1160. end;
  1161. end;
  1162. {$ifdef DEBUG_AOPTCPU}
  1163. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1164. begin
  1165. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1166. end;
  1167. function debug_tostr(i: tcgint): string; inline;
  1168. begin
  1169. Result := tostr(i);
  1170. end;
  1171. function debug_hexstr(i: tcgint): string;
  1172. begin
  1173. Result := '0x';
  1174. case i of
  1175. 0..$FF:
  1176. Result := Result + hexstr(i, 2);
  1177. $100..$FFFF:
  1178. Result := Result + hexstr(i, 4);
  1179. $10000..$FFFFFF:
  1180. Result := Result + hexstr(i, 6);
  1181. $1000000..$FFFFFFFF:
  1182. Result := Result + hexstr(i, 8);
  1183. else
  1184. Result := Result + hexstr(i, 16);
  1185. end;
  1186. end;
  1187. function debug_regname(r: TRegister): string; inline;
  1188. begin
  1189. Result := '%' + std_regname(r);
  1190. end;
  1191. { Debug output function - creates a string representation of an operator }
  1192. function debug_operstr(oper: TOper): string;
  1193. begin
  1194. case oper.typ of
  1195. top_const:
  1196. Result := '$' + debug_tostr(oper.val);
  1197. top_reg:
  1198. Result := debug_regname(oper.reg);
  1199. top_ref:
  1200. begin
  1201. if oper.ref^.offset <> 0 then
  1202. Result := debug_tostr(oper.ref^.offset) + '('
  1203. else
  1204. Result := '(';
  1205. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1206. begin
  1207. Result := Result + debug_regname(oper.ref^.base);
  1208. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1209. Result := Result + ',' + debug_regname(oper.ref^.index);
  1210. end
  1211. else
  1212. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1213. Result := Result + debug_regname(oper.ref^.index);
  1214. if (oper.ref^.scalefactor > 1) then
  1215. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1216. else
  1217. Result := Result + ')';
  1218. end;
  1219. else
  1220. Result := '[UNKNOWN]';
  1221. end;
  1222. end;
  1223. function debug_op2str(opcode: tasmop): string; inline;
  1224. begin
  1225. Result := std_op2str[opcode];
  1226. end;
  1227. function debug_opsize2str(opsize: topsize): string; inline;
  1228. begin
  1229. Result := gas_opsize2str[opsize];
  1230. end;
  1231. {$else DEBUG_AOPTCPU}
  1232. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1233. begin
  1234. end;
  1235. function debug_tostr(i: tcgint): string; inline;
  1236. begin
  1237. Result := '';
  1238. end;
  1239. function debug_hexstr(i: tcgint): string; inline;
  1240. begin
  1241. Result := '';
  1242. end;
  1243. function debug_regname(r: TRegister): string; inline;
  1244. begin
  1245. Result := '';
  1246. end;
  1247. function debug_operstr(oper: TOper): string; inline;
  1248. begin
  1249. Result := '';
  1250. end;
  1251. function debug_op2str(opcode: tasmop): string; inline;
  1252. begin
  1253. Result := '';
  1254. end;
  1255. function debug_opsize2str(opsize: topsize): string; inline;
  1256. begin
  1257. Result := '';
  1258. end;
  1259. {$endif DEBUG_AOPTCPU}
  1260. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1261. begin
  1262. {$ifdef x86_64}
  1263. { Always fine on x86-64 }
  1264. Result := True;
  1265. {$else x86_64}
  1266. Result :=
  1267. {$ifdef i8086}
  1268. (current_settings.cputype >= cpu_386) and
  1269. {$endif i8086}
  1270. (
  1271. { Always accept if optimising for size }
  1272. (cs_opt_size in current_settings.optimizerswitches) or
  1273. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1274. (current_settings.optimizecputype >= cpu_Pentium2)
  1275. );
  1276. {$endif x86_64}
  1277. end;
  1278. { Attempts to allocate a volatile integer register for use between p and hp,
  1279. using AUsedRegs for the current register usage information. Returns NR_NO
  1280. if no free register could be found }
  1281. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1282. var
  1283. RegSet: TCPURegisterSet;
  1284. CurrentSuperReg: Integer;
  1285. CurrentReg: TRegister;
  1286. Currentp: tai;
  1287. Breakout: Boolean;
  1288. begin
  1289. Result := NR_NO;
  1290. RegSet :=
  1291. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1292. current_procinfo.saved_regs_int;
  1293. (*
  1294. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1295. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1296. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1297. *)
  1298. for CurrentSuperReg in RegSet do
  1299. begin
  1300. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1301. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1302. {$if defined(i386) or defined(i8086)}
  1303. { If the target size is 8-bit, make sure we can actually encode it }
  1304. and (
  1305. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1306. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1307. )
  1308. {$endif i386 or i8086}
  1309. then
  1310. begin
  1311. Currentp := p;
  1312. Breakout := False;
  1313. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1314. begin
  1315. case Currentp.typ of
  1316. ait_instruction:
  1317. begin
  1318. if RegInInstruction(CurrentReg, Currentp) then
  1319. begin
  1320. Breakout := True;
  1321. Break;
  1322. end;
  1323. { Cannot allocate across an unconditional jump }
  1324. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1325. Exit;
  1326. end;
  1327. ait_marker:
  1328. { Don't try anything more if a marker is hit }
  1329. Exit;
  1330. ait_regalloc:
  1331. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1332. begin
  1333. Breakout := True;
  1334. Break;
  1335. end;
  1336. else
  1337. ;
  1338. end;
  1339. end;
  1340. if Breakout then
  1341. { Try the next register }
  1342. Continue;
  1343. { We have a free register available }
  1344. Result := CurrentReg;
  1345. if not DontAlloc then
  1346. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1347. Exit;
  1348. end;
  1349. end;
  1350. end;
  1351. { Attempts to allocate a volatile MM register for use between p and hp,
  1352. using AUsedRegs for the current register usage information. Returns NR_NO
  1353. if no free register could be found }
  1354. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1355. var
  1356. RegSet: TCPURegisterSet;
  1357. CurrentSuperReg: Integer;
  1358. CurrentReg: TRegister;
  1359. Currentp: tai;
  1360. Breakout: Boolean;
  1361. begin
  1362. Result := NR_NO;
  1363. RegSet :=
  1364. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1365. current_procinfo.saved_regs_mm;
  1366. for CurrentSuperReg in RegSet do
  1367. begin
  1368. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1369. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1370. begin
  1371. Currentp := p;
  1372. Breakout := False;
  1373. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1374. begin
  1375. case Currentp.typ of
  1376. ait_instruction:
  1377. begin
  1378. if RegInInstruction(CurrentReg, Currentp) then
  1379. begin
  1380. Breakout := True;
  1381. Break;
  1382. end;
  1383. { Cannot allocate across an unconditional jump }
  1384. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1385. Exit;
  1386. end;
  1387. ait_marker:
  1388. { Don't try anything more if a marker is hit }
  1389. Exit;
  1390. ait_regalloc:
  1391. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1392. begin
  1393. Breakout := True;
  1394. Break;
  1395. end;
  1396. else
  1397. ;
  1398. end;
  1399. end;
  1400. if Breakout then
  1401. { Try the next register }
  1402. Continue;
  1403. { We have a free register available }
  1404. Result := CurrentReg;
  1405. if not DontAlloc then
  1406. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1407. Exit;
  1408. end;
  1409. end;
  1410. end;
  1411. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1412. begin
  1413. if not SuperRegistersEqual(reg1,reg2) then
  1414. exit(false);
  1415. if getregtype(reg1)<>R_INTREGISTER then
  1416. exit(true); {because SuperRegisterEqual is true}
  1417. case getsubreg(reg1) of
  1418. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1419. higher, it preserves the high bits, so the new value depends on
  1420. reg2's previous value. In other words, it is equivalent to doing:
  1421. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1422. R_SUBL:
  1423. exit(getsubreg(reg2)=R_SUBL);
  1424. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1425. higher, it actually does a:
  1426. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1427. R_SUBH:
  1428. exit(getsubreg(reg2)=R_SUBH);
  1429. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1430. bits of reg2:
  1431. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1432. R_SUBW:
  1433. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1434. { a write to R_SUBD always overwrites every other subregister,
  1435. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1436. R_SUBD,
  1437. R_SUBQ:
  1438. exit(true);
  1439. else
  1440. internalerror(2017042801);
  1441. end;
  1442. end;
  1443. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1444. begin
  1445. if not SuperRegistersEqual(reg1,reg2) then
  1446. exit(false);
  1447. if getregtype(reg1)<>R_INTREGISTER then
  1448. exit(true); {because SuperRegisterEqual is true}
  1449. case getsubreg(reg1) of
  1450. R_SUBL:
  1451. exit(getsubreg(reg2)<>R_SUBH);
  1452. R_SUBH:
  1453. exit(getsubreg(reg2)<>R_SUBL);
  1454. R_SUBW,
  1455. R_SUBD,
  1456. R_SUBQ:
  1457. exit(true);
  1458. else
  1459. internalerror(2017042802);
  1460. end;
  1461. end;
  1462. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1463. var
  1464. hp1 : tai;
  1465. l : TCGInt;
  1466. begin
  1467. result:=false;
  1468. if not(GetNextInstruction(p, hp1)) then
  1469. exit;
  1470. { changes the code sequence
  1471. shr/sar const1, x
  1472. shl const2, x
  1473. to
  1474. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1475. if (taicpu(p).oper[0]^.typ = top_const) and
  1476. MatchInstruction(hp1,A_SHL,[]) and
  1477. (taicpu(hp1).oper[0]^.typ = top_const) and
  1478. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1479. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1480. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1481. begin
  1482. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1483. not(cs_opt_size in current_settings.optimizerswitches) then
  1484. begin
  1485. { shr/sar const1, %reg
  1486. shl const2, %reg
  1487. with const1 > const2 }
  1488. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1489. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1490. taicpu(hp1).opcode := A_AND;
  1491. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1492. case taicpu(p).opsize Of
  1493. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1494. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1495. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1496. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1497. else
  1498. Internalerror(2017050703)
  1499. end;
  1500. end
  1501. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1502. not(cs_opt_size in current_settings.optimizerswitches) then
  1503. begin
  1504. { shr/sar const1, %reg
  1505. shl const2, %reg
  1506. with const1 < const2 }
  1507. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1508. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1509. taicpu(p).opcode := A_AND;
  1510. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1511. case taicpu(p).opsize Of
  1512. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1513. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1514. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1515. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1516. else
  1517. Internalerror(2017050702)
  1518. end;
  1519. end
  1520. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1521. begin
  1522. { shr/sar const1, %reg
  1523. shl const2, %reg
  1524. with const1 = const2 }
  1525. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1526. taicpu(p).opcode := A_AND;
  1527. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1528. case taicpu(p).opsize Of
  1529. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1530. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1531. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1532. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1533. else
  1534. Internalerror(2017050701)
  1535. end;
  1536. RemoveInstruction(hp1);
  1537. end;
  1538. end;
  1539. end;
  1540. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1541. var
  1542. opsize : topsize;
  1543. hp1, hp2 : tai;
  1544. tmpref : treference;
  1545. ShiftValue : Cardinal;
  1546. BaseValue : TCGInt;
  1547. begin
  1548. result:=false;
  1549. opsize:=taicpu(p).opsize;
  1550. { changes certain "imul const, %reg"'s to lea sequences }
  1551. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1552. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1553. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1554. if (taicpu(p).oper[0]^.val = 1) then
  1555. if (taicpu(p).ops = 2) then
  1556. { remove "imul $1, reg" }
  1557. begin
  1558. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1559. Result := RemoveCurrentP(p);
  1560. end
  1561. else
  1562. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1563. begin
  1564. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1565. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1566. asml.InsertAfter(hp1, p);
  1567. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1568. RemoveCurrentP(p, hp1);
  1569. Result := True;
  1570. end
  1571. else if ((taicpu(p).ops <= 2) or
  1572. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1573. not(cs_opt_size in current_settings.optimizerswitches) and
  1574. (not(GetNextInstruction(p, hp1)) or
  1575. not((tai(hp1).typ = ait_instruction) and
  1576. ((taicpu(hp1).opcode=A_Jcc) and
  1577. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1578. begin
  1579. {
  1580. imul X, reg1, reg2 to
  1581. lea (reg1,reg1,Y), reg2
  1582. shl ZZ,reg2
  1583. imul XX, reg1 to
  1584. lea (reg1,reg1,YY), reg1
  1585. shl ZZ,reg2
  1586. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1587. it does not exist as a separate optimization target in FPC though.
  1588. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1589. at most two zeros
  1590. }
  1591. reference_reset(tmpref,1,[]);
  1592. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1593. begin
  1594. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1595. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1596. TmpRef.base := taicpu(p).oper[1]^.reg;
  1597. TmpRef.index := taicpu(p).oper[1]^.reg;
  1598. if not(BaseValue in [3,5,9]) then
  1599. Internalerror(2018110101);
  1600. TmpRef.ScaleFactor := BaseValue-1;
  1601. if (taicpu(p).ops = 2) then
  1602. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1603. else
  1604. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1605. AsmL.InsertAfter(hp1,p);
  1606. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1607. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1608. RemoveCurrentP(p, hp1);
  1609. if ShiftValue>0 then
  1610. begin
  1611. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1612. AsmL.InsertAfter(hp2,hp1);
  1613. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1614. end;
  1615. Result := True;
  1616. end;
  1617. end;
  1618. end;
  1619. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1620. begin
  1621. Result := False;
  1622. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1623. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1624. begin
  1625. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1626. taicpu(p).opcode := A_MOV;
  1627. Result := True;
  1628. end;
  1629. end;
  1630. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1631. var
  1632. p: taicpu absolute hp; { Implicit typecast }
  1633. i: Integer;
  1634. begin
  1635. Result := False;
  1636. if not assigned(hp) or
  1637. (hp.typ <> ait_instruction) then
  1638. Exit;
  1639. Prefetch(insprop[p.opcode]);
  1640. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1641. with insprop[p.opcode] do
  1642. begin
  1643. case getsubreg(reg) of
  1644. R_SUBW,R_SUBD,R_SUBQ:
  1645. Result:=
  1646. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1647. uncommon flags are checked first }
  1648. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1649. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1650. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1651. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1652. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1653. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1654. R_SUBFLAGCARRY:
  1655. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1656. R_SUBFLAGPARITY:
  1657. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1658. R_SUBFLAGAUXILIARY:
  1659. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1660. R_SUBFLAGZERO:
  1661. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1662. R_SUBFLAGSIGN:
  1663. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1664. R_SUBFLAGOVERFLOW:
  1665. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1666. R_SUBFLAGINTERRUPT:
  1667. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1668. R_SUBFLAGDIRECTION:
  1669. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1670. else
  1671. internalerror(2017050501);
  1672. end;
  1673. exit;
  1674. end;
  1675. { Handle special cases first }
  1676. case p.opcode of
  1677. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1678. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1679. begin
  1680. Result :=
  1681. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1682. (p.oper[1]^.typ = top_reg) and
  1683. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1684. (
  1685. (p.oper[0]^.typ = top_const) or
  1686. (
  1687. (p.oper[0]^.typ = top_reg) and
  1688. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1689. ) or (
  1690. (p.oper[0]^.typ = top_ref) and
  1691. not RegInRef(reg,p.oper[0]^.ref^)
  1692. )
  1693. );
  1694. end;
  1695. A_MUL, A_IMUL:
  1696. Result :=
  1697. (
  1698. (p.ops=3) and { IMUL only }
  1699. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1700. (
  1701. (
  1702. (p.oper[1]^.typ=top_reg) and
  1703. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1704. ) or (
  1705. (p.oper[1]^.typ=top_ref) and
  1706. not RegInRef(reg,p.oper[1]^.ref^)
  1707. )
  1708. )
  1709. ) or (
  1710. (
  1711. (p.ops=1) and
  1712. (
  1713. (
  1714. (
  1715. (p.oper[0]^.typ=top_reg) and
  1716. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1717. )
  1718. ) or (
  1719. (p.oper[0]^.typ=top_ref) and
  1720. not RegInRef(reg,p.oper[0]^.ref^)
  1721. )
  1722. ) and (
  1723. (
  1724. (p.opsize=S_B) and
  1725. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1726. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1727. ) or (
  1728. (p.opsize=S_W) and
  1729. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1730. ) or (
  1731. (p.opsize=S_L) and
  1732. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1733. {$ifdef x86_64}
  1734. ) or (
  1735. (p.opsize=S_Q) and
  1736. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1737. {$endif x86_64}
  1738. )
  1739. )
  1740. )
  1741. );
  1742. A_CBW:
  1743. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1744. {$ifndef x86_64}
  1745. A_LDS:
  1746. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1747. A_LES:
  1748. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1749. {$endif not x86_64}
  1750. A_LFS:
  1751. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1752. A_LGS:
  1753. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1754. A_LSS:
  1755. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1756. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1757. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1758. A_LODSB:
  1759. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1760. A_LODSW:
  1761. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1762. {$ifdef x86_64}
  1763. A_LODSQ:
  1764. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1765. {$endif x86_64}
  1766. A_LODSD:
  1767. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1768. A_FSTSW, A_FNSTSW:
  1769. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1770. else
  1771. begin
  1772. with insprop[p.opcode] do
  1773. begin
  1774. if (
  1775. { xor %reg,%reg etc. is classed as a new value }
  1776. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1777. MatchOpType(p, top_reg, top_reg) and
  1778. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1779. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1780. ) then
  1781. begin
  1782. Result := True;
  1783. Exit;
  1784. end;
  1785. { Make sure the entire register is overwritten }
  1786. if (getregtype(reg) = R_INTREGISTER) then
  1787. begin
  1788. if (p.ops > 0) then
  1789. begin
  1790. if RegInOp(reg, p.oper[0]^) then
  1791. begin
  1792. if (p.oper[0]^.typ = top_ref) then
  1793. begin
  1794. if RegInRef(reg, p.oper[0]^.ref^) then
  1795. begin
  1796. Result := False;
  1797. Exit;
  1798. end;
  1799. end
  1800. else if (p.oper[0]^.typ = top_reg) then
  1801. begin
  1802. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1803. begin
  1804. Result := False;
  1805. Exit;
  1806. end
  1807. else if ([Ch_WOp1]*Ch<>[]) then
  1808. begin
  1809. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1810. Result := True
  1811. else
  1812. begin
  1813. Result := False;
  1814. Exit;
  1815. end;
  1816. end;
  1817. end;
  1818. end;
  1819. if (p.ops > 1) then
  1820. begin
  1821. if RegInOp(reg, p.oper[1]^) then
  1822. begin
  1823. if (p.oper[1]^.typ = top_ref) then
  1824. begin
  1825. if RegInRef(reg, p.oper[1]^.ref^) then
  1826. begin
  1827. Result := False;
  1828. Exit;
  1829. end;
  1830. end
  1831. else if (p.oper[1]^.typ = top_reg) then
  1832. begin
  1833. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1834. begin
  1835. Result := False;
  1836. Exit;
  1837. end
  1838. else if ([Ch_WOp2]*Ch<>[]) then
  1839. begin
  1840. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1841. Result := True
  1842. else
  1843. begin
  1844. Result := False;
  1845. Exit;
  1846. end;
  1847. end;
  1848. end;
  1849. end;
  1850. if (p.ops > 2) then
  1851. begin
  1852. if RegInOp(reg, p.oper[2]^) then
  1853. begin
  1854. if (p.oper[2]^.typ = top_ref) then
  1855. begin
  1856. if RegInRef(reg, p.oper[2]^.ref^) then
  1857. begin
  1858. Result := False;
  1859. Exit;
  1860. end;
  1861. end
  1862. else if (p.oper[2]^.typ = top_reg) then
  1863. begin
  1864. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1865. begin
  1866. Result := False;
  1867. Exit;
  1868. end
  1869. else if ([Ch_WOp3]*Ch<>[]) then
  1870. begin
  1871. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1872. Result := True
  1873. else
  1874. begin
  1875. Result := False;
  1876. Exit;
  1877. end;
  1878. end;
  1879. end;
  1880. end;
  1881. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1882. begin
  1883. if (p.oper[3]^.typ = top_ref) then
  1884. begin
  1885. if RegInRef(reg, p.oper[3]^.ref^) then
  1886. begin
  1887. Result := False;
  1888. Exit;
  1889. end;
  1890. end
  1891. else if (p.oper[3]^.typ = top_reg) then
  1892. begin
  1893. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1894. begin
  1895. Result := False;
  1896. Exit;
  1897. end
  1898. else if ([Ch_WOp4]*Ch<>[]) then
  1899. begin
  1900. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1901. Result := True
  1902. else
  1903. begin
  1904. Result := False;
  1905. Exit;
  1906. end;
  1907. end;
  1908. end;
  1909. end;
  1910. end;
  1911. end;
  1912. end;
  1913. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1914. case getsupreg(reg) of
  1915. RS_EAX:
  1916. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1917. begin
  1918. Result := True;
  1919. Exit;
  1920. end;
  1921. RS_ECX:
  1922. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1923. begin
  1924. Result := True;
  1925. Exit;
  1926. end;
  1927. RS_EDX:
  1928. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1929. begin
  1930. Result := True;
  1931. Exit;
  1932. end;
  1933. RS_EBX:
  1934. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1935. begin
  1936. Result := True;
  1937. Exit;
  1938. end;
  1939. RS_ESP:
  1940. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1941. begin
  1942. Result := True;
  1943. Exit;
  1944. end;
  1945. RS_EBP:
  1946. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1947. begin
  1948. Result := True;
  1949. Exit;
  1950. end;
  1951. RS_ESI:
  1952. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1953. begin
  1954. Result := True;
  1955. Exit;
  1956. end;
  1957. RS_EDI:
  1958. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1959. begin
  1960. Result := True;
  1961. Exit;
  1962. end;
  1963. else
  1964. ;
  1965. end;
  1966. end;
  1967. end;
  1968. end;
  1969. end;
  1970. end;
  1971. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1972. var
  1973. hp2,hp3 : tai;
  1974. begin
  1975. { some x86-64 issue a NOP before the real exit code }
  1976. if MatchInstruction(p,A_NOP,[]) then
  1977. GetNextInstruction(p,p);
  1978. result:=assigned(p) and (p.typ=ait_instruction) and
  1979. ((taicpu(p).opcode = A_RET) or
  1980. ((taicpu(p).opcode=A_LEAVE) and
  1981. GetNextInstruction(p,hp2) and
  1982. MatchInstruction(hp2,A_RET,[S_NO])
  1983. ) or
  1984. (((taicpu(p).opcode=A_LEA) and
  1985. MatchOpType(taicpu(p),top_ref,top_reg) and
  1986. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1987. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1988. ) and
  1989. GetNextInstruction(p,hp2) and
  1990. MatchInstruction(hp2,A_RET,[S_NO])
  1991. ) or
  1992. ((((taicpu(p).opcode=A_MOV) and
  1993. MatchOpType(taicpu(p),top_reg,top_reg) and
  1994. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1995. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1996. ((taicpu(p).opcode=A_LEA) and
  1997. MatchOpType(taicpu(p),top_ref,top_reg) and
  1998. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1999. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2000. )
  2001. ) and
  2002. GetNextInstruction(p,hp2) and
  2003. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2004. MatchOpType(taicpu(hp2),top_reg) and
  2005. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2006. GetNextInstruction(hp2,hp3) and
  2007. MatchInstruction(hp3,A_RET,[S_NO])
  2008. )
  2009. );
  2010. end;
  2011. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2012. begin
  2013. isFoldableArithOp := False;
  2014. case hp1.opcode of
  2015. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2016. isFoldableArithOp :=
  2017. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2018. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2019. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2020. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2021. (taicpu(hp1).oper[1]^.reg = reg);
  2022. A_INC,A_DEC,A_NEG,A_NOT:
  2023. isFoldableArithOp :=
  2024. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2025. (taicpu(hp1).oper[0]^.reg = reg);
  2026. else
  2027. ;
  2028. end;
  2029. end;
  2030. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2031. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2032. var
  2033. hp2: tai;
  2034. begin
  2035. hp2 := p;
  2036. repeat
  2037. hp2 := tai(hp2.previous);
  2038. if assigned(hp2) and
  2039. (hp2.typ = ait_regalloc) and
  2040. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2041. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2042. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2043. begin
  2044. RemoveInstruction(hp2);
  2045. break;
  2046. end;
  2047. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2048. end;
  2049. begin
  2050. case current_procinfo.procdef.returndef.typ of
  2051. arraydef,recorddef,pointerdef,
  2052. stringdef,enumdef,procdef,objectdef,errordef,
  2053. filedef,setdef,procvardef,
  2054. classrefdef,forwarddef:
  2055. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2056. orddef:
  2057. if current_procinfo.procdef.returndef.size <> 0 then
  2058. begin
  2059. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2060. { for int64/qword }
  2061. if current_procinfo.procdef.returndef.size = 8 then
  2062. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2063. end;
  2064. else
  2065. ;
  2066. end;
  2067. end;
  2068. function TX86AsmOptimizer.OptPass1CMOVcc(var p: tai): Boolean;
  2069. var
  2070. hp1: tai;
  2071. operswap: poper;
  2072. begin
  2073. Result := False;
  2074. { Optimise:
  2075. cmov(c) %reg1,%reg2
  2076. mov %reg2,%reg1
  2077. (%reg2 dealloc.)
  2078. To:
  2079. cmov(~c) %reg2,%reg1
  2080. }
  2081. if (taicpu(p).oper[0]^.typ = top_reg) then
  2082. while GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) and
  2083. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  2084. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  2085. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[0]^.reg) do
  2086. begin
  2087. TransferUsedRegs(TmpUsedRegs);
  2088. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2089. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2090. begin
  2091. DebugMsg(SPeepholeOptimization + 'CMOV(c) %reg1,%reg2; MOV %reg2,%reg1 -> CMOV(~c) %reg2,%reg1 (CMovMov2CMov)', p);
  2092. { Save time by swapping the pointers (they're both registers, so
  2093. we don't need to worry about reference counts) }
  2094. operswap := taicpu(p).oper[0];
  2095. taicpu(p).oper[0] := taicpu(p).oper[1];
  2096. taicpu(p).oper[1] := operswap;
  2097. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  2098. RemoveInstruction(hp1);
  2099. { It's still a CMOV, so we can look further ahead }
  2100. Include(OptsToCheck, aoc_ForceNewIteration);
  2101. { But first, let's see if this will get optimised again
  2102. (probably won't happen, but best to be sure) }
  2103. Continue;
  2104. end;
  2105. Break;
  2106. end;
  2107. end;
  2108. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2109. var
  2110. hp1,hp2 : tai;
  2111. begin
  2112. result:=false;
  2113. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2114. begin
  2115. { vmova* reg1,reg1
  2116. =>
  2117. <nop> }
  2118. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2119. begin
  2120. RemoveCurrentP(p);
  2121. result:=true;
  2122. exit;
  2123. end;
  2124. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2125. (hp1.typ = ait_instruction) and
  2126. (
  2127. { Under -O2 and below, the instructions are always adjacent }
  2128. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2129. (taicpu(hp1).ops <= 1) or
  2130. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2131. { If reg1 = reg3, reg1 must not be modified in between }
  2132. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2133. ) then
  2134. begin
  2135. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2136. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2137. begin
  2138. { vmova* reg1,reg2
  2139. ...
  2140. vmova* reg2,reg3
  2141. dealloc reg2
  2142. =>
  2143. vmova* reg1,reg3 }
  2144. TransferUsedRegs(TmpUsedRegs);
  2145. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2146. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2147. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2148. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2149. begin
  2150. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2151. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2152. TransferUsedRegs(TmpUsedRegs);
  2153. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2154. RemoveInstruction(hp1);
  2155. result:=true;
  2156. exit;
  2157. end;
  2158. { special case:
  2159. vmova* reg1,<op>
  2160. ...
  2161. vmova* <op>,reg1
  2162. =>
  2163. vmova* reg1,<op> }
  2164. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2165. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2166. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2167. ) then
  2168. begin
  2169. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2170. RemoveInstruction(hp1);
  2171. result:=true;
  2172. exit;
  2173. end
  2174. end
  2175. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2176. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2177. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2178. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2179. ) and
  2180. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2181. begin
  2182. { vmova* reg1,reg2
  2183. ...
  2184. vmovs* reg2,<op>
  2185. dealloc reg2
  2186. =>
  2187. vmovs* reg1,<op> }
  2188. TransferUsedRegs(TmpUsedRegs);
  2189. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2190. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2191. begin
  2192. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2193. taicpu(p).opcode:=taicpu(hp1).opcode;
  2194. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2195. TransferUsedRegs(TmpUsedRegs);
  2196. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2197. RemoveInstruction(hp1);
  2198. result:=true;
  2199. exit;
  2200. end
  2201. end;
  2202. if MatchInstruction(hp1,[A_VFMADDPD,
  2203. A_VFMADD132PD,
  2204. A_VFMADD132PS,
  2205. A_VFMADD132SD,
  2206. A_VFMADD132SS,
  2207. A_VFMADD213PD,
  2208. A_VFMADD213PS,
  2209. A_VFMADD213SD,
  2210. A_VFMADD213SS,
  2211. A_VFMADD231PD,
  2212. A_VFMADD231PS,
  2213. A_VFMADD231SD,
  2214. A_VFMADD231SS,
  2215. A_VFMADDSUB132PD,
  2216. A_VFMADDSUB132PS,
  2217. A_VFMADDSUB213PD,
  2218. A_VFMADDSUB213PS,
  2219. A_VFMADDSUB231PD,
  2220. A_VFMADDSUB231PS,
  2221. A_VFMSUB132PD,
  2222. A_VFMSUB132PS,
  2223. A_VFMSUB132SD,
  2224. A_VFMSUB132SS,
  2225. A_VFMSUB213PD,
  2226. A_VFMSUB213PS,
  2227. A_VFMSUB213SD,
  2228. A_VFMSUB213SS,
  2229. A_VFMSUB231PD,
  2230. A_VFMSUB231PS,
  2231. A_VFMSUB231SD,
  2232. A_VFMSUB231SS,
  2233. A_VFMSUBADD132PD,
  2234. A_VFMSUBADD132PS,
  2235. A_VFMSUBADD213PD,
  2236. A_VFMSUBADD213PS,
  2237. A_VFMSUBADD231PD,
  2238. A_VFMSUBADD231PS,
  2239. A_VFNMADD132PD,
  2240. A_VFNMADD132PS,
  2241. A_VFNMADD132SD,
  2242. A_VFNMADD132SS,
  2243. A_VFNMADD213PD,
  2244. A_VFNMADD213PS,
  2245. A_VFNMADD213SD,
  2246. A_VFNMADD213SS,
  2247. A_VFNMADD231PD,
  2248. A_VFNMADD231PS,
  2249. A_VFNMADD231SD,
  2250. A_VFNMADD231SS,
  2251. A_VFNMSUB132PD,
  2252. A_VFNMSUB132PS,
  2253. A_VFNMSUB132SD,
  2254. A_VFNMSUB132SS,
  2255. A_VFNMSUB213PD,
  2256. A_VFNMSUB213PS,
  2257. A_VFNMSUB213SD,
  2258. A_VFNMSUB213SS,
  2259. A_VFNMSUB231PD,
  2260. A_VFNMSUB231PS,
  2261. A_VFNMSUB231SD,
  2262. A_VFNMSUB231SS],[S_NO]) and
  2263. { we mix single and double opperations here because we assume that the compiler
  2264. generates vmovapd only after double operations and vmovaps only after single operations }
  2265. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2266. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2267. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2268. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2269. begin
  2270. TransferUsedRegs(TmpUsedRegs);
  2271. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2272. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2273. begin
  2274. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2275. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2276. RemoveCurrentP(p)
  2277. else
  2278. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2279. RemoveInstruction(hp2);
  2280. end;
  2281. end
  2282. else if (hp1.typ = ait_instruction) and
  2283. (((taicpu(p).opcode=A_MOVAPS) and
  2284. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2285. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2286. ((taicpu(p).opcode=A_MOVAPD) and
  2287. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2288. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2289. ) and
  2290. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2291. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2292. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2293. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2294. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2295. { change
  2296. movapX reg,reg2
  2297. addsX/subsX/... reg3, reg2
  2298. movapX reg2,reg
  2299. to
  2300. addsX/subsX/... reg3,reg
  2301. }
  2302. begin
  2303. TransferUsedRegs(TmpUsedRegs);
  2304. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2305. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2306. begin
  2307. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2308. debug_op2str(taicpu(p).opcode)+' '+
  2309. debug_op2str(taicpu(hp1).opcode)+' '+
  2310. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2311. { we cannot eliminate the first move if
  2312. the operations uses the same register for source and dest }
  2313. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2314. { Remember that hp1 is not necessarily the immediate
  2315. next instruction }
  2316. RemoveCurrentP(p);
  2317. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2318. RemoveInstruction(hp2);
  2319. result:=true;
  2320. end;
  2321. end
  2322. else if (hp1.typ = ait_instruction) and
  2323. (((taicpu(p).opcode=A_VMOVAPD) and
  2324. (taicpu(hp1).opcode=A_VCOMISD)) or
  2325. ((taicpu(p).opcode=A_VMOVAPS) and
  2326. ((taicpu(hp1).opcode=A_VCOMISS))
  2327. )
  2328. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2329. { change
  2330. movapX reg,reg1
  2331. vcomisX reg1,reg1
  2332. to
  2333. vcomisX reg,reg
  2334. }
  2335. begin
  2336. TransferUsedRegs(TmpUsedRegs);
  2337. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2338. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2339. begin
  2340. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2341. debug_op2str(taicpu(p).opcode)+' '+
  2342. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2343. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2344. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2345. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2346. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2347. RemoveCurrentP(p);
  2348. result:=true;
  2349. exit;
  2350. end;
  2351. end
  2352. end;
  2353. end;
  2354. end;
  2355. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2356. var
  2357. hp1 : tai;
  2358. begin
  2359. result:=false;
  2360. { replace
  2361. V<Op>X %mreg1,%mreg2,%mreg3
  2362. VMovX %mreg3,%mreg4
  2363. dealloc %mreg3
  2364. by
  2365. V<Op>X %mreg1,%mreg2,%mreg4
  2366. ?
  2367. }
  2368. if GetNextInstruction(p,hp1) and
  2369. { we mix single and double operations here because we assume that the compiler
  2370. generates vmovapd only after double operations and vmovaps only after single operations }
  2371. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2372. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2373. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2374. begin
  2375. TransferUsedRegs(TmpUsedRegs);
  2376. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2377. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2378. begin
  2379. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2380. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2381. RemoveInstruction(hp1);
  2382. result:=true;
  2383. end;
  2384. end;
  2385. end;
  2386. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2387. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2388. begin
  2389. Result := False;
  2390. { For safety reasons, only check for exact register matches }
  2391. { Check base register }
  2392. if (ref.base = AOldReg) then
  2393. begin
  2394. ref.base := ANewReg;
  2395. Result := True;
  2396. end;
  2397. { Check index register }
  2398. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2399. begin
  2400. ref.index := ANewReg;
  2401. Result := True;
  2402. end;
  2403. end;
  2404. { Replaces all references to AOldReg in an operand to ANewReg }
  2405. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2406. var
  2407. OldSupReg, NewSupReg: TSuperRegister;
  2408. OldSubReg, NewSubReg: TSubRegister;
  2409. OldRegType: TRegisterType;
  2410. ThisOper: POper;
  2411. begin
  2412. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2413. Result := False;
  2414. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2415. InternalError(2020011801);
  2416. OldSupReg := getsupreg(AOldReg);
  2417. OldSubReg := getsubreg(AOldReg);
  2418. OldRegType := getregtype(AOldReg);
  2419. NewSupReg := getsupreg(ANewReg);
  2420. NewSubReg := getsubreg(ANewReg);
  2421. if OldRegType <> getregtype(ANewReg) then
  2422. InternalError(2020011802);
  2423. if OldSubReg <> NewSubReg then
  2424. InternalError(2020011803);
  2425. case ThisOper^.typ of
  2426. top_reg:
  2427. if (
  2428. (ThisOper^.reg = AOldReg) or
  2429. (
  2430. (OldRegType = R_INTREGISTER) and
  2431. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2432. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2433. (
  2434. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2435. {$ifndef x86_64}
  2436. and (
  2437. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2438. don't have an 8-bit representation }
  2439. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2440. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2441. )
  2442. {$endif x86_64}
  2443. )
  2444. )
  2445. ) then
  2446. begin
  2447. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2448. Result := True;
  2449. end;
  2450. top_ref:
  2451. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2452. Result := True;
  2453. else
  2454. ;
  2455. end;
  2456. end;
  2457. { Replaces all references to AOldReg in an instruction to ANewReg }
  2458. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2459. const
  2460. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2461. var
  2462. OperIdx: Integer;
  2463. begin
  2464. Result := False;
  2465. for OperIdx := 0 to p.ops - 1 do
  2466. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2467. begin
  2468. { The shift and rotate instructions can only use CL }
  2469. if not (
  2470. (OperIdx = 0) and
  2471. { This second condition just helps to avoid unnecessarily
  2472. calling MatchInstruction for 10 different opcodes }
  2473. (p.oper[0]^.reg = NR_CL) and
  2474. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2475. ) then
  2476. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2477. end
  2478. else if p.oper[OperIdx]^.typ = top_ref then
  2479. { It's okay to replace registers in references that get written to }
  2480. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2481. end;
  2482. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2483. begin
  2484. Result :=
  2485. (ref^.index = NR_NO) and
  2486. (
  2487. {$ifdef x86_64}
  2488. (
  2489. (ref^.base = NR_RIP) and
  2490. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2491. ) or
  2492. {$endif x86_64}
  2493. (ref^.refaddr = addr_full) or
  2494. (ref^.base = NR_STACK_POINTER_REG) or
  2495. (ref^.base = current_procinfo.framepointer)
  2496. );
  2497. end;
  2498. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2499. var
  2500. l: asizeint;
  2501. begin
  2502. Result := False;
  2503. { Should have been checked previously }
  2504. if p.opcode <> A_LEA then
  2505. InternalError(2020072501);
  2506. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2507. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2508. not(cs_opt_size in current_settings.optimizerswitches) then
  2509. exit;
  2510. with p.oper[0]^.ref^ do
  2511. begin
  2512. if (base <> p.oper[1]^.reg) or
  2513. (index <> NR_NO) or
  2514. assigned(symbol) then
  2515. exit;
  2516. l:=offset;
  2517. if (l=1) and UseIncDec then
  2518. begin
  2519. p.opcode:=A_INC;
  2520. p.loadreg(0,p.oper[1]^.reg);
  2521. p.ops:=1;
  2522. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2523. end
  2524. else if (l=-1) and UseIncDec then
  2525. begin
  2526. p.opcode:=A_DEC;
  2527. p.loadreg(0,p.oper[1]^.reg);
  2528. p.ops:=1;
  2529. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2530. end
  2531. else
  2532. begin
  2533. if (l<0) and (l<>-2147483648) then
  2534. begin
  2535. p.opcode:=A_SUB;
  2536. p.loadConst(0,-l);
  2537. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2538. end
  2539. else
  2540. begin
  2541. p.opcode:=A_ADD;
  2542. p.loadConst(0,l);
  2543. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2544. end;
  2545. end;
  2546. end;
  2547. Result := True;
  2548. end;
  2549. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2550. var
  2551. CurrentReg, ReplaceReg: TRegister;
  2552. begin
  2553. Result := False;
  2554. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2555. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2556. case hp.opcode of
  2557. A_FSTSW, A_FNSTSW,
  2558. A_IN, A_INS, A_OUT, A_OUTS,
  2559. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2560. { These routines have explicit operands, but they are restricted in
  2561. what they can be (e.g. IN and OUT can only read from AL, AX or
  2562. EAX. }
  2563. Exit;
  2564. A_IMUL:
  2565. begin
  2566. { The 1-operand version writes to implicit registers
  2567. The 2-operand version reads from the first operator, and reads
  2568. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2569. the 3-operand version reads from a register that it doesn't write to
  2570. }
  2571. case hp.ops of
  2572. 1:
  2573. if (
  2574. (
  2575. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2576. ) or
  2577. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2578. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2579. begin
  2580. Result := True;
  2581. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2582. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2583. end;
  2584. 2:
  2585. { Only modify the first parameter }
  2586. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2587. begin
  2588. Result := True;
  2589. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2590. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2591. end;
  2592. 3:
  2593. { Only modify the second parameter }
  2594. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2595. begin
  2596. Result := True;
  2597. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2598. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2599. end;
  2600. else
  2601. InternalError(2020012901);
  2602. end;
  2603. end;
  2604. else
  2605. if (hp.ops > 0) and
  2606. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2607. begin
  2608. Result := True;
  2609. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2610. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2611. end;
  2612. end;
  2613. end;
  2614. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2615. var
  2616. hp2, hp_regalloc: tai;
  2617. p_SourceReg, p_TargetReg: TRegister;
  2618. begin
  2619. Result := False;
  2620. { Backward optimisation. If we have:
  2621. func. %reg1,%reg2
  2622. mov %reg2,%reg3
  2623. (dealloc %reg2)
  2624. Change to:
  2625. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2626. Perform similar optimisations with 1, 3 and 4-operand instructions
  2627. that only have one output.
  2628. }
  2629. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2630. begin
  2631. p_SourceReg := taicpu(p).oper[0]^.reg;
  2632. p_TargetReg := taicpu(p).oper[1]^.reg;
  2633. TransferUsedRegs(TmpUsedRegs);
  2634. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2635. GetLastInstruction(p, hp2) and
  2636. (hp2.typ = ait_instruction) and
  2637. { Have to make sure it's an instruction that only reads from
  2638. the first operands and only writes (not reads or modifies) to
  2639. the last one; in essence, a pure function such as BSR, POPCNT
  2640. or ANDN }
  2641. (
  2642. (
  2643. (taicpu(hp2).ops = 1) and
  2644. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2645. ) or
  2646. (
  2647. (taicpu(hp2).ops = 2) and
  2648. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2649. ) or
  2650. (
  2651. (taicpu(hp2).ops = 3) and
  2652. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2653. ) or
  2654. (
  2655. (taicpu(hp2).ops = 4) and
  2656. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2657. )
  2658. ) and
  2659. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2660. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2661. begin
  2662. case taicpu(hp2).opcode of
  2663. A_FSTSW, A_FNSTSW,
  2664. A_IN, A_INS, A_OUT, A_OUTS,
  2665. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2666. { These routines have explicit operands, but they are restricted in
  2667. what they can be (e.g. IN and OUT can only read from AL, AX or
  2668. EAX. }
  2669. ;
  2670. else
  2671. begin
  2672. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2673. { if %reg2 (p_SourceReg) is allocated before func., remove it completely }
  2674. hp_regalloc := FindRegAllocBackward(p_SourceReg, hp2);
  2675. if Assigned(hp_regalloc) then
  2676. begin
  2677. Asml.Remove(hp_regalloc);
  2678. if Assigned(FindRegDealloc(p_SourceReg, p)) then
  2679. begin
  2680. ExcludeRegFromUsedRegs(p_SourceReg, UsedRegs);
  2681. hp_regalloc.Free;
  2682. end
  2683. else
  2684. { If the register is not explicitly deallocated, it's
  2685. being reused, so move the allocation to after func. }
  2686. AsmL.InsertAfter(hp_regalloc, hp2);
  2687. end;
  2688. if not RegInInstruction(p_TargetReg, hp2) then
  2689. begin
  2690. TransferUsedRegs(TmpUsedRegs);
  2691. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2692. end;
  2693. { Actually make the changes }
  2694. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2695. RemoveCurrentp(p, hp1);
  2696. { If the Func was another MOV instruction, we might get
  2697. "mov %reg,%reg" that doesn't get removed in Pass 2
  2698. otherwise, so deal with it here (also do something
  2699. similar with lea (%reg),%reg}
  2700. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2701. begin
  2702. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2703. if p = hp2 then
  2704. RemoveCurrentp(p)
  2705. else
  2706. RemoveInstruction(hp2);
  2707. end;
  2708. Result := True;
  2709. Exit;
  2710. end;
  2711. end;
  2712. end;
  2713. end;
  2714. end;
  2715. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2716. begin
  2717. Result := False;
  2718. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2719. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2720. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2721. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2722. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2723. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2724. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2725. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2726. begin
  2727. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2728. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2729. Result := True;
  2730. end;
  2731. end;
  2732. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2733. var
  2734. hp1, hp2, hp3, hp4: tai;
  2735. DoOptimisation, TempBool: Boolean;
  2736. {$ifdef x86_64}
  2737. NewConst: TCGInt;
  2738. {$endif x86_64}
  2739. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2740. begin
  2741. if taicpu(hp1).opcode = signed_movop then
  2742. begin
  2743. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2744. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2745. end
  2746. else
  2747. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2748. end;
  2749. function TryConstMerge(var p1, p2: tai): Boolean;
  2750. var
  2751. ThisRef: TReference;
  2752. begin
  2753. Result := False;
  2754. ThisRef := taicpu(p2).oper[1]^.ref^;
  2755. { Only permit writes to the stack, since we can guarantee alignment with that }
  2756. if (ThisRef.index = NR_NO) and
  2757. (
  2758. (ThisRef.base = NR_STACK_POINTER_REG) or
  2759. (ThisRef.base = current_procinfo.framepointer)
  2760. ) then
  2761. begin
  2762. case taicpu(p).opsize of
  2763. S_B:
  2764. begin
  2765. { Word writes must be on a 2-byte boundary }
  2766. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2767. begin
  2768. { Reduce offset of second reference to see if it is sequential with the first }
  2769. Dec(ThisRef.offset, 1);
  2770. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2771. begin
  2772. { Make sure the constants aren't represented as a
  2773. negative number, as these won't merge properly }
  2774. taicpu(p1).opsize := S_W;
  2775. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2776. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2777. RemoveInstruction(p2);
  2778. Result := True;
  2779. end;
  2780. end;
  2781. end;
  2782. S_W:
  2783. begin
  2784. { Longword writes must be on a 4-byte boundary }
  2785. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2786. begin
  2787. { Reduce offset of second reference to see if it is sequential with the first }
  2788. Dec(ThisRef.offset, 2);
  2789. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2790. begin
  2791. { Make sure the constants aren't represented as a
  2792. negative number, as these won't merge properly }
  2793. taicpu(p1).opsize := S_L;
  2794. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2795. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2796. RemoveInstruction(p2);
  2797. Result := True;
  2798. end;
  2799. end;
  2800. end;
  2801. {$ifdef x86_64}
  2802. S_L:
  2803. begin
  2804. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2805. see if the constants can be encoded this way. }
  2806. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2807. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2808. { Quadword writes must be on an 8-byte boundary }
  2809. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2810. begin
  2811. { Reduce offset of second reference to see if it is sequential with the first }
  2812. Dec(ThisRef.offset, 4);
  2813. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2814. begin
  2815. { Make sure the constants aren't represented as a
  2816. negative number, as these won't merge properly }
  2817. taicpu(p1).opsize := S_Q;
  2818. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2819. taicpu(p1).oper[0]^.val := NewConst;
  2820. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2821. RemoveInstruction(p2);
  2822. Result := True;
  2823. end;
  2824. end;
  2825. end;
  2826. {$endif x86_64}
  2827. else
  2828. ;
  2829. end;
  2830. end;
  2831. end;
  2832. var
  2833. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2834. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2835. NewSize: topsize; NewOffset: asizeint;
  2836. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2837. SourceRef, TargetRef: TReference;
  2838. MovAligned, MovUnaligned: TAsmOp;
  2839. ThisRef: TReference;
  2840. JumpTracking: TLinkedList;
  2841. begin
  2842. Result:=false;
  2843. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2844. { remove mov reg1,reg1? }
  2845. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2846. then
  2847. begin
  2848. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2849. { take care of the register (de)allocs following p }
  2850. RemoveCurrentP(p, hp1);
  2851. Result:=true;
  2852. exit;
  2853. end;
  2854. { All the next optimisations require a next instruction }
  2855. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2856. Exit;
  2857. { Prevent compiler warnings }
  2858. p_TargetReg := NR_NO;
  2859. if taicpu(p).oper[1]^.typ = top_reg then
  2860. begin
  2861. { Saves on a large number of dereferences }
  2862. p_TargetReg := taicpu(p).oper[1]^.reg;
  2863. { Look for:
  2864. mov %reg1,%reg2
  2865. ??? %reg2,r/m
  2866. Change to:
  2867. mov %reg1,%reg2
  2868. ??? %reg1,r/m
  2869. }
  2870. if taicpu(p).oper[0]^.typ = top_reg then
  2871. begin
  2872. if RegReadByInstruction(p_TargetReg, hp1) and
  2873. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2874. begin
  2875. { A change has occurred, just not in p }
  2876. Result := True;
  2877. TransferUsedRegs(TmpUsedRegs);
  2878. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2879. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2880. { Just in case something didn't get modified (e.g. an
  2881. implicit register) }
  2882. not RegReadByInstruction(p_TargetReg, hp1) then
  2883. begin
  2884. { We can remove the original MOV }
  2885. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2886. RemoveCurrentp(p, hp1);
  2887. { UsedRegs got updated by RemoveCurrentp }
  2888. Result := True;
  2889. Exit;
  2890. end;
  2891. { If we know a MOV instruction has become a null operation, we might as well
  2892. get rid of it now to save time. }
  2893. if (taicpu(hp1).opcode = A_MOV) and
  2894. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2895. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2896. { Just being a register is enough to confirm it's a null operation }
  2897. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2898. begin
  2899. Result := True;
  2900. { Speed-up to reduce a pipeline stall... if we had something like...
  2901. movl %eax,%edx
  2902. movw %dx,%ax
  2903. ... the second instruction would change to movw %ax,%ax, but
  2904. given that it is now %ax that's active rather than %eax,
  2905. penalties might occur due to a partial register write, so instead,
  2906. change it to a MOVZX instruction when optimising for speed.
  2907. }
  2908. if not (cs_opt_size in current_settings.optimizerswitches) and
  2909. IsMOVZXAcceptable and
  2910. (taicpu(hp1).opsize < taicpu(p).opsize)
  2911. {$ifdef x86_64}
  2912. { operations already implicitly set the upper 64 bits to zero }
  2913. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2914. {$endif x86_64}
  2915. then
  2916. begin
  2917. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2918. case taicpu(p).opsize of
  2919. S_W:
  2920. if taicpu(hp1).opsize = S_B then
  2921. taicpu(hp1).opsize := S_BL
  2922. else
  2923. InternalError(2020012911);
  2924. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2925. case taicpu(hp1).opsize of
  2926. S_B:
  2927. taicpu(hp1).opsize := S_BL;
  2928. S_W:
  2929. taicpu(hp1).opsize := S_WL;
  2930. else
  2931. InternalError(2020012912);
  2932. end;
  2933. else
  2934. InternalError(2020012910);
  2935. end;
  2936. taicpu(hp1).opcode := A_MOVZX;
  2937. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2938. end
  2939. else
  2940. begin
  2941. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2942. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2943. RemoveInstruction(hp1);
  2944. { The instruction after what was hp1 is now the immediate next instruction,
  2945. so we can continue to make optimisations if it's present }
  2946. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2947. Exit;
  2948. hp1 := hp2;
  2949. end;
  2950. end;
  2951. end;
  2952. end;
  2953. end;
  2954. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2955. overwrites the original destination register. e.g.
  2956. movl ###,%reg2d
  2957. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2958. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2959. }
  2960. if (taicpu(p).oper[1]^.typ = top_reg) and
  2961. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2962. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2963. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2964. begin
  2965. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2966. begin
  2967. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2968. case taicpu(p).oper[0]^.typ of
  2969. top_const:
  2970. { We have something like:
  2971. movb $x, %regb
  2972. movzbl %regb,%regd
  2973. Change to:
  2974. movl $x, %regd
  2975. }
  2976. begin
  2977. case taicpu(hp1).opsize of
  2978. S_BW:
  2979. begin
  2980. convert_mov_value(A_MOVSX, $FF);
  2981. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2982. taicpu(p).opsize := S_W;
  2983. end;
  2984. S_BL:
  2985. begin
  2986. convert_mov_value(A_MOVSX, $FF);
  2987. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2988. taicpu(p).opsize := S_L;
  2989. end;
  2990. S_WL:
  2991. begin
  2992. convert_mov_value(A_MOVSX, $FFFF);
  2993. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2994. taicpu(p).opsize := S_L;
  2995. end;
  2996. {$ifdef x86_64}
  2997. S_BQ:
  2998. begin
  2999. convert_mov_value(A_MOVSX, $FF);
  3000. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3001. taicpu(p).opsize := S_Q;
  3002. end;
  3003. S_WQ:
  3004. begin
  3005. convert_mov_value(A_MOVSX, $FFFF);
  3006. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3007. taicpu(p).opsize := S_Q;
  3008. end;
  3009. S_LQ:
  3010. begin
  3011. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  3012. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3013. taicpu(p).opsize := S_Q;
  3014. end;
  3015. {$endif x86_64}
  3016. else
  3017. { If hp1 was a MOV instruction, it should have been
  3018. optimised already }
  3019. InternalError(2020021001);
  3020. end;
  3021. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  3022. RemoveInstruction(hp1);
  3023. Result := True;
  3024. Exit;
  3025. end;
  3026. top_ref:
  3027. begin
  3028. { We have something like:
  3029. movb mem, %regb
  3030. movzbl %regb,%regd
  3031. Change to:
  3032. movzbl mem, %regd
  3033. }
  3034. ThisRef := taicpu(p).oper[0]^.ref^;
  3035. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  3036. begin
  3037. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  3038. taicpu(hp1).loadref(0, ThisRef);
  3039. { Make sure any registers in the references are properly tracked }
  3040. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  3041. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  3042. if (ThisRef.index <> NR_NO) then
  3043. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  3044. RemoveCurrentP(p, hp1);
  3045. Result := True;
  3046. Exit;
  3047. end;
  3048. end;
  3049. else
  3050. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  3051. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  3052. Exit;
  3053. end;
  3054. end
  3055. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3056. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3057. optimised }
  3058. else
  3059. begin
  3060. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3061. RemoveCurrentP(p, hp1);
  3062. Result := True;
  3063. Exit;
  3064. end;
  3065. end;
  3066. if (taicpu(hp1).opcode = A_AND) and
  3067. (taicpu(p).oper[1]^.typ = top_reg) and
  3068. MatchOpType(taicpu(hp1),top_const,top_reg) then
  3069. begin
  3070. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  3071. begin
  3072. case taicpu(p).opsize of
  3073. S_L:
  3074. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  3075. begin
  3076. { Optimize out:
  3077. mov x, %reg
  3078. and ffffffffh, %reg
  3079. }
  3080. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  3081. RemoveInstruction(hp1);
  3082. Result:=true;
  3083. exit;
  3084. end;
  3085. S_Q: { TODO: Confirm if this is even possible }
  3086. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  3087. begin
  3088. { Optimize out:
  3089. mov x, %reg
  3090. and ffffffffffffffffh, %reg
  3091. }
  3092. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  3093. RemoveInstruction(hp1);
  3094. Result:=true;
  3095. exit;
  3096. end;
  3097. else
  3098. ;
  3099. end;
  3100. if (
  3101. (taicpu(p).oper[0]^.typ=top_reg) or
  3102. (
  3103. (taicpu(p).oper[0]^.typ=top_ref) and
  3104. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  3105. )
  3106. ) and
  3107. GetNextInstruction(hp1,hp2) and
  3108. MatchInstruction(hp2,A_TEST,[]) and
  3109. (
  3110. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3111. (
  3112. { If the register being tested is smaller than the one
  3113. that received a bitwise AND, permit it if the constant
  3114. fits into the smaller size }
  3115. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3116. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3117. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3118. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3119. (
  3120. (
  3121. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3122. (taicpu(hp1).oper[0]^.val <= $FF)
  3123. ) or
  3124. (
  3125. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3126. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3127. {$ifdef x86_64}
  3128. ) or
  3129. (
  3130. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3131. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3132. {$endif x86_64}
  3133. )
  3134. )
  3135. )
  3136. ) and
  3137. (
  3138. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3139. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3140. ) and
  3141. GetNextInstruction(hp2,hp3) and
  3142. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3143. (taicpu(hp3).condition in [C_E,C_NE]) then
  3144. begin
  3145. TransferUsedRegs(TmpUsedRegs);
  3146. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3147. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3148. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3149. begin
  3150. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3151. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3152. taicpu(hp1).opcode:=A_TEST;
  3153. { Shrink the TEST instruction down to the smallest possible size }
  3154. case taicpu(hp1).oper[0]^.val of
  3155. 0..255:
  3156. if (taicpu(hp1).opsize <> S_B)
  3157. {$ifndef x86_64}
  3158. and (
  3159. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3160. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3161. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3162. )
  3163. {$endif x86_64}
  3164. then
  3165. begin
  3166. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3167. { Only print debug message if the TEST instruction
  3168. is a different size before and after }
  3169. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3170. taicpu(hp1).opsize := S_B;
  3171. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3172. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3173. end;
  3174. 256..65535:
  3175. if (taicpu(hp1).opsize <> S_W) then
  3176. begin
  3177. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3178. { Only print debug message if the TEST instruction
  3179. is a different size before and after }
  3180. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3181. taicpu(hp1).opsize := S_W;
  3182. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3183. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3184. end;
  3185. {$ifdef x86_64}
  3186. 65536..$7FFFFFFF:
  3187. if (taicpu(hp1).opsize <> S_L) then
  3188. begin
  3189. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3190. { Only print debug message if the TEST instruction
  3191. is a different size before and after }
  3192. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3193. taicpu(hp1).opsize := S_L;
  3194. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3195. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3196. end;
  3197. {$endif x86_64}
  3198. else
  3199. ;
  3200. end;
  3201. RemoveInstruction(hp2);
  3202. RemoveCurrentP(p, hp1);
  3203. Result:=true;
  3204. exit;
  3205. end;
  3206. end;
  3207. end
  3208. else if IsMOVZXAcceptable and
  3209. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3210. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3211. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3212. then
  3213. begin
  3214. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3215. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3216. case taicpu(p).opsize of
  3217. S_B:
  3218. if (taicpu(hp1).oper[0]^.val = $ff) then
  3219. begin
  3220. { Convert:
  3221. movb x, %regl movb x, %regl
  3222. andw ffh, %regw andl ffh, %regd
  3223. To:
  3224. movzbw x, %regd movzbl x, %regd
  3225. (Identical registers, just different sizes)
  3226. }
  3227. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3228. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3229. case taicpu(hp1).opsize of
  3230. S_W: NewSize := S_BW;
  3231. S_L: NewSize := S_BL;
  3232. {$ifdef x86_64}
  3233. S_Q: NewSize := S_BQ;
  3234. {$endif x86_64}
  3235. else
  3236. InternalError(2018011510);
  3237. end;
  3238. end
  3239. else
  3240. NewSize := S_NO;
  3241. S_W:
  3242. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3243. begin
  3244. { Convert:
  3245. movw x, %regw
  3246. andl ffffh, %regd
  3247. To:
  3248. movzwl x, %regd
  3249. (Identical registers, just different sizes)
  3250. }
  3251. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3252. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3253. case taicpu(hp1).opsize of
  3254. S_L: NewSize := S_WL;
  3255. {$ifdef x86_64}
  3256. S_Q: NewSize := S_WQ;
  3257. {$endif x86_64}
  3258. else
  3259. InternalError(2018011511);
  3260. end;
  3261. end
  3262. else
  3263. NewSize := S_NO;
  3264. else
  3265. NewSize := S_NO;
  3266. end;
  3267. if NewSize <> S_NO then
  3268. begin
  3269. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3270. { The actual optimization }
  3271. taicpu(p).opcode := A_MOVZX;
  3272. taicpu(p).changeopsize(NewSize);
  3273. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3274. { Safeguard if "and" is followed by a conditional command }
  3275. TransferUsedRegs(TmpUsedRegs);
  3276. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3277. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3278. begin
  3279. { At this point, the "and" command is effectively equivalent to
  3280. "test %reg,%reg". This will be handled separately by the
  3281. Peephole Optimizer. [Kit] }
  3282. DebugMsg(SPeepholeOptimization + PreMessage +
  3283. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3284. end
  3285. else
  3286. begin
  3287. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3288. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3289. RemoveInstruction(hp1);
  3290. end;
  3291. Result := True;
  3292. Exit;
  3293. end;
  3294. end;
  3295. end;
  3296. if (taicpu(hp1).opcode = A_OR) and
  3297. (taicpu(p).oper[1]^.typ = top_reg) and
  3298. MatchOperand(taicpu(p).oper[0]^, 0) and
  3299. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3300. begin
  3301. { mov 0, %reg
  3302. or ###,%reg
  3303. Change to (only if the flags are not used):
  3304. mov ###,%reg
  3305. }
  3306. TransferUsedRegs(TmpUsedRegs);
  3307. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3308. DoOptimisation := True;
  3309. { Even if the flags are used, we might be able to do the optimisation
  3310. if the conditions are predictable }
  3311. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3312. begin
  3313. { Only perform if ### = %reg (the same register) or equal to 0,
  3314. so %reg is guaranteed to still have a value of zero }
  3315. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3316. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3317. begin
  3318. hp2 := hp1;
  3319. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3320. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3321. GetNextInstruction(hp2, hp3) do
  3322. begin
  3323. { Don't continue modifying if the flags state is getting changed }
  3324. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3325. Break;
  3326. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3327. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3328. begin
  3329. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3330. begin
  3331. { Condition is always true }
  3332. case taicpu(hp3).opcode of
  3333. A_Jcc:
  3334. begin
  3335. { Check for jump shortcuts before we destroy the condition }
  3336. hp4 := hp3;
  3337. DoJumpOptimizations(hp3, TempBool);
  3338. { Make sure hp3 hasn't changed }
  3339. if (hp4 = hp3) then
  3340. begin
  3341. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3342. MakeUnconditional(taicpu(hp3));
  3343. end;
  3344. Result := True;
  3345. end;
  3346. A_CMOVcc:
  3347. begin
  3348. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3349. taicpu(hp3).opcode := A_MOV;
  3350. taicpu(hp3).condition := C_None;
  3351. Result := True;
  3352. end;
  3353. A_SETcc:
  3354. begin
  3355. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3356. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3357. taicpu(hp3).opcode := A_MOV;
  3358. taicpu(hp3).ops := 2;
  3359. taicpu(hp3).condition := C_None;
  3360. taicpu(hp3).opsize := S_B;
  3361. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3362. taicpu(hp3).loadconst(0, 1);
  3363. Result := True;
  3364. end;
  3365. else
  3366. InternalError(2021090701);
  3367. end;
  3368. end
  3369. 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
  3370. begin
  3371. { Condition is always false }
  3372. case taicpu(hp3).opcode of
  3373. A_Jcc:
  3374. begin
  3375. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3376. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3377. RemoveInstruction(hp3);
  3378. Result := True;
  3379. { Since hp3 was deleted, hp2 must not be updated }
  3380. Continue;
  3381. end;
  3382. A_CMOVcc:
  3383. begin
  3384. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3385. RemoveInstruction(hp3);
  3386. Result := True;
  3387. { Since hp3 was deleted, hp2 must not be updated }
  3388. Continue;
  3389. end;
  3390. A_SETcc:
  3391. begin
  3392. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3393. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3394. taicpu(hp3).opcode := A_MOV;
  3395. taicpu(hp3).ops := 2;
  3396. taicpu(hp3).condition := C_None;
  3397. taicpu(hp3).opsize := S_B;
  3398. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3399. taicpu(hp3).loadconst(0, 0);
  3400. Result := True;
  3401. end;
  3402. else
  3403. InternalError(2021090702);
  3404. end;
  3405. end
  3406. else
  3407. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3408. DoOptimisation := False;
  3409. end;
  3410. hp2 := hp3;
  3411. end;
  3412. { Flags are still in use - don't optimise }
  3413. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3414. DoOptimisation := False;
  3415. end
  3416. else
  3417. DoOptimisation := False;
  3418. end;
  3419. if DoOptimisation then
  3420. begin
  3421. {$ifdef x86_64}
  3422. { OR only supports 32-bit sign-extended constants for 64-bit
  3423. instructions, so compensate for this if the constant is
  3424. encoded as a value greater than or equal to 2^31 }
  3425. if (taicpu(hp1).opsize = S_Q) and
  3426. (taicpu(hp1).oper[0]^.typ = top_const) and
  3427. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3428. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3429. {$endif x86_64}
  3430. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3431. taicpu(hp1).opcode := A_MOV;
  3432. RemoveCurrentP(p, hp1);
  3433. Result := True;
  3434. Exit;
  3435. end;
  3436. end;
  3437. { Next instruction is also a MOV ? }
  3438. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3439. begin
  3440. if MatchOpType(taicpu(p), top_const, top_ref) and
  3441. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3442. TryConstMerge(p, hp1) then
  3443. begin
  3444. Result := True;
  3445. { In case we have four byte writes in a row, check for 2 more
  3446. right now so we don't have to wait for another iteration of
  3447. pass 1
  3448. }
  3449. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3450. case taicpu(p).opsize of
  3451. S_W:
  3452. begin
  3453. if GetNextInstruction(p, hp1) and
  3454. MatchInstruction(hp1, A_MOV, [S_B]) and
  3455. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3456. GetNextInstruction(hp1, hp2) and
  3457. MatchInstruction(hp2, A_MOV, [S_B]) and
  3458. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3459. { Try to merge the two bytes }
  3460. TryConstMerge(hp1, hp2) then
  3461. { Now try to merge the two words (hp2 will get deleted) }
  3462. TryConstMerge(p, hp1);
  3463. end;
  3464. S_L:
  3465. begin
  3466. { Though this only really benefits x86_64 and not i386, it
  3467. gets a potential optimisation done faster and hence
  3468. reduces the number of times OptPass1MOV is entered }
  3469. if GetNextInstruction(p, hp1) and
  3470. MatchInstruction(hp1, A_MOV, [S_W]) and
  3471. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3472. GetNextInstruction(hp1, hp2) and
  3473. MatchInstruction(hp2, A_MOV, [S_W]) and
  3474. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3475. { Try to merge the two words }
  3476. TryConstMerge(hp1, hp2) then
  3477. { This will always fail on i386, so don't bother
  3478. calling it unless we're doing x86_64 }
  3479. {$ifdef x86_64}
  3480. { Now try to merge the two longwords (hp2 will get deleted) }
  3481. TryConstMerge(p, hp1)
  3482. {$endif x86_64}
  3483. ;
  3484. end;
  3485. else
  3486. ;
  3487. end;
  3488. Exit;
  3489. end;
  3490. if (taicpu(p).oper[1]^.typ = top_reg) and
  3491. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3492. begin
  3493. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3494. TransferUsedRegs(TmpUsedRegs);
  3495. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3496. { we have
  3497. mov x, %treg
  3498. mov %treg, y
  3499. }
  3500. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3501. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3502. { we've got
  3503. mov x, %treg
  3504. mov %treg, y
  3505. with %treg is not used after }
  3506. case taicpu(p).oper[0]^.typ Of
  3507. { top_reg is covered by DeepMOVOpt }
  3508. top_const:
  3509. begin
  3510. { change
  3511. mov const, %treg
  3512. mov %treg, y
  3513. to
  3514. mov const, y
  3515. }
  3516. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3517. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3518. begin
  3519. if taicpu(hp1).oper[1]^.typ=top_reg then
  3520. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3521. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3522. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3523. RemoveInstruction(hp1);
  3524. Result:=true;
  3525. Exit;
  3526. end;
  3527. end;
  3528. top_ref:
  3529. case taicpu(hp1).oper[1]^.typ of
  3530. top_reg:
  3531. begin
  3532. { change
  3533. mov mem, %treg
  3534. mov %treg, %reg
  3535. to
  3536. mov mem, %reg"
  3537. }
  3538. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3539. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3540. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3541. RemoveInstruction(hp1);
  3542. Result:=true;
  3543. Exit;
  3544. end;
  3545. top_ref:
  3546. begin
  3547. {$ifdef x86_64}
  3548. { Look for the following to simplify:
  3549. mov x(mem1), %reg
  3550. mov %reg, y(mem2)
  3551. mov x+8(mem1), %reg
  3552. mov %reg, y+8(mem2)
  3553. Change to:
  3554. movdqu x(mem1), %xmmreg
  3555. movdqu %xmmreg, y(mem2)
  3556. ...but only as long as the memory blocks don't overlap
  3557. }
  3558. SourceRef := taicpu(p).oper[0]^.ref^;
  3559. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3560. if (taicpu(p).opsize = S_Q) and
  3561. GetNextInstruction(hp1, hp2) and
  3562. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3563. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3564. begin
  3565. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3566. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3567. Inc(SourceRef.offset, 8);
  3568. if UseAVX then
  3569. begin
  3570. MovAligned := A_VMOVDQA;
  3571. MovUnaligned := A_VMOVDQU;
  3572. end
  3573. else
  3574. begin
  3575. MovAligned := A_MOVDQA;
  3576. MovUnaligned := A_MOVDQU;
  3577. end;
  3578. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3579. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3580. begin
  3581. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3582. Inc(TargetRef.offset, 8);
  3583. if GetNextInstruction(hp2, hp3) and
  3584. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3585. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3586. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3587. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3588. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3589. begin
  3590. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3591. if NewMMReg <> NR_NO then
  3592. begin
  3593. { Remember that the offsets are 8 ahead }
  3594. if ((SourceRef.offset mod 16) = 8) and
  3595. (
  3596. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3597. (SourceRef.base = current_procinfo.framepointer) or
  3598. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3599. ) then
  3600. taicpu(p).opcode := MovAligned
  3601. else
  3602. taicpu(p).opcode := MovUnaligned;
  3603. taicpu(p).opsize := S_XMM;
  3604. taicpu(p).oper[1]^.reg := NewMMReg;
  3605. if ((TargetRef.offset mod 16) = 8) and
  3606. (
  3607. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3608. (TargetRef.base = current_procinfo.framepointer) or
  3609. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3610. ) then
  3611. taicpu(hp1).opcode := MovAligned
  3612. else
  3613. taicpu(hp1).opcode := MovUnaligned;
  3614. taicpu(hp1).opsize := S_XMM;
  3615. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3616. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3617. RemoveInstruction(hp2);
  3618. RemoveInstruction(hp3);
  3619. Result := True;
  3620. Exit;
  3621. end;
  3622. end;
  3623. end
  3624. else
  3625. begin
  3626. { See if the next references are 8 less rather than 8 greater }
  3627. Dec(SourceRef.offset, 16); { -8 the other way }
  3628. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3629. begin
  3630. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3631. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3632. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3633. GetNextInstruction(hp2, hp3) and
  3634. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3635. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3636. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3637. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3638. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3639. begin
  3640. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3641. if NewMMReg <> NR_NO then
  3642. begin
  3643. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3644. if ((SourceRef.offset mod 16) = 0) and
  3645. (
  3646. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3647. (SourceRef.base = current_procinfo.framepointer) or
  3648. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3649. ) then
  3650. taicpu(hp2).opcode := MovAligned
  3651. else
  3652. taicpu(hp2).opcode := MovUnaligned;
  3653. taicpu(hp2).opsize := S_XMM;
  3654. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3655. if ((TargetRef.offset mod 16) = 0) and
  3656. (
  3657. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3658. (TargetRef.base = current_procinfo.framepointer) or
  3659. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3660. ) then
  3661. taicpu(hp3).opcode := MovAligned
  3662. else
  3663. taicpu(hp3).opcode := MovUnaligned;
  3664. taicpu(hp3).opsize := S_XMM;
  3665. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3666. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3667. RemoveInstruction(hp1);
  3668. RemoveCurrentP(p, hp2);
  3669. Result := True;
  3670. Exit;
  3671. end;
  3672. end;
  3673. end;
  3674. end;
  3675. end;
  3676. {$endif x86_64}
  3677. end;
  3678. else
  3679. { The write target should be a reg or a ref }
  3680. InternalError(2021091601);
  3681. end;
  3682. else
  3683. ;
  3684. end
  3685. else
  3686. { %treg is used afterwards, but all eventualities
  3687. other than the first MOV instruction being a constant
  3688. are covered by DeepMOVOpt, so only check for that }
  3689. if (taicpu(p).oper[0]^.typ = top_const) and
  3690. (
  3691. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3692. not (cs_opt_size in current_settings.optimizerswitches) or
  3693. (taicpu(hp1).opsize = S_B)
  3694. ) and
  3695. (
  3696. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3697. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3698. ) then
  3699. begin
  3700. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3701. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3702. end;
  3703. end;
  3704. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3705. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3706. { mov reg1, mem1 or mov mem1, reg1
  3707. mov mem2, reg2 mov reg2, mem2}
  3708. begin
  3709. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3710. { mov reg1, mem1 or mov mem1, reg1
  3711. mov mem2, reg1 mov reg2, mem1}
  3712. begin
  3713. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3714. { Removes the second statement from
  3715. mov reg1, mem1/reg2
  3716. mov mem1/reg2, reg1 }
  3717. begin
  3718. if taicpu(p).oper[0]^.typ=top_reg then
  3719. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3720. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3721. RemoveInstruction(hp1);
  3722. Result:=true;
  3723. exit;
  3724. end
  3725. else
  3726. begin
  3727. TransferUsedRegs(TmpUsedRegs);
  3728. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3729. if (taicpu(p).oper[1]^.typ = top_ref) and
  3730. { mov reg1, mem1
  3731. mov mem2, reg1 }
  3732. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3733. GetNextInstruction(hp1, hp2) and
  3734. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3735. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3736. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3737. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3738. { change to
  3739. mov reg1, mem1 mov reg1, mem1
  3740. mov mem2, reg1 cmp reg1, mem2
  3741. cmp mem1, reg1
  3742. }
  3743. begin
  3744. RemoveInstruction(hp2);
  3745. taicpu(hp1).opcode := A_CMP;
  3746. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3747. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3748. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3749. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3750. end;
  3751. end;
  3752. end
  3753. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3754. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3755. begin
  3756. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3757. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3758. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3759. end
  3760. else
  3761. begin
  3762. TransferUsedRegs(TmpUsedRegs);
  3763. if GetNextInstruction(hp1, hp2) and
  3764. MatchOpType(taicpu(p),top_ref,top_reg) and
  3765. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3766. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3767. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3768. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3769. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3770. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3771. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3772. { mov mem1, %reg1
  3773. mov %reg1, mem2
  3774. mov mem2, reg2
  3775. to:
  3776. mov mem1, reg2
  3777. mov reg2, mem2}
  3778. begin
  3779. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3780. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3781. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3782. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3783. RemoveInstruction(hp2);
  3784. Result := True;
  3785. end
  3786. {$ifdef i386}
  3787. { this is enabled for i386 only, as the rules to create the reg sets below
  3788. are too complicated for x86-64, so this makes this code too error prone
  3789. on x86-64
  3790. }
  3791. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3792. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3793. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3794. { mov mem1, reg1 mov mem1, reg1
  3795. mov reg1, mem2 mov reg1, mem2
  3796. mov mem2, reg2 mov mem2, reg1
  3797. to: to:
  3798. mov mem1, reg1 mov mem1, reg1
  3799. mov mem1, reg2 mov reg1, mem2
  3800. mov reg1, mem2
  3801. or (if mem1 depends on reg1
  3802. and/or if mem2 depends on reg2)
  3803. to:
  3804. mov mem1, reg1
  3805. mov reg1, mem2
  3806. mov reg1, reg2
  3807. }
  3808. begin
  3809. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3810. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3811. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3812. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3813. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3814. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3815. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3816. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3817. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3818. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3819. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3820. end
  3821. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3822. begin
  3823. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3824. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3825. end
  3826. else
  3827. begin
  3828. RemoveInstruction(hp2);
  3829. end
  3830. {$endif i386}
  3831. ;
  3832. end;
  3833. end
  3834. { movl [mem1],reg1
  3835. movl [mem1],reg2
  3836. to
  3837. movl [mem1],reg1
  3838. movl reg1,reg2
  3839. }
  3840. else if not CheckMovMov2MovMov2(p, hp1) and
  3841. { movl const1,[mem1]
  3842. movl [mem1],reg1
  3843. to
  3844. movl const1,reg1
  3845. movl reg1,[mem1]
  3846. }
  3847. MatchOpType(Taicpu(p),top_const,top_ref) and
  3848. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3849. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3850. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3851. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3852. begin
  3853. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3854. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3855. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3856. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3857. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3858. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3859. Result:=true;
  3860. exit;
  3861. end;
  3862. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3863. { Change:
  3864. movl %reg1,%reg2
  3865. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3866. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3867. To:
  3868. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3869. movl x(%reg1),%reg1
  3870. movl %reg1,%regX
  3871. }
  3872. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3873. begin
  3874. p_SourceReg := taicpu(p).oper[0]^.reg;
  3875. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3876. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3877. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3878. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3879. GetNextInstruction(hp1, hp2) and
  3880. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3881. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3882. begin
  3883. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3884. if RegInRef(p_TargetReg, SourceRef) and
  3885. { If %reg1 also appears in the second reference, then it will
  3886. not refer to the same memory block as the first reference }
  3887. not RegInRef(p_SourceReg, SourceRef) then
  3888. begin
  3889. { Check to see if the references match if %reg2 is changed to %reg1 }
  3890. if SourceRef.base = p_TargetReg then
  3891. SourceRef.base := p_SourceReg;
  3892. if SourceRef.index = p_TargetReg then
  3893. SourceRef.index := p_SourceReg;
  3894. { RefsEqual also checks to ensure both references are non-volatile }
  3895. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3896. begin
  3897. taicpu(hp2).loadreg(0, p_SourceReg);
  3898. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3899. Result := True;
  3900. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3901. begin
  3902. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3903. RemoveCurrentP(p, hp1);
  3904. Exit;
  3905. end
  3906. else
  3907. begin
  3908. { Check to see if %reg2 is no longer in use }
  3909. TransferUsedRegs(TmpUsedRegs);
  3910. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3911. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3912. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3913. begin
  3914. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3915. RemoveCurrentP(p, hp1);
  3916. Exit;
  3917. end;
  3918. end;
  3919. { If we reach this point, p and hp1 weren't actually modified,
  3920. so we can do a bit more work on this pass }
  3921. end;
  3922. end;
  3923. end;
  3924. end;
  3925. end;
  3926. {$ifdef x86_64}
  3927. { Change:
  3928. movl %reg1l,%reg2l
  3929. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3930. To:
  3931. movl %reg1l,%reg2l
  3932. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3933. If %reg1 = %reg3, convert to:
  3934. movl %reg1l,%reg2l
  3935. andl %reg1l,%reg1l
  3936. }
  3937. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3938. MatchOpType(taicpu(p), top_reg, top_reg) and
  3939. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3940. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3941. begin
  3942. TransferUsedRegs(TmpUsedRegs);
  3943. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3944. taicpu(hp1).opsize := S_L;
  3945. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3946. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3947. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3948. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3949. begin
  3950. { %reg1 = %reg3 }
  3951. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3952. taicpu(hp1).opcode := A_AND;
  3953. end
  3954. else
  3955. begin
  3956. { %reg1 <> %reg3 }
  3957. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3958. end;
  3959. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3960. begin
  3961. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3962. RemoveCurrentP(p, hp1);
  3963. Result := True;
  3964. Exit;
  3965. end
  3966. else
  3967. begin
  3968. { Initial instruction wasn't actually changed }
  3969. Include(OptsToCheck, aoc_ForceNewIteration);
  3970. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3971. appears below since %reg1 has technically changed }
  3972. if taicpu(hp1).opcode = A_AND then
  3973. Exit;
  3974. end;
  3975. end;
  3976. {$endif x86_64}
  3977. { search further than the next instruction for a mov (as long as it's not a jump) }
  3978. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3979. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3980. (taicpu(p).oper[1]^.typ = top_reg) and
  3981. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3982. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3983. begin
  3984. { we work with hp2 here, so hp1 can be still used later on when
  3985. checking for GetNextInstruction_p }
  3986. hp3 := hp1;
  3987. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3988. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3989. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3990. TransferUsedRegs(TmpUsedRegs);
  3991. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3992. if NotFirstIteration then
  3993. JumpTracking := TLinkedList.Create
  3994. else
  3995. JumpTracking := nil;
  3996. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3997. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3998. (hp2.typ=ait_instruction) do
  3999. begin
  4000. case taicpu(hp2).opcode of
  4001. A_POP:
  4002. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4003. begin
  4004. if not CrossJump and
  4005. not RegUsedBetween(p_TargetReg, p, hp2) then
  4006. begin
  4007. { We can remove the original MOV since the register
  4008. wasn't used between it and its popping from the stack }
  4009. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4010. RemoveCurrentp(p, hp1);
  4011. Result := True;
  4012. JumpTracking.Free;
  4013. Exit;
  4014. end;
  4015. { Can't go any further }
  4016. Break;
  4017. end;
  4018. A_MOV:
  4019. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4020. ((taicpu(p).oper[0]^.typ=top_const) or
  4021. ((taicpu(p).oper[0]^.typ=top_reg) and
  4022. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4023. )
  4024. ) then
  4025. begin
  4026. { we have
  4027. mov x, %treg
  4028. mov %treg, y
  4029. }
  4030. { We don't need to call UpdateUsedRegs for every instruction between
  4031. p and hp2 because the register we're concerned about will not
  4032. become deallocated (otherwise GetNextInstructionUsingReg would
  4033. have stopped at an earlier instruction). [Kit] }
  4034. TempRegUsed :=
  4035. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4036. RegReadByInstruction(p_TargetReg, hp3) or
  4037. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4038. case taicpu(p).oper[0]^.typ Of
  4039. top_reg:
  4040. begin
  4041. { change
  4042. mov %reg, %treg
  4043. mov %treg, y
  4044. to
  4045. mov %reg, y
  4046. }
  4047. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4048. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4049. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4050. begin
  4051. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4052. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4053. if TempRegUsed then
  4054. begin
  4055. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4056. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4057. { Set the start of the next GetNextInstructionUsingRegCond search
  4058. to start at the entry right before hp2 (which is about to be removed) }
  4059. hp3 := tai(hp2.Previous);
  4060. RemoveInstruction(hp2);
  4061. Include(OptsToCheck, aoc_ForceNewIteration);
  4062. { See if there's more we can optimise }
  4063. Continue;
  4064. end
  4065. else
  4066. begin
  4067. RemoveInstruction(hp2);
  4068. { We can remove the original MOV too }
  4069. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4070. RemoveCurrentP(p, hp1);
  4071. Result:=true;
  4072. JumpTracking.Free;
  4073. Exit;
  4074. end;
  4075. end
  4076. else
  4077. begin
  4078. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4079. taicpu(hp2).loadReg(0, p_SourceReg);
  4080. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4081. { Check to see if the register also appears in the reference }
  4082. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4083. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4084. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4085. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4086. begin
  4087. { Don't remove the first instruction if the temporary register is in use }
  4088. if not TempRegUsed then
  4089. begin
  4090. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4091. RemoveCurrentP(p, hp1);
  4092. Result:=true;
  4093. JumpTracking.Free;
  4094. Exit;
  4095. end;
  4096. { No need to set Result to True here. If there's another instruction later
  4097. on that can be optimised, it will be detected when the main Pass 1 loop
  4098. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4099. hp3 := hp2;
  4100. Continue;
  4101. end;
  4102. end;
  4103. end;
  4104. top_const:
  4105. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4106. begin
  4107. { change
  4108. mov const, %treg
  4109. mov %treg, y
  4110. to
  4111. mov const, y
  4112. }
  4113. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4114. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4115. begin
  4116. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4117. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4118. if TempRegUsed then
  4119. begin
  4120. { Don't remove the first instruction if the temporary register is in use }
  4121. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4122. { No need to set Result to True. If there's another instruction later on
  4123. that can be optimised, it will be detected when the main Pass 1 loop
  4124. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4125. end
  4126. else
  4127. begin
  4128. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4129. RemoveCurrentP(p, hp1);
  4130. Result:=true;
  4131. Exit;
  4132. end;
  4133. end;
  4134. end;
  4135. else
  4136. Internalerror(2019103001);
  4137. end;
  4138. end
  4139. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4140. begin
  4141. if not CrossJump and
  4142. not RegUsedBetween(p_TargetReg, p, hp2) and
  4143. not RegReadByInstruction(p_TargetReg, hp2) then
  4144. begin
  4145. { Register is not used before it is overwritten }
  4146. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4147. RemoveCurrentp(p, hp1);
  4148. Result := True;
  4149. Exit;
  4150. end;
  4151. if (taicpu(p).oper[0]^.typ = top_const) and
  4152. (taicpu(hp2).oper[0]^.typ = top_const) then
  4153. begin
  4154. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4155. begin
  4156. { Same value - register hasn't changed }
  4157. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4158. RemoveInstruction(hp2);
  4159. Include(OptsToCheck, aoc_ForceNewIteration);
  4160. { See if there's more we can optimise }
  4161. Continue;
  4162. end;
  4163. end;
  4164. {$ifdef x86_64}
  4165. end
  4166. { Change:
  4167. movl %reg1l,%reg2l
  4168. ...
  4169. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4170. To:
  4171. movl %reg1l,%reg2l
  4172. ...
  4173. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4174. If %reg1 = %reg3, convert to:
  4175. movl %reg1l,%reg2l
  4176. ...
  4177. andl %reg1l,%reg1l
  4178. }
  4179. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4180. (taicpu(p).oper[0]^.typ = top_reg) and
  4181. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4182. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4183. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4184. begin
  4185. TempRegUsed :=
  4186. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4187. RegReadByInstruction(p_TargetReg, hp3) or
  4188. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4189. taicpu(hp2).opsize := S_L;
  4190. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4191. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4192. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4193. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4194. begin
  4195. { %reg1 = %reg3 }
  4196. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4197. taicpu(hp2).opcode := A_AND;
  4198. end
  4199. else
  4200. begin
  4201. { %reg1 <> %reg3 }
  4202. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4203. end;
  4204. if not TempRegUsed then
  4205. begin
  4206. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4207. RemoveCurrentP(p, hp1);
  4208. Result := True;
  4209. Exit;
  4210. end
  4211. else
  4212. begin
  4213. { Initial instruction wasn't actually changed }
  4214. Include(OptsToCheck, aoc_ForceNewIteration);
  4215. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4216. appears below since %reg1 has technically changed }
  4217. if taicpu(hp2).opcode = A_AND then
  4218. Break;
  4219. end;
  4220. {$endif x86_64}
  4221. end
  4222. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4223. GetNextInstruction(hp2, hp4) and
  4224. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4225. { Optimise the following first:
  4226. movl [mem1],reg1
  4227. movl [mem1],reg2
  4228. to
  4229. movl [mem1],reg1
  4230. movl reg1,reg2
  4231. If [mem1] contains the target register and reg1 is the
  4232. the source register, this optimisation will get missed
  4233. and produce less efficient code later on.
  4234. }
  4235. if CheckMovMov2MovMov2(hp2, hp4) then
  4236. { Initial instruction wasn't actually changed }
  4237. Include(OptsToCheck, aoc_ForceNewIteration);
  4238. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4239. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4240. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4241. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4242. begin
  4243. {
  4244. Change from:
  4245. mov ###, %reg
  4246. ...
  4247. movs/z %reg,%reg (Same register, just different sizes)
  4248. To:
  4249. movs/z ###, %reg (Longer version)
  4250. ...
  4251. (remove)
  4252. }
  4253. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4254. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4255. { Keep the first instruction as mov if ### is a constant }
  4256. if taicpu(p).oper[0]^.typ = top_const then
  4257. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4258. else
  4259. begin
  4260. taicpu(p).opcode := taicpu(hp2).opcode;
  4261. taicpu(p).opsize := taicpu(hp2).opsize;
  4262. end;
  4263. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4264. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4265. RemoveInstruction(hp2);
  4266. Result := True;
  4267. JumpTracking.Free;
  4268. Exit;
  4269. end;
  4270. else
  4271. { Move down to the if-block below };
  4272. end;
  4273. { Also catches MOV/S/Z instructions that aren't modified }
  4274. if taicpu(p).oper[0]^.typ = top_reg then
  4275. begin
  4276. p_SourceReg := taicpu(p).oper[0]^.reg;
  4277. if
  4278. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4279. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4280. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4281. begin
  4282. Result := True;
  4283. { Just in case something didn't get modified (e.g. an
  4284. implicit register). Also, if it does read from this
  4285. register, then there's no longer an advantage to
  4286. changing the register on subsequent instructions.}
  4287. if not RegReadByInstruction(p_TargetReg, hp2) then
  4288. begin
  4289. { If a conditional jump was crossed, do not delete
  4290. the original MOV no matter what }
  4291. if not CrossJump and
  4292. { RegEndOfLife returns True if the register is
  4293. deallocated before the next instruction or has
  4294. been loaded with a new value }
  4295. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4296. begin
  4297. { We can remove the original MOV }
  4298. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4299. RemoveCurrentp(p, hp1);
  4300. JumpTracking.Free;
  4301. Result := True;
  4302. Exit;
  4303. end;
  4304. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4305. begin
  4306. { See if there's more we can optimise }
  4307. hp3 := hp2;
  4308. Continue;
  4309. end;
  4310. end;
  4311. end;
  4312. end;
  4313. { Break out of the while loop under normal circumstances }
  4314. Break;
  4315. end;
  4316. JumpTracking.Free;
  4317. end;
  4318. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4319. (taicpu(p).oper[1]^.typ = top_reg) and
  4320. (taicpu(p).opsize = S_L) and
  4321. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4322. (hp2.typ = ait_instruction) and
  4323. (taicpu(hp2).opcode = A_AND) and
  4324. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4325. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4326. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4327. ) then
  4328. begin
  4329. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4330. begin
  4331. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4332. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4333. begin
  4334. { Optimize out:
  4335. mov x, %reg
  4336. and ffffffffh, %reg
  4337. }
  4338. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4339. RemoveInstruction(hp2);
  4340. Result:=true;
  4341. exit;
  4342. end;
  4343. end;
  4344. end;
  4345. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4346. x >= RetOffset) as it doesn't do anything (it writes either to a
  4347. parameter or to the temporary storage room for the function
  4348. result)
  4349. }
  4350. if IsExitCode(hp1) and
  4351. (taicpu(p).oper[1]^.typ = top_ref) and
  4352. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4353. (
  4354. (
  4355. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4356. not (
  4357. assigned(current_procinfo.procdef.funcretsym) and
  4358. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4359. )
  4360. ) or
  4361. { Also discard writes to the stack that are below the base pointer,
  4362. as this is temporary storage rather than a function result on the
  4363. stack, say. }
  4364. (
  4365. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4366. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4367. )
  4368. ) then
  4369. begin
  4370. RemoveCurrentp(p, hp1);
  4371. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4372. RemoveLastDeallocForFuncRes(p);
  4373. Result:=true;
  4374. exit;
  4375. end;
  4376. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4377. begin
  4378. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4379. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4380. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4381. begin
  4382. { change
  4383. mov reg1, mem1
  4384. test/cmp x, mem1
  4385. to
  4386. mov reg1, mem1
  4387. test/cmp x, reg1
  4388. }
  4389. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4390. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4391. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4392. Result := True;
  4393. Exit;
  4394. end;
  4395. if DoMovCmpMemOpt(p, hp1) then
  4396. begin
  4397. Result := True;
  4398. Exit;
  4399. end;
  4400. end;
  4401. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4402. { If the flags register is in use, don't change the instruction to an
  4403. ADD otherwise this will scramble the flags. [Kit] }
  4404. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4405. begin
  4406. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4407. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4408. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4409. ) or
  4410. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4411. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4412. )
  4413. ) then
  4414. { mov reg1,ref
  4415. lea reg2,[reg1,reg2]
  4416. to
  4417. add reg2,ref}
  4418. begin
  4419. TransferUsedRegs(TmpUsedRegs);
  4420. { reg1 may not be used afterwards }
  4421. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4422. begin
  4423. Taicpu(hp1).opcode:=A_ADD;
  4424. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4425. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4426. RemoveCurrentp(p, hp1);
  4427. result:=true;
  4428. exit;
  4429. end;
  4430. end;
  4431. { If the LEA instruction can be converted into an arithmetic instruction,
  4432. it may be possible to then fold it in the next optimisation, otherwise
  4433. there's nothing more that can be optimised here. }
  4434. if not ConvertLEA(taicpu(hp1)) then
  4435. Exit;
  4436. end;
  4437. if (taicpu(p).oper[1]^.typ = top_reg) and
  4438. (hp1.typ = ait_instruction) and
  4439. GetNextInstruction(hp1, hp2) and
  4440. MatchInstruction(hp2,A_MOV,[]) and
  4441. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4442. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4443. (
  4444. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4445. {$ifdef x86_64}
  4446. or
  4447. (
  4448. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4449. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4450. )
  4451. {$endif x86_64}
  4452. ) then
  4453. begin
  4454. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4455. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4456. { change movsX/movzX reg/ref, reg2
  4457. add/sub/or/... reg3/$const, reg2
  4458. mov reg2 reg/ref
  4459. dealloc reg2
  4460. to
  4461. add/sub/or/... reg3/$const, reg/ref }
  4462. begin
  4463. TransferUsedRegs(TmpUsedRegs);
  4464. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4465. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4466. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4467. begin
  4468. { by example:
  4469. movswl %si,%eax movswl %si,%eax p
  4470. decl %eax addl %edx,%eax hp1
  4471. movw %ax,%si movw %ax,%si hp2
  4472. ->
  4473. movswl %si,%eax movswl %si,%eax p
  4474. decw %eax addw %edx,%eax hp1
  4475. movw %ax,%si movw %ax,%si hp2
  4476. }
  4477. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4478. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4479. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4480. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4481. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4482. {
  4483. ->
  4484. movswl %si,%eax movswl %si,%eax p
  4485. decw %si addw %dx,%si hp1
  4486. movw %ax,%si movw %ax,%si hp2
  4487. }
  4488. case taicpu(hp1).ops of
  4489. 1:
  4490. begin
  4491. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4492. if taicpu(hp1).oper[0]^.typ=top_reg then
  4493. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4494. end;
  4495. 2:
  4496. begin
  4497. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4498. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4499. (taicpu(hp1).opcode<>A_SHL) and
  4500. (taicpu(hp1).opcode<>A_SHR) and
  4501. (taicpu(hp1).opcode<>A_SAR) then
  4502. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4503. end;
  4504. else
  4505. internalerror(2008042701);
  4506. end;
  4507. {
  4508. ->
  4509. decw %si addw %dx,%si p
  4510. }
  4511. RemoveInstruction(hp2);
  4512. RemoveCurrentP(p, hp1);
  4513. Result:=True;
  4514. Exit;
  4515. end;
  4516. end;
  4517. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4518. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4519. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4520. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4521. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4522. )
  4523. {$ifdef i386}
  4524. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4525. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4526. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4527. {$endif i386}
  4528. then
  4529. { change movsX/movzX reg/ref, reg2
  4530. add/sub/or/... regX/$const, reg2
  4531. mov reg2, reg3
  4532. dealloc reg2
  4533. to
  4534. movsX/movzX reg/ref, reg3
  4535. add/sub/or/... reg3/$const, reg3
  4536. }
  4537. begin
  4538. TransferUsedRegs(TmpUsedRegs);
  4539. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4540. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4541. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4542. begin
  4543. { by example:
  4544. movswl %si,%eax movswl %si,%eax p
  4545. decl %eax addl %edx,%eax hp1
  4546. movw %ax,%si movw %ax,%si hp2
  4547. ->
  4548. movswl %si,%eax movswl %si,%eax p
  4549. decw %eax addw %edx,%eax hp1
  4550. movw %ax,%si movw %ax,%si hp2
  4551. }
  4552. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4553. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4554. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4555. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4556. { limit size of constants as well to avoid assembler errors, but
  4557. check opsize to avoid overflow when left shifting the 1 }
  4558. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4559. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4560. {$ifdef x86_64}
  4561. { Be careful of, for example:
  4562. movl %reg1,%reg2
  4563. addl %reg3,%reg2
  4564. movq %reg2,%reg4
  4565. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4566. }
  4567. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4568. begin
  4569. taicpu(hp2).changeopsize(S_L);
  4570. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4571. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4572. end;
  4573. {$endif x86_64}
  4574. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4575. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4576. if taicpu(p).oper[0]^.typ=top_reg then
  4577. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4578. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4579. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4580. {
  4581. ->
  4582. movswl %si,%eax movswl %si,%eax p
  4583. decw %si addw %dx,%si hp1
  4584. movw %ax,%si movw %ax,%si hp2
  4585. }
  4586. case taicpu(hp1).ops of
  4587. 1:
  4588. begin
  4589. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4590. if taicpu(hp1).oper[0]^.typ=top_reg then
  4591. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4592. end;
  4593. 2:
  4594. begin
  4595. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4596. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4597. (taicpu(hp1).opcode<>A_SHL) and
  4598. (taicpu(hp1).opcode<>A_SHR) and
  4599. (taicpu(hp1).opcode<>A_SAR) then
  4600. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4601. end;
  4602. else
  4603. internalerror(2018111801);
  4604. end;
  4605. {
  4606. ->
  4607. decw %si addw %dx,%si p
  4608. }
  4609. RemoveInstruction(hp2);
  4610. end;
  4611. end;
  4612. end;
  4613. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4614. GetNextInstruction(hp1, hp2) and
  4615. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4616. MatchOperand(Taicpu(p).oper[0]^,0) and
  4617. (Taicpu(p).oper[1]^.typ = top_reg) and
  4618. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4619. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4620. { mov reg1,0
  4621. bts reg1,operand1 --> mov reg1,operand2
  4622. or reg1,operand2 bts reg1,operand1}
  4623. begin
  4624. Taicpu(hp2).opcode:=A_MOV;
  4625. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4626. asml.remove(hp1);
  4627. insertllitem(hp2,hp2.next,hp1);
  4628. RemoveCurrentp(p, hp1);
  4629. Result:=true;
  4630. exit;
  4631. end;
  4632. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4633. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4634. GetNextInstruction(hp1, hp2) and
  4635. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4636. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4637. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4638. { change
  4639. mov reg1,reg2
  4640. sub reg3,reg2
  4641. cmp reg3,reg1
  4642. into
  4643. mov reg1,reg2
  4644. sub reg3,reg2
  4645. }
  4646. begin
  4647. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4648. RemoveInstruction(hp2);
  4649. Result:=true;
  4650. exit;
  4651. end;
  4652. {
  4653. mov ref,reg0
  4654. <op> reg0,reg1
  4655. dealloc reg0
  4656. to
  4657. <op> ref,reg1
  4658. }
  4659. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4660. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4661. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4662. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4663. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4664. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4665. begin
  4666. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4667. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4668. RemoveCurrentp(p, hp1);
  4669. Result:=true;
  4670. exit;
  4671. end;
  4672. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4673. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4674. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4675. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4676. begin
  4677. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4678. {$ifdef x86_64}
  4679. { Convert:
  4680. movq x(ref),%reg64
  4681. shrq y,%reg64
  4682. To:
  4683. movl x+4(ref),%reg32
  4684. shrl y-32,%reg32 (Remove if y = 32)
  4685. }
  4686. if (taicpu(p).opsize = S_Q) and
  4687. (taicpu(hp1).opcode = A_SHR) and
  4688. (taicpu(hp1).oper[0]^.val >= 32) then
  4689. begin
  4690. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4691. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4692. { Convert to 32-bit }
  4693. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4694. taicpu(p).opsize := S_L;
  4695. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4696. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4697. if (taicpu(hp1).oper[0]^.val = 32) then
  4698. begin
  4699. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4700. RemoveInstruction(hp1);
  4701. end
  4702. else
  4703. begin
  4704. { This will potentially open up more arithmetic operations since
  4705. the peephole optimizer now has a big hint that only the lower
  4706. 32 bits are currently in use (and opcodes are smaller in size) }
  4707. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4708. taicpu(hp1).opsize := S_L;
  4709. Dec(taicpu(hp1).oper[0]^.val, 32);
  4710. DebugMsg(SPeepholeOptimization + PreMessage +
  4711. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4712. end;
  4713. Result := True;
  4714. Exit;
  4715. end;
  4716. {$endif x86_64}
  4717. { Convert:
  4718. movl x(ref),%reg
  4719. shrl $24,%reg
  4720. To:
  4721. movzbl x+3(ref),%reg
  4722. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4723. Also accept sar instead of shr, but convert to movsx instead of movzx
  4724. }
  4725. if taicpu(hp1).opcode = A_SHR then
  4726. MovUnaligned := A_MOVZX
  4727. else
  4728. MovUnaligned := A_MOVSX;
  4729. NewSize := S_NO;
  4730. NewOffset := 0;
  4731. case taicpu(p).opsize of
  4732. S_B:
  4733. { No valid combinations };
  4734. S_W:
  4735. if (taicpu(hp1).oper[0]^.val = 8) then
  4736. begin
  4737. NewSize := S_BW;
  4738. NewOffset := 1;
  4739. end;
  4740. S_L:
  4741. case taicpu(hp1).oper[0]^.val of
  4742. 16:
  4743. begin
  4744. NewSize := S_WL;
  4745. NewOffset := 2;
  4746. end;
  4747. 24:
  4748. begin
  4749. NewSize := S_BL;
  4750. NewOffset := 3;
  4751. end;
  4752. else
  4753. ;
  4754. end;
  4755. {$ifdef x86_64}
  4756. S_Q:
  4757. case taicpu(hp1).oper[0]^.val of
  4758. 32:
  4759. begin
  4760. if taicpu(hp1).opcode = A_SAR then
  4761. begin
  4762. { 32-bit to 64-bit is a distinct instruction }
  4763. MovUnaligned := A_MOVSXD;
  4764. NewSize := S_LQ;
  4765. NewOffset := 4;
  4766. end
  4767. else
  4768. { Should have been handled by MovShr2Mov above }
  4769. InternalError(2022081811);
  4770. end;
  4771. 48:
  4772. begin
  4773. NewSize := S_WQ;
  4774. NewOffset := 6;
  4775. end;
  4776. 56:
  4777. begin
  4778. NewSize := S_BQ;
  4779. NewOffset := 7;
  4780. end;
  4781. else
  4782. ;
  4783. end;
  4784. {$endif x86_64}
  4785. else
  4786. InternalError(2022081810);
  4787. end;
  4788. if (NewSize <> S_NO) and
  4789. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4790. begin
  4791. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4792. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4793. debug_op2str(MovUnaligned);
  4794. {$ifdef x86_64}
  4795. if MovUnaligned <> A_MOVSXD then
  4796. { Don't add size suffix for MOVSXD }
  4797. {$endif x86_64}
  4798. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4799. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4800. taicpu(p).opcode := MovUnaligned;
  4801. taicpu(p).opsize := NewSize;
  4802. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4803. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4804. RemoveInstruction(hp1);
  4805. Result := True;
  4806. Exit;
  4807. end;
  4808. end;
  4809. { Backward optimisation shared with OptPass2MOV }
  4810. if FuncMov2Func(p, hp1) then
  4811. begin
  4812. Result := True;
  4813. Exit;
  4814. end;
  4815. end;
  4816. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4817. var
  4818. hp1 : tai;
  4819. begin
  4820. Result:=false;
  4821. if taicpu(p).ops <> 2 then
  4822. exit;
  4823. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4824. GetNextInstruction(p,hp1) then
  4825. begin
  4826. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4827. (taicpu(hp1).ops = 2) then
  4828. begin
  4829. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4830. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4831. { movXX reg1, mem1 or movXX mem1, reg1
  4832. movXX mem2, reg2 movXX reg2, mem2}
  4833. begin
  4834. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4835. { movXX reg1, mem1 or movXX mem1, reg1
  4836. movXX mem2, reg1 movXX reg2, mem1}
  4837. begin
  4838. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4839. begin
  4840. { Removes the second statement from
  4841. movXX reg1, mem1/reg2
  4842. movXX mem1/reg2, reg1
  4843. }
  4844. if taicpu(p).oper[0]^.typ=top_reg then
  4845. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4846. { Removes the second statement from
  4847. movXX mem1/reg1, reg2
  4848. movXX reg2, mem1/reg1
  4849. }
  4850. if (taicpu(p).oper[1]^.typ=top_reg) and
  4851. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4852. begin
  4853. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4854. RemoveInstruction(hp1);
  4855. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4856. Result:=true;
  4857. exit;
  4858. end
  4859. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4860. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4861. begin
  4862. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4863. RemoveInstruction(hp1);
  4864. Result:=true;
  4865. exit;
  4866. end;
  4867. end
  4868. end;
  4869. end;
  4870. end;
  4871. end;
  4872. end;
  4873. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4874. var
  4875. hp1 : tai;
  4876. begin
  4877. result:=false;
  4878. { replace
  4879. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4880. MovX %mreg2,%mreg1
  4881. dealloc %mreg2
  4882. by
  4883. <Op>X %mreg2,%mreg1
  4884. ?
  4885. }
  4886. if GetNextInstruction(p,hp1) and
  4887. { we mix single and double opperations here because we assume that the compiler
  4888. generates vmovapd only after double operations and vmovaps only after single operations }
  4889. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4890. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4891. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4892. (taicpu(p).oper[0]^.typ=top_reg) then
  4893. begin
  4894. TransferUsedRegs(TmpUsedRegs);
  4895. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4896. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4897. begin
  4898. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4899. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4900. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4901. RemoveInstruction(hp1);
  4902. result:=true;
  4903. end;
  4904. end;
  4905. end;
  4906. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4907. var
  4908. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4909. JumpLabel, JumpLabel_dist: TAsmLabel;
  4910. FirstValue, SecondValue: TCGInt;
  4911. function OptimizeJump(var InputP: tai): Boolean;
  4912. var
  4913. TempBool: Boolean;
  4914. begin
  4915. Result := False;
  4916. TempBool := True;
  4917. if DoJumpOptimizations(InputP, TempBool) or
  4918. not TempBool then
  4919. begin
  4920. Result := True;
  4921. if Assigned(InputP) then
  4922. begin
  4923. { CollapseZeroDistJump will be set to the label or an align
  4924. before it after the jump if it optimises, whether or not
  4925. the label is live or dead }
  4926. if (InputP.typ = ait_align) or
  4927. (
  4928. (InputP.typ = ait_label) and
  4929. not (tai_label(InputP).labsym.is_used)
  4930. ) then
  4931. GetNextInstruction(InputP, InputP);
  4932. end;
  4933. Exit;
  4934. end;
  4935. end;
  4936. begin
  4937. Result := False;
  4938. if (taicpu(p).oper[0]^.typ = top_const) and
  4939. (taicpu(p).oper[0]^.val <> -1) then
  4940. begin
  4941. { Convert unsigned maximum constants to -1 to aid optimisation }
  4942. case taicpu(p).opsize of
  4943. S_B:
  4944. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4945. begin
  4946. taicpu(p).oper[0]^.val := -1;
  4947. Result := True;
  4948. Exit;
  4949. end;
  4950. S_W:
  4951. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4952. begin
  4953. taicpu(p).oper[0]^.val := -1;
  4954. Result := True;
  4955. Exit;
  4956. end;
  4957. S_L:
  4958. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4959. begin
  4960. taicpu(p).oper[0]^.val := -1;
  4961. Result := True;
  4962. Exit;
  4963. end;
  4964. {$ifdef x86_64}
  4965. S_Q:
  4966. { Storing anything greater than $7FFFFFFF is not possible so do
  4967. nothing };
  4968. {$endif x86_64}
  4969. else
  4970. InternalError(2021121001);
  4971. end;
  4972. end;
  4973. if GetNextInstruction(p, hp1) and
  4974. TrySwapMovCmp(p, hp1) then
  4975. begin
  4976. Result := True;
  4977. Exit;
  4978. end;
  4979. p_label := nil;
  4980. JumpLabel := nil;
  4981. if MatchInstruction(hp1, A_Jcc, []) then
  4982. begin
  4983. if OptimizeJump(hp1) then
  4984. begin
  4985. Result := True;
  4986. if Assigned(hp1) then
  4987. begin
  4988. { CollapseZeroDistJump will be set to the label or an align
  4989. before it after the jump if it optimises, whether or not
  4990. the label is live or dead }
  4991. if (hp1.typ = ait_align) or
  4992. (
  4993. (hp1.typ = ait_label) and
  4994. not (tai_label(hp1).labsym.is_used)
  4995. ) then
  4996. GetNextInstruction(hp1, hp1);
  4997. end;
  4998. TransferUsedRegs(TmpUsedRegs);
  4999. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5000. if not Assigned(hp1) or
  5001. (
  5002. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5003. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5004. ) then
  5005. begin
  5006. { No more conditional jumps; conditional statement is no longer required }
  5007. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5008. RemoveCurrentP(p);
  5009. end;
  5010. Exit;
  5011. end;
  5012. if IsJumpToLabel(taicpu(hp1)) then
  5013. begin
  5014. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5015. if Assigned(JumpLabel) then
  5016. p_label := getlabelwithsym(JumpLabel);
  5017. end;
  5018. end;
  5019. { Search for:
  5020. test $x,(reg/ref)
  5021. jne @lbl1
  5022. test $y,(reg/ref) (same register or reference)
  5023. jne @lbl1
  5024. Change to:
  5025. test $(x or y),(reg/ref)
  5026. jne @lbl1
  5027. (Note, this doesn't work with je instead of jne)
  5028. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5029. Also search for:
  5030. test $x,(reg/ref)
  5031. je @lbl1
  5032. ...
  5033. test $y,(reg/ref)
  5034. je/jne @lbl2
  5035. If (x or y) = x, then the second jump is deterministic
  5036. }
  5037. if (
  5038. (
  5039. (taicpu(p).oper[0]^.typ = top_const) or
  5040. (
  5041. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5042. (taicpu(p).oper[0]^.typ = top_reg) and
  5043. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5044. )
  5045. ) and
  5046. MatchInstruction(hp1, A_JCC, [])
  5047. ) then
  5048. begin
  5049. if (taicpu(p).oper[0]^.typ = top_reg) and
  5050. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5051. FirstValue := -1
  5052. else
  5053. FirstValue := taicpu(p).oper[0]^.val;
  5054. { If we have several test/jne's in a row, it might be the case that
  5055. the second label doesn't go to the same location, but the one
  5056. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5057. so accommodate for this with a while loop.
  5058. }
  5059. hp1_last := hp1;
  5060. while (
  5061. (
  5062. (taicpu(p).oper[1]^.typ = top_reg) and
  5063. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5064. ) or GetNextInstruction(hp1_last, p_dist)
  5065. ) and (p_dist.typ = ait_instruction) do
  5066. begin
  5067. if (
  5068. (
  5069. (taicpu(p_dist).opcode = A_TEST) and
  5070. (
  5071. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5072. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5073. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5074. )
  5075. ) or
  5076. (
  5077. { cmp 0,%reg = test %reg,%reg }
  5078. (taicpu(p_dist).opcode = A_CMP) and
  5079. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5080. )
  5081. ) and
  5082. { Make sure the destination operands are actually the same }
  5083. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5084. GetNextInstruction(p_dist, hp1_dist) and
  5085. MatchInstruction(hp1_dist, A_JCC, []) then
  5086. begin
  5087. if OptimizeJump(hp1_dist) then
  5088. begin
  5089. Result := True;
  5090. Exit;
  5091. end;
  5092. if
  5093. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5094. (
  5095. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5096. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5097. ) then
  5098. SecondValue := -1
  5099. else
  5100. SecondValue := taicpu(p_dist).oper[0]^.val;
  5101. { If both of the TEST constants are identical, delete the
  5102. second TEST that is unnecessary (be careful though, just
  5103. in case the flags are modified in between) }
  5104. if (FirstValue = SecondValue) then
  5105. begin
  5106. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5107. begin
  5108. { Since the second jump's condition is a subset of the first, we
  5109. know it will never branch because the first jump dominates it.
  5110. Get it out of the way now rather than wait for the jump
  5111. optimisations for a speed boost. }
  5112. if IsJumpToLabel(taicpu(hp1_dist)) then
  5113. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5114. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5115. RemoveInstruction(hp1_dist);
  5116. Result := True;
  5117. end
  5118. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5119. begin
  5120. { If the inverse of the first condition is a subset of the second,
  5121. the second one will definitely branch if the first one doesn't }
  5122. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5123. { We can remove the TEST instruction too }
  5124. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5125. RemoveInstruction(p_dist);
  5126. MakeUnconditional(taicpu(hp1_dist));
  5127. RemoveDeadCodeAfterJump(hp1_dist);
  5128. { Since the jump is now unconditional, we can't
  5129. continue any further with this particular
  5130. optimisation. The original TEST is still intact
  5131. though, so there might be something else we can
  5132. do }
  5133. Include(OptsToCheck, aoc_ForceNewIteration);
  5134. Break;
  5135. end;
  5136. if Result or
  5137. { If a jump wasn't removed or made unconditional, only
  5138. remove the identical TEST instruction if the flags
  5139. weren't modified }
  5140. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5141. begin
  5142. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5143. RemoveInstruction(p_dist);
  5144. { If the jump was removed or made unconditional, we
  5145. don't need to allocate NR_DEFAULTFLAGS over the
  5146. entire range }
  5147. if not Result then
  5148. begin
  5149. { Mark the flags as 'in use' over the entire range }
  5150. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5151. { Speed gain - continue search from the Jcc instruction }
  5152. hp1_last := hp1_dist;
  5153. { Only the TEST instruction was removed, and the
  5154. original was unchanged, so we can safely do
  5155. another iteration of the while loop }
  5156. Include(OptsToCheck, aoc_ForceNewIteration);
  5157. Continue;
  5158. end;
  5159. Exit;
  5160. end;
  5161. end;
  5162. hp1_last := nil;
  5163. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5164. (
  5165. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5166. { Always adjacent under -O2 and under }
  5167. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5168. (
  5169. GetNextInstruction(hp1, hp1_last) and
  5170. (hp1_last = p_dist)
  5171. )
  5172. ) and
  5173. (
  5174. (
  5175. { Test the following variant:
  5176. test $x,(reg/ref)
  5177. jne @lbl1
  5178. test $y,(reg/ref)
  5179. je @lbl2
  5180. @lbl1:
  5181. Becomes:
  5182. test $(x or y),(reg/ref)
  5183. je @lbl2
  5184. @lbl1: (may become a dead label)
  5185. }
  5186. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5187. GetNextInstruction(hp1_dist, hp1_last) and
  5188. (hp1_last = p_label)
  5189. ) or
  5190. (
  5191. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5192. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5193. then the second jump will never branch, so it can also be
  5194. removed regardless of where it goes }
  5195. (
  5196. (FirstValue = -1) or
  5197. (SecondValue = -1) or
  5198. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5199. )
  5200. )
  5201. ) then
  5202. begin
  5203. { Same jump location... can be a register since nothing's changed }
  5204. { If any of the entries are equivalent to test %reg,%reg, then the
  5205. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5206. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5207. if (hp1_last = p_label) then
  5208. begin
  5209. { Variant }
  5210. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5211. RemoveInstruction(p_dist);
  5212. if Assigned(JumpLabel) then
  5213. JumpLabel.decrefs;
  5214. RemoveInstruction(hp1);
  5215. end
  5216. else
  5217. begin
  5218. { Only remove the second test if no jumps or other conditional instructions follow }
  5219. TransferUsedRegs(TmpUsedRegs);
  5220. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5221. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5222. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5223. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5224. begin
  5225. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5226. RemoveInstruction(p_dist);
  5227. { Remove the first jump, not the second, to keep
  5228. any register deallocations between the second
  5229. TEST/JNE pair in the same place. Aids future
  5230. optimisation. }
  5231. if Assigned(JumpLabel) then
  5232. JumpLabel.decrefs;
  5233. RemoveInstruction(hp1);
  5234. end
  5235. else
  5236. begin
  5237. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5238. if IsJumpToLabel(taicpu(hp1_dist)) then
  5239. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5240. { Remove second jump in this instance }
  5241. RemoveInstruction(hp1_dist);
  5242. end;
  5243. end;
  5244. Result := True;
  5245. Exit;
  5246. end;
  5247. end;
  5248. if { If -O2 and under, it may stop on any old instruction }
  5249. (cs_opt_level3 in current_settings.optimizerswitches) and
  5250. (taicpu(p).oper[1]^.typ = top_reg) and
  5251. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5252. begin
  5253. hp1_last := p_dist;
  5254. Continue;
  5255. end;
  5256. Break;
  5257. end;
  5258. end;
  5259. { Search for:
  5260. test %reg,%reg
  5261. j(c1) @lbl1
  5262. ...
  5263. @lbl:
  5264. test %reg,%reg (same register)
  5265. j(c2) @lbl2
  5266. If c2 is a subset of c1, change to:
  5267. test %reg,%reg
  5268. j(c1) @lbl2
  5269. (@lbl1 may become a dead label as a result)
  5270. }
  5271. if (taicpu(p).oper[1]^.typ = top_reg) and
  5272. (taicpu(p).oper[0]^.typ = top_reg) and
  5273. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5274. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5275. Assigned(p_label) and
  5276. GetNextInstruction(p_label, p_dist) and
  5277. MatchInstruction(p_dist, A_TEST, []) and
  5278. { It's fine if the second test uses smaller sub-registers }
  5279. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5280. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5281. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5282. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5283. GetNextInstruction(p_dist, hp1_dist) and
  5284. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5285. begin
  5286. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5287. if JumpLabel = JumpLabel_dist then
  5288. { This is an infinite loop }
  5289. Exit;
  5290. { Best optimisation when the first condition is a subset (or equal) of the second }
  5291. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5292. begin
  5293. { Any registers used here will already be allocated }
  5294. if Assigned(JumpLabel) then
  5295. JumpLabel.DecRefs;
  5296. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5297. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5298. Result := True;
  5299. Exit;
  5300. end;
  5301. end;
  5302. end;
  5303. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5304. var
  5305. hp1, hp2: tai;
  5306. ActiveReg: TRegister;
  5307. OldOffset: asizeint;
  5308. ThisConst: TCGInt;
  5309. function RegDeallocated: Boolean;
  5310. begin
  5311. TransferUsedRegs(TmpUsedRegs);
  5312. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5313. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5314. end;
  5315. begin
  5316. result:=false;
  5317. hp1 := nil;
  5318. { replace
  5319. addX const,%reg1
  5320. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5321. dealloc %reg1
  5322. by
  5323. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5324. }
  5325. if MatchOpType(taicpu(p),top_const,top_reg) then
  5326. begin
  5327. ActiveReg := taicpu(p).oper[1]^.reg;
  5328. { Ensures the entire register was updated }
  5329. if (taicpu(p).opsize >= S_L) and
  5330. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5331. MatchInstruction(hp1,A_LEA,[]) and
  5332. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5333. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5334. (
  5335. { Cover the case where the register in the reference is also the destination register }
  5336. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5337. (
  5338. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5339. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5340. RegDeallocated
  5341. )
  5342. ) then
  5343. begin
  5344. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5345. {$push}
  5346. {$R-}{$Q-}
  5347. { Explicitly disable overflow checking for these offset calculation
  5348. as those do not matter for the final result }
  5349. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5350. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5351. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5352. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5353. {$pop}
  5354. {$ifdef x86_64}
  5355. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5356. begin
  5357. { Overflow; abort }
  5358. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5359. end
  5360. else
  5361. {$endif x86_64}
  5362. begin
  5363. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5364. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5365. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5366. RemoveCurrentP(p, hp1)
  5367. else
  5368. RemoveCurrentP(p);
  5369. result:=true;
  5370. Exit;
  5371. end;
  5372. end;
  5373. if (
  5374. { Save calling GetNextInstructionUsingReg again }
  5375. Assigned(hp1) or
  5376. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5377. ) and
  5378. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5379. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5380. begin
  5381. if taicpu(hp1).oper[0]^.typ = top_const then
  5382. begin
  5383. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5384. if taicpu(hp1).opcode = A_ADD then
  5385. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5386. else
  5387. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5388. Result := True;
  5389. { Handle any overflows }
  5390. case taicpu(p).opsize of
  5391. S_B:
  5392. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5393. S_W:
  5394. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5395. S_L:
  5396. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5397. {$ifdef x86_64}
  5398. S_Q:
  5399. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5400. { Overflow; abort }
  5401. Result := False
  5402. else
  5403. taicpu(p).oper[0]^.val := ThisConst;
  5404. {$endif x86_64}
  5405. else
  5406. InternalError(2021102610);
  5407. end;
  5408. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5409. if Result then
  5410. begin
  5411. if (taicpu(p).oper[0]^.val < 0) and
  5412. (
  5413. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5414. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5415. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5416. ) then
  5417. begin
  5418. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5419. taicpu(p).opcode := A_SUB;
  5420. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5421. end
  5422. else
  5423. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5424. RemoveInstruction(hp1);
  5425. end;
  5426. end
  5427. else
  5428. begin
  5429. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5430. TransferUsedRegs(TmpUsedRegs);
  5431. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5432. hp2 := p;
  5433. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5434. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5435. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5436. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5437. begin
  5438. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5439. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5440. Asml.Remove(p);
  5441. Asml.InsertAfter(p, hp1);
  5442. p := hp1;
  5443. Result := True;
  5444. Exit;
  5445. end;
  5446. end;
  5447. end;
  5448. if DoArithCombineOpt(p) then
  5449. Result:=true;
  5450. end;
  5451. end;
  5452. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5453. var
  5454. hp1, hp2: tai;
  5455. ref: Integer;
  5456. saveref: treference;
  5457. offsetcalc: Int64;
  5458. TempReg: TRegister;
  5459. Multiple: TCGInt;
  5460. Adjacent, IntermediateRegDiscarded: Boolean;
  5461. begin
  5462. Result:=false;
  5463. { play save and throw an error if LEA uses a seg register prefix,
  5464. this is most likely an error somewhere else }
  5465. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5466. internalerror(2022022001);
  5467. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5468. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5469. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5470. (
  5471. { do not mess with leas accessing the stack pointer
  5472. unless it's a null operation }
  5473. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5474. (
  5475. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5476. (taicpu(p).oper[0]^.ref^.offset = 0)
  5477. )
  5478. ) and
  5479. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5480. begin
  5481. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5482. begin
  5483. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5484. begin
  5485. taicpu(p).opcode := A_MOV;
  5486. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5487. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5488. end
  5489. else
  5490. begin
  5491. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5492. RemoveCurrentP(p);
  5493. end;
  5494. Result:=true;
  5495. exit;
  5496. end
  5497. else if (
  5498. { continue to use lea to adjust the stack pointer,
  5499. it is the recommended way, but only if not optimizing for size }
  5500. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5501. (cs_opt_size in current_settings.optimizerswitches)
  5502. ) and
  5503. { If the flags register is in use, don't change the instruction
  5504. to an ADD otherwise this will scramble the flags. [Kit] }
  5505. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5506. ConvertLEA(taicpu(p)) then
  5507. begin
  5508. Result:=true;
  5509. exit;
  5510. end;
  5511. end;
  5512. { Don't optimise if the stack or frame pointer is the destination register }
  5513. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5514. Exit;
  5515. if GetNextInstruction(p,hp1) and
  5516. (hp1.typ=ait_instruction) then
  5517. begin
  5518. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5519. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5520. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5521. begin
  5522. TransferUsedRegs(TmpUsedRegs);
  5523. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5524. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5525. begin
  5526. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5527. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5528. RemoveInstruction(hp1);
  5529. result:=true;
  5530. exit;
  5531. end;
  5532. end;
  5533. { changes
  5534. lea <ref1>, reg1
  5535. <op> ...,<ref. with reg1>,...
  5536. to
  5537. <op> ...,<ref1>,... }
  5538. { find a reference which uses reg1 }
  5539. 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
  5540. ref:=0
  5541. 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
  5542. ref:=1
  5543. else
  5544. ref:=-1;
  5545. if (ref<>-1) and
  5546. { reg1 must be either the base or the index }
  5547. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5548. begin
  5549. { reg1 can be removed from the reference }
  5550. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5551. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5552. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5553. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5554. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5555. else
  5556. Internalerror(2019111201);
  5557. { check if the can insert all data of the lea into the second instruction }
  5558. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5559. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5560. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5561. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5562. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5563. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5564. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5565. {$ifdef x86_64}
  5566. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5567. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5568. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5569. )
  5570. {$endif x86_64}
  5571. then
  5572. begin
  5573. { reg1 might not used by the second instruction after it is remove from the reference }
  5574. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5575. begin
  5576. TransferUsedRegs(TmpUsedRegs);
  5577. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5578. { reg1 is not updated so it might not be used afterwards }
  5579. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5580. begin
  5581. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5582. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5583. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5584. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5585. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5586. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5587. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5588. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5589. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5590. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5591. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5592. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5593. RemoveCurrentP(p, hp1);
  5594. result:=true;
  5595. exit;
  5596. end
  5597. end;
  5598. end;
  5599. { recover }
  5600. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5601. end;
  5602. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5603. if Adjacent or
  5604. { Check further ahead (up to 2 instructions ahead for -O2) }
  5605. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5606. begin
  5607. { Check common LEA/LEA conditions }
  5608. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5609. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5610. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5611. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5612. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5613. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5614. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5615. (
  5616. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5617. calling it (since it calls GetNextInstruction) }
  5618. Adjacent or
  5619. (
  5620. (
  5621. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5622. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5623. ) and (
  5624. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5625. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5626. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5627. )
  5628. )
  5629. ) then
  5630. begin
  5631. TransferUsedRegs(TmpUsedRegs);
  5632. hp2 := p;
  5633. repeat
  5634. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5635. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5636. IntermediateRegDiscarded :=
  5637. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5638. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5639. { changes
  5640. lea offset1(regX,scale), reg1
  5641. lea offset2(reg1,reg1), reg2
  5642. to
  5643. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5644. and
  5645. lea offset1(regX,scale1), reg1
  5646. lea offset2(reg1,scale2), reg2
  5647. to
  5648. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5649. and
  5650. lea offset1(regX,scale1), reg1
  5651. lea offset2(reg3,reg1,scale2), reg2
  5652. to
  5653. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5654. ... so long as the final scale does not exceed 8
  5655. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5656. }
  5657. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5658. (
  5659. { Don't optimise if size is a concern and the intermediate register remains in use }
  5660. IntermediateRegDiscarded or
  5661. not (cs_opt_size in current_settings.optimizerswitches)
  5662. ) and
  5663. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5664. (
  5665. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5666. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5667. ) and (
  5668. (
  5669. { lea (reg1,scale2), reg2 variant }
  5670. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5671. (
  5672. Adjacent or
  5673. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5674. ) and
  5675. (
  5676. (
  5677. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5678. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5679. ) or (
  5680. { lea (regX,regX), reg1 variant }
  5681. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5682. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5683. )
  5684. )
  5685. ) or (
  5686. { lea (reg1,reg1), reg1 variant }
  5687. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5688. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5689. )
  5690. ) then
  5691. begin
  5692. { Make everything homogeneous to make calculations easier }
  5693. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5694. begin
  5695. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5696. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5697. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5698. else
  5699. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5700. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5701. end;
  5702. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5703. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5704. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5705. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5706. begin
  5707. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5708. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5709. begin
  5710. { Put the register to change in the index register }
  5711. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5712. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5713. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5714. end;
  5715. { Change lea (reg,reg) to lea(,reg,2) }
  5716. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5717. begin
  5718. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5719. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5720. end;
  5721. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5722. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5723. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5724. { Just to prevent miscalculations }
  5725. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5726. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5727. else
  5728. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5729. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5730. if IntermediateRegDiscarded then
  5731. begin
  5732. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5733. RemoveCurrentP(p);
  5734. end
  5735. else
  5736. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5737. result:=true;
  5738. exit;
  5739. end;
  5740. end;
  5741. { changes
  5742. lea offset1(regX), reg1
  5743. lea offset2(reg1), reg2
  5744. to
  5745. lea offset1+offset2(regX), reg2 }
  5746. if (
  5747. { Don't optimise if size is a concern and the intermediate register remains in use }
  5748. IntermediateRegDiscarded or
  5749. not (cs_opt_size in current_settings.optimizerswitches)
  5750. ) and
  5751. (
  5752. (
  5753. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5754. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5755. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5756. ) or (
  5757. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5758. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5759. (
  5760. (
  5761. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5762. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5763. ) or (
  5764. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5765. (
  5766. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5767. (
  5768. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5769. (
  5770. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5771. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5772. )
  5773. )
  5774. )
  5775. )
  5776. )
  5777. )
  5778. ) then
  5779. begin
  5780. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5781. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5782. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5783. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5784. begin
  5785. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5786. begin
  5787. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5788. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5789. { if the register is used as index and base, we have to increase for base as well
  5790. and adapt base }
  5791. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5792. begin
  5793. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5794. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5795. end;
  5796. end
  5797. else
  5798. begin
  5799. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5800. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5801. end;
  5802. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5803. begin
  5804. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5805. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5806. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  5807. { Catch the situation where the base = index
  5808. and treat this as *2. The scalefactor of
  5809. p will be 0 or 1 due to the conditional
  5810. checks above. Fixes i40647 }
  5811. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  5812. else
  5813. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  5814. end;
  5815. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5816. if IntermediateRegDiscarded then
  5817. begin
  5818. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5819. RemoveCurrentP(p);
  5820. end
  5821. else
  5822. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5823. result:=true;
  5824. exit;
  5825. end;
  5826. end;
  5827. end;
  5828. { Change:
  5829. leal/q $x(%reg1),%reg2
  5830. ...
  5831. shll/q $y,%reg2
  5832. To:
  5833. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5834. }
  5835. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5836. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5837. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5838. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5839. (taicpu(hp1).oper[0]^.val <= 3) then
  5840. begin
  5841. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5842. TransferUsedRegs(TmpUsedRegs);
  5843. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5844. if
  5845. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5846. (this works even if scalefactor is zero) }
  5847. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5848. { Ensure offset doesn't go out of bounds }
  5849. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5850. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5851. (
  5852. (
  5853. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5854. (
  5855. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5856. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5857. (
  5858. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5859. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5860. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5861. )
  5862. )
  5863. ) or (
  5864. (
  5865. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5866. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5867. ) and
  5868. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5869. )
  5870. ) then
  5871. begin
  5872. repeat
  5873. with taicpu(p).oper[0]^.ref^ do
  5874. begin
  5875. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5876. if index = base then
  5877. begin
  5878. if Multiple > 4 then
  5879. { Optimisation will no longer work because resultant
  5880. scale factor will exceed 8 }
  5881. Break;
  5882. base := NR_NO;
  5883. scalefactor := 2;
  5884. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5885. end
  5886. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5887. begin
  5888. { Scale factor only works on the index register }
  5889. index := base;
  5890. base := NR_NO;
  5891. end;
  5892. { For safety }
  5893. if scalefactor <= 1 then
  5894. begin
  5895. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5896. scalefactor := Multiple;
  5897. end
  5898. else
  5899. begin
  5900. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5901. scalefactor := scalefactor * Multiple;
  5902. end;
  5903. offset := offset * Multiple;
  5904. end;
  5905. RemoveInstruction(hp1);
  5906. Result := True;
  5907. Exit;
  5908. { This repeat..until loop exists for the benefit of Break }
  5909. until True;
  5910. end;
  5911. end;
  5912. end;
  5913. end;
  5914. end;
  5915. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5916. var
  5917. hp1 : tai;
  5918. SubInstr: Boolean;
  5919. ThisConst: TCGInt;
  5920. const
  5921. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5922. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5923. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5924. begin
  5925. Result := False;
  5926. if taicpu(p).oper[0]^.typ <> top_const then
  5927. { Should have been confirmed before calling }
  5928. InternalError(2021102601);
  5929. SubInstr := (taicpu(p).opcode = A_SUB);
  5930. if GetLastInstruction(p, hp1) and
  5931. (hp1.typ = ait_instruction) and
  5932. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5933. begin
  5934. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5935. { Bad size }
  5936. InternalError(2022042001);
  5937. case taicpu(hp1).opcode Of
  5938. A_INC:
  5939. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5940. begin
  5941. if SubInstr then
  5942. ThisConst := taicpu(p).oper[0]^.val - 1
  5943. else
  5944. ThisConst := taicpu(p).oper[0]^.val + 1;
  5945. end
  5946. else
  5947. Exit;
  5948. A_DEC:
  5949. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5950. begin
  5951. if SubInstr then
  5952. ThisConst := taicpu(p).oper[0]^.val + 1
  5953. else
  5954. ThisConst := taicpu(p).oper[0]^.val - 1;
  5955. end
  5956. else
  5957. Exit;
  5958. A_SUB:
  5959. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5960. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5961. begin
  5962. if SubInstr then
  5963. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5964. else
  5965. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5966. end
  5967. else
  5968. Exit;
  5969. A_ADD:
  5970. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5971. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5972. begin
  5973. if SubInstr then
  5974. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5975. else
  5976. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5977. end
  5978. else
  5979. Exit;
  5980. else
  5981. Exit;
  5982. end;
  5983. { Check that the values are in range }
  5984. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5985. { Overflow; abort }
  5986. Exit;
  5987. if (ThisConst = 0) then
  5988. begin
  5989. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5990. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5991. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5992. RemoveInstruction(hp1);
  5993. hp1 := tai(p.next);
  5994. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5995. if not GetLastInstruction(hp1, p) then
  5996. p := hp1;
  5997. end
  5998. else
  5999. begin
  6000. if taicpu(hp1).opercnt=1 then
  6001. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6002. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6003. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6004. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6005. else
  6006. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6007. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6008. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6009. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6010. RemoveInstruction(hp1);
  6011. taicpu(p).loadconst(0, ThisConst);
  6012. end;
  6013. Result := True;
  6014. end;
  6015. end;
  6016. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6017. begin
  6018. Result := False;
  6019. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6020. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6021. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6022. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6023. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6024. (
  6025. (
  6026. (taicpu(hp1).opcode = A_TEST)
  6027. ) or (
  6028. (taicpu(hp1).opcode = A_CMP) and
  6029. { A sanity check more than anything }
  6030. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6031. )
  6032. ) then
  6033. begin
  6034. { change
  6035. mov mem, %reg
  6036. ...
  6037. cmp/test x, %reg / test %reg,%reg
  6038. (reg deallocated)
  6039. to
  6040. cmp/test x, mem / cmp 0, mem
  6041. }
  6042. TransferUsedRegs(TmpUsedRegs);
  6043. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6044. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6045. begin
  6046. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6047. if (taicpu(hp1).opcode = A_TEST) and
  6048. (
  6049. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6050. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6051. ) then
  6052. begin
  6053. taicpu(hp1).opcode := A_CMP;
  6054. taicpu(hp1).loadconst(0, 0);
  6055. end;
  6056. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6057. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6058. RemoveCurrentP(p);
  6059. if (p <> hp1) then
  6060. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6061. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6062. { Make sure the flags are allocated across the CMP instruction }
  6063. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6064. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6065. Result := True;
  6066. Exit;
  6067. end;
  6068. end;
  6069. end;
  6070. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6071. var
  6072. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6073. ThisReg, SecondReg: TRegister;
  6074. JumpLoc: TAsmLabel;
  6075. NewSize: TOpSize;
  6076. begin
  6077. Result := False;
  6078. {
  6079. Convert:
  6080. j<c> .L1
  6081. .L2:
  6082. mov 1,reg
  6083. jmp .L3 (or ret, although it might not be a RET yet)
  6084. .L1:
  6085. mov 0,reg
  6086. jmp .L3 (or ret)
  6087. ( As long as .L3 <> .L1 or .L2)
  6088. To:
  6089. mov 0,reg
  6090. set<not(c)> reg
  6091. jmp .L3 (or ret)
  6092. .L2:
  6093. mov 1,reg
  6094. jmp .L3 (or ret)
  6095. .L1:
  6096. mov 0,reg
  6097. jmp .L3 (or ret)
  6098. }
  6099. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6100. Exit;
  6101. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6102. if GetNextInstruction(hp_label, hp2) and
  6103. MatchInstruction(hp2,A_MOV,[]) and
  6104. (taicpu(hp2).oper[0]^.typ = top_const) and
  6105. (
  6106. (
  6107. (taicpu(hp2).oper[1]^.typ = top_reg)
  6108. {$ifdef i386}
  6109. { Under i386, ESI, EDI, EBP and ESP
  6110. don't have an 8-bit representation }
  6111. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6112. {$endif i386}
  6113. ) or (
  6114. {$ifdef i386}
  6115. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6116. {$endif i386}
  6117. (taicpu(hp2).opsize = S_B)
  6118. )
  6119. ) and
  6120. GetNextInstruction(hp2, hp3) and
  6121. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6122. (
  6123. (taicpu(hp3).opcode=A_RET) or
  6124. (
  6125. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6126. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6127. )
  6128. ) and
  6129. GetNextInstruction(hp3, hp4) and
  6130. (hp4.typ=ait_label) and
  6131. (tai_label(hp4).labsym=JumpLoc) and
  6132. (
  6133. not (cs_opt_size in current_settings.optimizerswitches) or
  6134. { If the initial jump is the label's only reference, then it will
  6135. become a dead label if the other conditions are met and hence
  6136. remove at least 2 instructions, including a jump }
  6137. (JumpLoc.getrefs = 1)
  6138. ) and
  6139. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6140. that will be optimised out }
  6141. GetNextInstruction(hp4, hp5) and
  6142. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6143. (taicpu(hp5).oper[0]^.typ = top_const) and
  6144. (
  6145. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6146. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6147. ) and
  6148. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6149. GetNextInstruction(hp5,hp6) and
  6150. (
  6151. (hp6.typ<>ait_label) or
  6152. SkipLabels(hp6, hp6)
  6153. ) and
  6154. (hp6.typ=ait_instruction) then
  6155. begin
  6156. { First, let's look at the two jumps that are hp3 and hp6 }
  6157. if not
  6158. (
  6159. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6160. (
  6161. (taicpu(hp6).opcode=A_RET) or
  6162. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6163. )
  6164. ) then
  6165. { If condition is False, then the JMP/RET instructions matched conventionally }
  6166. begin
  6167. { See if one of the jumps can be instantly converted into a RET }
  6168. if (taicpu(hp3).opcode=A_JMP) then
  6169. begin
  6170. { Reuse hp5 }
  6171. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6172. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  6173. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  6174. Exit;
  6175. if MatchInstruction(hp5, A_RET, []) then
  6176. begin
  6177. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6178. ConvertJumpToRET(hp3, hp5);
  6179. Result := True;
  6180. end
  6181. else
  6182. Exit;
  6183. end;
  6184. if (taicpu(hp6).opcode=A_JMP) then
  6185. begin
  6186. { Reuse hp5 }
  6187. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6188. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6189. Exit;
  6190. if MatchInstruction(hp5, A_RET, []) then
  6191. begin
  6192. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6193. ConvertJumpToRET(hp6, hp5);
  6194. Result := True;
  6195. end
  6196. else
  6197. Exit;
  6198. end;
  6199. if not
  6200. (
  6201. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6202. (
  6203. (taicpu(hp6).opcode=A_RET) or
  6204. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6205. )
  6206. ) then
  6207. { Still doesn't match }
  6208. Exit;
  6209. end;
  6210. if (taicpu(hp2).oper[0]^.val = 1) then
  6211. begin
  6212. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6213. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6214. end
  6215. else
  6216. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6217. if taicpu(hp2).opsize=S_B then
  6218. begin
  6219. if taicpu(hp2).oper[1]^.typ = top_reg then
  6220. begin
  6221. SecondReg := taicpu(hp2).oper[1]^.reg;
  6222. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6223. end
  6224. else
  6225. begin
  6226. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6227. SecondReg := NR_NO;
  6228. end;
  6229. hp_pos := p;
  6230. hp_allocstart := hp4;
  6231. end
  6232. else
  6233. begin
  6234. { Will be a register because the size can't be S_B otherwise }
  6235. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6236. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6237. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6238. if (cs_opt_size in current_settings.optimizerswitches) then
  6239. begin
  6240. { Favour using MOVZX when optimising for size }
  6241. case taicpu(hp2).opsize of
  6242. S_W:
  6243. NewSize := S_BW;
  6244. S_L:
  6245. NewSize := S_BL;
  6246. {$ifdef x86_64}
  6247. S_Q:
  6248. begin
  6249. NewSize := S_BL;
  6250. { Will implicitly zero-extend to 64-bit }
  6251. setsubreg(SecondReg, R_SUBD);
  6252. end;
  6253. {$endif x86_64}
  6254. else
  6255. InternalError(2022101301);
  6256. end;
  6257. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6258. { Inserting it right before p will guarantee that the flags are also tracked }
  6259. Asml.InsertBefore(hp5, p);
  6260. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6261. hp_pos := hp5;
  6262. hp_allocstart := hp4;
  6263. end
  6264. else
  6265. begin
  6266. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6267. { Inserting it right before p will guarantee that the flags are also tracked }
  6268. Asml.InsertBefore(hp5, p);
  6269. hp_pos := p;
  6270. hp_allocstart := hp5;
  6271. end;
  6272. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6273. end;
  6274. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6275. taicpu(hp4).condition := taicpu(p).condition;
  6276. asml.InsertBefore(hp4, hp_pos);
  6277. if taicpu(hp3).is_jmp then
  6278. begin
  6279. JumpLoc.decrefs;
  6280. MakeUnconditional(taicpu(p));
  6281. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6282. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6283. end
  6284. else
  6285. ConvertJumpToRET(p, hp3);
  6286. if SecondReg <> NR_NO then
  6287. { Ensure the destination register is allocated over this region }
  6288. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6289. if (JumpLoc.getrefs = 0) then
  6290. RemoveDeadCodeAfterJump(hp3);
  6291. Result:=true;
  6292. exit;
  6293. end;
  6294. end;
  6295. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6296. var
  6297. hp1, hp2: tai;
  6298. ActiveReg: TRegister;
  6299. OldOffset: asizeint;
  6300. ThisConst: TCGInt;
  6301. function RegDeallocated: Boolean;
  6302. begin
  6303. TransferUsedRegs(TmpUsedRegs);
  6304. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6305. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6306. end;
  6307. begin
  6308. Result:=false;
  6309. hp1 := nil;
  6310. { replace
  6311. subX const,%reg1
  6312. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6313. dealloc %reg1
  6314. by
  6315. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6316. }
  6317. if MatchOpType(taicpu(p),top_const,top_reg) then
  6318. begin
  6319. ActiveReg := taicpu(p).oper[1]^.reg;
  6320. { Ensures the entire register was updated }
  6321. if (taicpu(p).opsize >= S_L) and
  6322. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6323. MatchInstruction(hp1,A_LEA,[]) and
  6324. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6325. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6326. (
  6327. { Cover the case where the register in the reference is also the destination register }
  6328. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6329. (
  6330. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6331. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6332. RegDeallocated
  6333. )
  6334. ) then
  6335. begin
  6336. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6337. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6338. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6339. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6340. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6341. {$ifdef x86_64}
  6342. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6343. begin
  6344. { Overflow; abort }
  6345. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6346. end
  6347. else
  6348. {$endif x86_64}
  6349. begin
  6350. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6351. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6352. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6353. RemoveCurrentP(p, hp1)
  6354. else
  6355. RemoveCurrentP(p);
  6356. result:=true;
  6357. Exit;
  6358. end;
  6359. end;
  6360. if (
  6361. { Save calling GetNextInstructionUsingReg again }
  6362. Assigned(hp1) or
  6363. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6364. ) and
  6365. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6366. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6367. begin
  6368. if taicpu(hp1).oper[0]^.typ = top_const then
  6369. begin
  6370. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6371. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6372. Result := True;
  6373. { Handle any overflows }
  6374. case taicpu(p).opsize of
  6375. S_B:
  6376. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6377. S_W:
  6378. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6379. S_L:
  6380. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6381. {$ifdef x86_64}
  6382. S_Q:
  6383. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6384. { Overflow; abort }
  6385. Result := False
  6386. else
  6387. taicpu(p).oper[0]^.val := ThisConst;
  6388. {$endif x86_64}
  6389. else
  6390. InternalError(2021102611);
  6391. end;
  6392. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6393. if Result then
  6394. begin
  6395. if (taicpu(p).oper[0]^.val < 0) and
  6396. (
  6397. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6398. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6399. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6400. ) then
  6401. begin
  6402. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6403. taicpu(p).opcode := A_SUB;
  6404. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6405. end
  6406. else
  6407. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6408. RemoveInstruction(hp1);
  6409. end;
  6410. end
  6411. else
  6412. begin
  6413. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6414. TransferUsedRegs(TmpUsedRegs);
  6415. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6416. hp2 := p;
  6417. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6418. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6419. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6420. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6421. begin
  6422. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6423. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6424. Asml.Remove(p);
  6425. Asml.InsertAfter(p, hp1);
  6426. p := hp1;
  6427. Result := True;
  6428. Exit;
  6429. end;
  6430. end;
  6431. end;
  6432. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6433. { * change "sub/add const1, reg" or "dec reg" followed by
  6434. "sub const2, reg" to one "sub ..., reg" }
  6435. {$ifdef i386}
  6436. if (taicpu(p).oper[0]^.val = 2) and
  6437. (ActiveReg = NR_ESP) and
  6438. { Don't do the sub/push optimization if the sub }
  6439. { comes from setting up the stack frame (JM) }
  6440. (not(GetLastInstruction(p,hp1)) or
  6441. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6442. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6443. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6444. begin
  6445. hp1 := tai(p.next);
  6446. while Assigned(hp1) and
  6447. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6448. not RegReadByInstruction(NR_ESP,hp1) and
  6449. not RegModifiedByInstruction(NR_ESP,hp1) do
  6450. hp1 := tai(hp1.next);
  6451. if Assigned(hp1) and
  6452. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6453. begin
  6454. taicpu(hp1).changeopsize(S_L);
  6455. if taicpu(hp1).oper[0]^.typ=top_reg then
  6456. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6457. hp1 := tai(p.next);
  6458. RemoveCurrentp(p, hp1);
  6459. Result:=true;
  6460. exit;
  6461. end;
  6462. end;
  6463. {$endif i386}
  6464. if DoArithCombineOpt(p) then
  6465. Result:=true;
  6466. end;
  6467. end;
  6468. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6469. var
  6470. TmpBool1,TmpBool2 : Boolean;
  6471. tmpref : treference;
  6472. hp1,hp2: tai;
  6473. mask, shiftval: tcgint;
  6474. begin
  6475. Result:=false;
  6476. { All these optimisations work on "shl/sal const,%reg" }
  6477. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6478. Exit;
  6479. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6480. (taicpu(p).oper[0]^.val <= 3) then
  6481. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6482. begin
  6483. { should we check the next instruction? }
  6484. TmpBool1 := True;
  6485. { have we found an add/sub which could be
  6486. integrated in the lea? }
  6487. TmpBool2 := False;
  6488. reference_reset(tmpref,2,[]);
  6489. TmpRef.index := taicpu(p).oper[1]^.reg;
  6490. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6491. while TmpBool1 and
  6492. GetNextInstruction(p, hp1) and
  6493. (tai(hp1).typ = ait_instruction) and
  6494. ((((taicpu(hp1).opcode = A_ADD) or
  6495. (taicpu(hp1).opcode = A_SUB)) and
  6496. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6497. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6498. (((taicpu(hp1).opcode = A_INC) or
  6499. (taicpu(hp1).opcode = A_DEC)) and
  6500. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6501. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6502. ((taicpu(hp1).opcode = A_LEA) and
  6503. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6504. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6505. (not GetNextInstruction(hp1,hp2) or
  6506. not instrReadsFlags(hp2)) Do
  6507. begin
  6508. TmpBool1 := False;
  6509. if taicpu(hp1).opcode=A_LEA then
  6510. begin
  6511. if (TmpRef.base = NR_NO) and
  6512. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6513. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6514. { Segment register isn't a concern here }
  6515. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6516. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6517. begin
  6518. TmpBool1 := True;
  6519. TmpBool2 := True;
  6520. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6521. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6522. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6523. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6524. RemoveInstruction(hp1);
  6525. end
  6526. end
  6527. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6528. begin
  6529. TmpBool1 := True;
  6530. TmpBool2 := True;
  6531. case taicpu(hp1).opcode of
  6532. A_ADD:
  6533. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6534. A_SUB:
  6535. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6536. else
  6537. internalerror(2019050536);
  6538. end;
  6539. RemoveInstruction(hp1);
  6540. end
  6541. else
  6542. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6543. (((taicpu(hp1).opcode = A_ADD) and
  6544. (TmpRef.base = NR_NO)) or
  6545. (taicpu(hp1).opcode = A_INC) or
  6546. (taicpu(hp1).opcode = A_DEC)) then
  6547. begin
  6548. TmpBool1 := True;
  6549. TmpBool2 := True;
  6550. case taicpu(hp1).opcode of
  6551. A_ADD:
  6552. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6553. A_INC:
  6554. inc(TmpRef.offset);
  6555. A_DEC:
  6556. dec(TmpRef.offset);
  6557. else
  6558. internalerror(2019050535);
  6559. end;
  6560. RemoveInstruction(hp1);
  6561. end;
  6562. end;
  6563. if TmpBool2
  6564. {$ifndef x86_64}
  6565. or
  6566. ((current_settings.optimizecputype < cpu_Pentium2) and
  6567. (taicpu(p).oper[0]^.val <= 3) and
  6568. not(cs_opt_size in current_settings.optimizerswitches))
  6569. {$endif x86_64}
  6570. then
  6571. begin
  6572. if not(TmpBool2) and
  6573. (taicpu(p).oper[0]^.val=1) then
  6574. begin
  6575. taicpu(p).opcode := A_ADD;
  6576. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6577. end
  6578. else
  6579. begin
  6580. taicpu(p).opcode := A_LEA;
  6581. taicpu(p).loadref(0, TmpRef);
  6582. end;
  6583. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6584. Result := True;
  6585. end;
  6586. end
  6587. {$ifndef x86_64}
  6588. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6589. begin
  6590. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6591. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6592. (unlike shl, which is only Tairable in the U pipe) }
  6593. if taicpu(p).oper[0]^.val=1 then
  6594. begin
  6595. taicpu(p).opcode := A_ADD;
  6596. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6597. Result := True;
  6598. end
  6599. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6600. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6601. else if (taicpu(p).opsize = S_L) and
  6602. (taicpu(p).oper[0]^.val<= 3) then
  6603. begin
  6604. reference_reset(tmpref,2,[]);
  6605. TmpRef.index := taicpu(p).oper[1]^.reg;
  6606. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6607. taicpu(p).opcode := A_LEA;
  6608. taicpu(p).loadref(0, TmpRef);
  6609. Result := True;
  6610. end;
  6611. end
  6612. {$endif x86_64}
  6613. else if
  6614. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6615. (
  6616. (
  6617. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6618. SetAndTest(hp1, hp2)
  6619. {$ifdef x86_64}
  6620. ) or
  6621. (
  6622. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6623. GetNextInstruction(hp1, hp2) and
  6624. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6625. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6626. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6627. {$endif x86_64}
  6628. )
  6629. ) and
  6630. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6631. begin
  6632. { Change:
  6633. shl x, %reg1
  6634. mov -(1<<x), %reg2
  6635. and %reg2, %reg1
  6636. Or:
  6637. shl x, %reg1
  6638. and -(1<<x), %reg1
  6639. To just:
  6640. shl x, %reg1
  6641. Since the and operation only zeroes bits that are already zero from the shl operation
  6642. }
  6643. case taicpu(p).oper[0]^.val of
  6644. 8:
  6645. mask:=$FFFFFFFFFFFFFF00;
  6646. 16:
  6647. mask:=$FFFFFFFFFFFF0000;
  6648. 32:
  6649. mask:=$FFFFFFFF00000000;
  6650. 63:
  6651. { Constant pre-calculated to prevent overflow errors with Int64 }
  6652. mask:=$8000000000000000;
  6653. else
  6654. begin
  6655. if taicpu(p).oper[0]^.val >= 64 then
  6656. { Shouldn't happen realistically, since the register
  6657. is guaranteed to be set to zero at this point }
  6658. mask := 0
  6659. else
  6660. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6661. end;
  6662. end;
  6663. if taicpu(hp1).oper[0]^.val = mask then
  6664. begin
  6665. { Everything checks out, perform the optimisation, as long as
  6666. the FLAGS register isn't being used}
  6667. TransferUsedRegs(TmpUsedRegs);
  6668. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6669. {$ifdef x86_64}
  6670. if (hp1 <> hp2) then
  6671. begin
  6672. { "shl/mov/and" version }
  6673. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6674. { Don't do the optimisation if the FLAGS register is in use }
  6675. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6676. begin
  6677. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6678. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6679. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6680. begin
  6681. RemoveInstruction(hp1);
  6682. Result := True;
  6683. end;
  6684. { Only set Result to True if the 'mov' instruction was removed }
  6685. RemoveInstruction(hp2);
  6686. end;
  6687. end
  6688. else
  6689. {$endif x86_64}
  6690. begin
  6691. { "shl/and" version }
  6692. { Don't do the optimisation if the FLAGS register is in use }
  6693. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6694. begin
  6695. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6696. RemoveInstruction(hp1);
  6697. Result := True;
  6698. end;
  6699. end;
  6700. Exit;
  6701. end
  6702. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6703. begin
  6704. { Even if the mask doesn't allow for its removal, we might be
  6705. able to optimise the mask for the "shl/and" version, which
  6706. may permit other peephole optimisations }
  6707. {$ifdef DEBUG_AOPTCPU}
  6708. mask := taicpu(hp1).oper[0]^.val and mask;
  6709. if taicpu(hp1).oper[0]^.val <> mask then
  6710. begin
  6711. DebugMsg(
  6712. SPeepholeOptimization +
  6713. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6714. ' to $' + debug_tostr(mask) +
  6715. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6716. taicpu(hp1).oper[0]^.val := mask;
  6717. end;
  6718. {$else DEBUG_AOPTCPU}
  6719. { If debugging is off, just set the operand even if it's the same }
  6720. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6721. {$endif DEBUG_AOPTCPU}
  6722. end;
  6723. end;
  6724. {
  6725. change
  6726. shl/sal const,reg
  6727. <op> ...(...,reg,1),...
  6728. into
  6729. <op> ...(...,reg,1 shl const),...
  6730. if const in 1..3
  6731. }
  6732. if MatchOpType(taicpu(p), top_const, top_reg) and
  6733. (taicpu(p).oper[0]^.val in [1..3]) and
  6734. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6735. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6736. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6737. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6738. MatchOpType(taicpu(hp1),top_ref))
  6739. ) and
  6740. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6741. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6742. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6743. begin
  6744. TransferUsedRegs(TmpUsedRegs);
  6745. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6746. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6747. begin
  6748. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6749. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6750. RemoveCurrentP(p);
  6751. Result:=true;
  6752. exit;
  6753. end;
  6754. end;
  6755. if MatchOpType(taicpu(p), top_const, top_reg) and
  6756. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6757. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6758. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6759. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6760. begin
  6761. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6762. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6763. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6764. {$ifdef x86_64}
  6765. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6766. {$endif x86_64}
  6767. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6768. begin
  6769. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6770. taicpu(hp1).opcode:=A_MOV;
  6771. taicpu(hp1).oper[0]^.val:=0;
  6772. end
  6773. else
  6774. begin
  6775. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6776. taicpu(hp1).oper[0]^.val:=shiftval;
  6777. end;
  6778. RemoveCurrentP(p);
  6779. Result:=true;
  6780. exit;
  6781. end;
  6782. end;
  6783. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6784. begin
  6785. case shr_size of
  6786. S_B:
  6787. { No valid combinations }
  6788. Result := False;
  6789. S_W:
  6790. Result := (Shift >= 8) and (movz_size = S_BW);
  6791. S_L:
  6792. Result :=
  6793. (Shift >= 24) { Any opsize is valid for this shift } or
  6794. ((Shift >= 16) and (movz_size = S_WL));
  6795. {$ifdef x86_64}
  6796. S_Q:
  6797. Result :=
  6798. (Shift >= 56) { Any opsize is valid for this shift } or
  6799. ((Shift >= 48) and (movz_size = S_WL));
  6800. {$endif x86_64}
  6801. else
  6802. InternalError(2022081510);
  6803. end;
  6804. end;
  6805. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6806. var
  6807. hp1, hp2: tai;
  6808. Shift: TCGInt;
  6809. LimitSize: Topsize;
  6810. DoNotMerge: Boolean;
  6811. begin
  6812. Result := False;
  6813. { All these optimisations work on "shr const,%reg" }
  6814. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6815. Exit;
  6816. DoNotMerge := False;
  6817. Shift := taicpu(p).oper[0]^.val;
  6818. LimitSize := taicpu(p).opsize;
  6819. hp1 := p;
  6820. repeat
  6821. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6822. Exit;
  6823. case taicpu(hp1).opcode of
  6824. A_TEST, A_CMP, A_Jcc:
  6825. { Skip over conditional jumps and relevant comparisons }
  6826. Continue;
  6827. A_MOVZX:
  6828. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6829. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6830. begin
  6831. { Since the original register is being read as is, subsequent
  6832. SHRs must not be merged at this point }
  6833. DoNotMerge := True;
  6834. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6835. begin
  6836. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6837. begin
  6838. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6839. taicpu(hp1).opcode := A_MOV;
  6840. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6841. case taicpu(hp1).opsize of
  6842. S_BW:
  6843. taicpu(hp1).opsize := S_W;
  6844. S_BL, S_WL:
  6845. taicpu(hp1).opsize := S_L;
  6846. else
  6847. InternalError(2022081503);
  6848. end;
  6849. { p itself hasn't changed, so no need to set Result to True }
  6850. Include(OptsToCheck, aoc_ForceNewIteration);
  6851. { See if there's anything afterwards that can be
  6852. optimised, since the input register hasn't changed }
  6853. Continue;
  6854. end;
  6855. { NOTE: If the MOVZX instruction reads and writes the same
  6856. register, defer this to the post-peephole optimisation stage }
  6857. Exit;
  6858. end;
  6859. end;
  6860. A_SHL, A_SAL, A_SHR:
  6861. if (taicpu(hp1).opsize <= LimitSize) and
  6862. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6863. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6864. begin
  6865. { Make sure the sizes don't exceed the register size limit
  6866. (measured by the shift value falling below the limit) }
  6867. if taicpu(hp1).opsize < LimitSize then
  6868. LimitSize := taicpu(hp1).opsize;
  6869. if taicpu(hp1).opcode = A_SHR then
  6870. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6871. else
  6872. begin
  6873. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6874. DoNotMerge := True;
  6875. end;
  6876. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6877. Exit;
  6878. { Since we've established that the combined shift is within
  6879. limits, we can actually combine the adjacent SHR
  6880. instructions even if they're different sizes }
  6881. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6882. begin
  6883. hp2 := tai(hp1.Previous);
  6884. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6885. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6886. RemoveInstruction(hp1);
  6887. hp1 := hp2;
  6888. { Though p has changed, only the constant has, and its
  6889. effects can still be detected on the next iteration of
  6890. the repeat..until loop }
  6891. Include(OptsToCheck, aoc_ForceNewIteration);
  6892. end;
  6893. { Move onto the next instruction }
  6894. Continue;
  6895. end;
  6896. else
  6897. ;
  6898. end;
  6899. Break;
  6900. until False;
  6901. end;
  6902. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6903. var
  6904. CurrentRef: TReference;
  6905. FullReg: TRegister;
  6906. hp1, hp2: tai;
  6907. begin
  6908. Result := False;
  6909. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6910. Exit;
  6911. { We assume you've checked if the operand is actually a reference by
  6912. this point. If it isn't, you'll most likely get an access violation }
  6913. CurrentRef := first_mov.oper[1]^.ref^;
  6914. { Memory must be aligned }
  6915. if (CurrentRef.offset mod 4) <> 0 then
  6916. Exit;
  6917. Inc(CurrentRef.offset);
  6918. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6919. if MatchOperand(second_mov.oper[0]^, 0) and
  6920. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6921. GetNextInstruction(second_mov, hp1) and
  6922. (hp1.typ = ait_instruction) and
  6923. (taicpu(hp1).opcode = A_MOV) and
  6924. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6925. (taicpu(hp1).oper[0]^.val = 0) then
  6926. begin
  6927. Inc(CurrentRef.offset);
  6928. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6929. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6930. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6931. begin
  6932. case taicpu(hp1).opsize of
  6933. S_B:
  6934. if GetNextInstruction(hp1, hp2) and
  6935. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6936. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6937. (taicpu(hp2).oper[0]^.val = 0) then
  6938. begin
  6939. Inc(CurrentRef.offset);
  6940. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6941. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6942. (taicpu(hp2).opsize = S_B) then
  6943. begin
  6944. RemoveInstruction(hp1);
  6945. RemoveInstruction(hp2);
  6946. first_mov.opsize := S_L;
  6947. if first_mov.oper[0]^.typ = top_reg then
  6948. begin
  6949. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6950. { Reuse second_mov as a MOVZX instruction }
  6951. second_mov.opcode := A_MOVZX;
  6952. second_mov.opsize := S_BL;
  6953. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6954. second_mov.loadreg(1, FullReg);
  6955. first_mov.oper[0]^.reg := FullReg;
  6956. asml.Remove(second_mov);
  6957. asml.InsertBefore(second_mov, first_mov);
  6958. end
  6959. else
  6960. { It's a value }
  6961. begin
  6962. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6963. RemoveInstruction(second_mov);
  6964. end;
  6965. Result := True;
  6966. Exit;
  6967. end;
  6968. end;
  6969. S_W:
  6970. begin
  6971. RemoveInstruction(hp1);
  6972. first_mov.opsize := S_L;
  6973. if first_mov.oper[0]^.typ = top_reg then
  6974. begin
  6975. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6976. { Reuse second_mov as a MOVZX instruction }
  6977. second_mov.opcode := A_MOVZX;
  6978. second_mov.opsize := S_BL;
  6979. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6980. second_mov.loadreg(1, FullReg);
  6981. first_mov.oper[0]^.reg := FullReg;
  6982. asml.Remove(second_mov);
  6983. asml.InsertBefore(second_mov, first_mov);
  6984. end
  6985. else
  6986. { It's a value }
  6987. begin
  6988. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6989. RemoveInstruction(second_mov);
  6990. end;
  6991. Result := True;
  6992. Exit;
  6993. end;
  6994. else
  6995. ;
  6996. end;
  6997. end;
  6998. end;
  6999. end;
  7000. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7001. { returns true if a "continue" should be done after this optimization }
  7002. var
  7003. hp1, hp2, hp3: tai;
  7004. begin
  7005. Result := false;
  7006. hp3 := nil;
  7007. if MatchOpType(taicpu(p),top_ref) and
  7008. GetNextInstruction(p, hp1) and
  7009. (hp1.typ = ait_instruction) and
  7010. (((taicpu(hp1).opcode = A_FLD) and
  7011. (taicpu(p).opcode = A_FSTP)) or
  7012. ((taicpu(p).opcode = A_FISTP) and
  7013. (taicpu(hp1).opcode = A_FILD))) and
  7014. MatchOpType(taicpu(hp1),top_ref) and
  7015. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7016. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7017. begin
  7018. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7019. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7020. GetNextInstruction(hp1, hp2) and
  7021. (((hp2.typ = ait_instruction) and
  7022. IsExitCode(hp2) and
  7023. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7024. not(assigned(current_procinfo.procdef.funcretsym) and
  7025. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7026. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7027. { fstp <temp>
  7028. fld <temp>
  7029. <dealloc> <temp>
  7030. }
  7031. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7032. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7033. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7034. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7035. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7036. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7037. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7038. )
  7039. )
  7040. ) then
  7041. begin
  7042. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7043. RemoveInstruction(hp1);
  7044. RemoveCurrentP(p, hp2);
  7045. { first case: exit code }
  7046. if hp2.typ = ait_instruction then
  7047. RemoveLastDeallocForFuncRes(p);
  7048. Result := true;
  7049. end
  7050. else
  7051. { we can do this only in fast math mode as fstp is rounding ...
  7052. ... still disabled as it breaks the compiler and/or rtl }
  7053. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7054. { ... or if another fstp equal to the first one follows }
  7055. GetNextInstruction(hp1,hp2) and
  7056. (hp2.typ = ait_instruction) and
  7057. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7058. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7059. begin
  7060. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7061. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7062. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7063. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7064. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7065. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7066. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7067. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7068. ) then
  7069. begin
  7070. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7071. RemoveCurrentP(p,hp2);
  7072. RemoveInstruction(hp1);
  7073. Result := true;
  7074. end
  7075. else if { fst can't store an extended/comp value }
  7076. (taicpu(p).opsize <> S_FX) and
  7077. (taicpu(p).opsize <> S_IQ) then
  7078. begin
  7079. if (taicpu(p).opcode = A_FSTP) then
  7080. taicpu(p).opcode := A_FST
  7081. else
  7082. taicpu(p).opcode := A_FIST;
  7083. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7084. RemoveInstruction(hp1);
  7085. Result := true;
  7086. end;
  7087. end;
  7088. end;
  7089. end;
  7090. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7091. var
  7092. hp1, hp2, hp3: tai;
  7093. begin
  7094. result:=false;
  7095. if MatchOpType(taicpu(p),top_reg) and
  7096. GetNextInstruction(p, hp1) and
  7097. (hp1.typ = Ait_Instruction) and
  7098. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7099. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7100. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7101. { change to
  7102. fld reg fxxx reg,st
  7103. fxxxp st, st1 (hp1)
  7104. Remark: non commutative operations must be reversed!
  7105. }
  7106. begin
  7107. case taicpu(hp1).opcode Of
  7108. A_FMULP,A_FADDP,
  7109. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7110. begin
  7111. case taicpu(hp1).opcode Of
  7112. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7113. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7114. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7115. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7116. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7117. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7118. else
  7119. internalerror(2019050534);
  7120. end;
  7121. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7122. taicpu(hp1).oper[1]^.reg := NR_ST;
  7123. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7124. RemoveCurrentP(p, hp1);
  7125. Result:=true;
  7126. exit;
  7127. end;
  7128. else
  7129. ;
  7130. end;
  7131. end
  7132. else
  7133. if MatchOpType(taicpu(p),top_ref) and
  7134. GetNextInstruction(p, hp2) and
  7135. (hp2.typ = Ait_Instruction) and
  7136. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7137. (taicpu(p).opsize in [S_FS, S_FL]) and
  7138. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7139. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7140. if GetLastInstruction(p, hp1) and
  7141. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7142. MatchOpType(taicpu(hp1),top_ref) and
  7143. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7144. if ((taicpu(hp2).opcode = A_FMULP) or
  7145. (taicpu(hp2).opcode = A_FADDP)) then
  7146. { change to
  7147. fld/fst mem1 (hp1) fld/fst mem1
  7148. fld mem1 (p) fadd/
  7149. faddp/ fmul st, st
  7150. fmulp st, st1 (hp2) }
  7151. begin
  7152. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7153. RemoveCurrentP(p, hp1);
  7154. if (taicpu(hp2).opcode = A_FADDP) then
  7155. taicpu(hp2).opcode := A_FADD
  7156. else
  7157. taicpu(hp2).opcode := A_FMUL;
  7158. taicpu(hp2).oper[1]^.reg := NR_ST;
  7159. end
  7160. else
  7161. { change to
  7162. fld/fst mem1 (hp1) fld/fst mem1
  7163. fld mem1 (p) fld st
  7164. }
  7165. begin
  7166. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7167. taicpu(p).changeopsize(S_FL);
  7168. taicpu(p).loadreg(0,NR_ST);
  7169. end
  7170. else
  7171. begin
  7172. case taicpu(hp2).opcode Of
  7173. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7174. { change to
  7175. fld/fst mem1 (hp1) fld/fst mem1
  7176. fld mem2 (p) fxxx mem2
  7177. fxxxp st, st1 (hp2) }
  7178. begin
  7179. case taicpu(hp2).opcode Of
  7180. A_FADDP: taicpu(p).opcode := A_FADD;
  7181. A_FMULP: taicpu(p).opcode := A_FMUL;
  7182. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7183. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7184. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7185. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7186. else
  7187. internalerror(2019050533);
  7188. end;
  7189. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7190. RemoveInstruction(hp2);
  7191. end
  7192. else
  7193. ;
  7194. end
  7195. end
  7196. end;
  7197. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7198. begin
  7199. Result := condition_in(cond1, cond2) or
  7200. { Not strictly subsets due to the actual flags checked, but because we're
  7201. comparing integers, E is a subset of AE and GE and their aliases }
  7202. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7203. end;
  7204. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7205. var
  7206. v: TCGInt;
  7207. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7208. FirstMatch, TempBool: Boolean;
  7209. NewReg: TRegister;
  7210. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7211. begin
  7212. Result:=false;
  7213. { All these optimisations need a next instruction }
  7214. if not GetNextInstruction(p, hp1) then
  7215. Exit;
  7216. true_hp1 := hp1;
  7217. { Search for:
  7218. cmp ###,###
  7219. j(c1) @lbl1
  7220. ...
  7221. @lbl:
  7222. cmp ###,### (same comparison as above)
  7223. j(c2) @lbl2
  7224. If c1 is a subset of c2, change to:
  7225. cmp ###,###
  7226. j(c1) @lbl2
  7227. (@lbl1 may become a dead label as a result)
  7228. }
  7229. { Also handle cases where there are multiple jumps in a row }
  7230. p_jump := hp1;
  7231. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7232. begin
  7233. Prefetch(p_jump.Next);
  7234. if IsJumpToLabel(taicpu(p_jump)) then
  7235. begin
  7236. { Do jump optimisations first in case the condition becomes
  7237. unnecessary }
  7238. TempBool := True;
  7239. if DoJumpOptimizations(p_jump, TempBool) or
  7240. not TempBool then
  7241. begin
  7242. if Assigned(p_jump) then
  7243. begin
  7244. { CollapseZeroDistJump will be set to the label or an align
  7245. before it after the jump if it optimises, whether or not
  7246. the label is live or dead }
  7247. if (p_jump.typ = ait_align) or
  7248. (
  7249. (p_jump.typ = ait_label) and
  7250. not (tai_label(p_jump).labsym.is_used)
  7251. ) then
  7252. GetNextInstruction(p_jump, p_jump);
  7253. end;
  7254. TransferUsedRegs(TmpUsedRegs);
  7255. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7256. if not Assigned(p_jump) or
  7257. (
  7258. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7259. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7260. ) then
  7261. begin
  7262. { No more conditional jumps; conditional statement is no longer required }
  7263. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7264. RemoveCurrentP(p);
  7265. Result := True;
  7266. Exit;
  7267. end;
  7268. hp1 := p_jump;
  7269. Include(OptsToCheck, aoc_ForceNewIteration);
  7270. Continue;
  7271. end;
  7272. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7273. if GetNextInstruction(p_jump, hp2) and
  7274. (
  7275. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7276. not TempBool
  7277. ) then
  7278. begin
  7279. hp1 := p_jump;
  7280. Include(OptsToCheck, aoc_ForceNewIteration);
  7281. Continue;
  7282. end;
  7283. p_label := nil;
  7284. if Assigned(JumpLabel) then
  7285. p_label := getlabelwithsym(JumpLabel);
  7286. if Assigned(p_label) and
  7287. GetNextInstruction(p_label, p_dist) and
  7288. MatchInstruction(p_dist, A_CMP, []) and
  7289. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7290. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7291. GetNextInstruction(p_dist, hp1_dist) and
  7292. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7293. begin
  7294. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7295. if JumpLabel = JumpLabel_dist then
  7296. { This is an infinite loop }
  7297. Exit;
  7298. { Best optimisation when the first condition is a subset (or equal) of the second }
  7299. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7300. begin
  7301. { Any registers used here will already be allocated }
  7302. if Assigned(JumpLabel) then
  7303. JumpLabel.DecRefs;
  7304. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7305. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7306. Include(OptsToCheck, aoc_ForceNewIteration);
  7307. { Don't exit yet. Since p and p_jump haven't actually been
  7308. removed, we can check for more on this iteration }
  7309. end
  7310. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7311. GetNextInstruction(hp1_dist, hp1_label) and
  7312. (hp1_label.typ = ait_label) then
  7313. begin
  7314. JumpLabel_far := tai_label(hp1_label).labsym;
  7315. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7316. { This is an infinite loop }
  7317. Exit;
  7318. if Assigned(JumpLabel_far) then
  7319. begin
  7320. { In this situation, if the first jump branches, the second one will never,
  7321. branch so change the destination label to after the second jump }
  7322. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7323. if Assigned(JumpLabel) then
  7324. JumpLabel.DecRefs;
  7325. JumpLabel_far.IncRefs;
  7326. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7327. Result := True;
  7328. { Don't exit yet. Since p and p_jump haven't actually been
  7329. removed, we can check for more on this iteration }
  7330. Continue;
  7331. end;
  7332. end;
  7333. end;
  7334. end;
  7335. { Search for:
  7336. cmp ###,###
  7337. j(c1) @lbl1
  7338. cmp ###,### (same as first)
  7339. Remove second cmp
  7340. }
  7341. if GetNextInstruction(p_jump, hp2) and
  7342. (
  7343. (
  7344. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7345. (
  7346. (
  7347. MatchOpType(taicpu(p), top_const, top_reg) and
  7348. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7349. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7350. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7351. ) or (
  7352. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7353. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7354. )
  7355. )
  7356. ) or (
  7357. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7358. MatchOperand(taicpu(p).oper[0]^, 0) and
  7359. (taicpu(p).oper[1]^.typ = top_reg) and
  7360. MatchInstruction(hp2, A_TEST, []) and
  7361. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7362. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7363. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7364. )
  7365. ) then
  7366. begin
  7367. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7368. TransferUsedRegs(TmpUsedRegs);
  7369. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7370. RemoveInstruction(hp2);
  7371. Result := True;
  7372. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7373. end
  7374. else
  7375. begin
  7376. { hp2 is the next instruction, so save time and just set p_jump
  7377. to it instead of calling GetNextInstruction below }
  7378. p_jump := hp2;
  7379. Continue;
  7380. end;
  7381. GetNextInstruction(p_jump, p_jump);
  7382. end;
  7383. if (
  7384. { Don't call GetNextInstruction again if we already have it }
  7385. (true_hp1 = p_jump) or
  7386. GetNextInstruction(p, hp1)
  7387. ) and
  7388. MatchInstruction(hp1, A_Jcc, []) and
  7389. IsJumpToLabel(taicpu(hp1)) and
  7390. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7391. GetNextInstruction(hp1, hp2) then
  7392. begin
  7393. {
  7394. cmp x, y (or "cmp y, x")
  7395. je @lbl
  7396. mov x, y
  7397. @lbl:
  7398. (x and y can be constants, registers or references)
  7399. Change to:
  7400. mov x, y (x and y will always be equal in the end)
  7401. @lbl: (may beceome a dead label)
  7402. Also:
  7403. cmp x, y (or "cmp y, x")
  7404. jne @lbl
  7405. mov x, y
  7406. @lbl:
  7407. (x and y can be constants, registers or references)
  7408. Change to:
  7409. Absolutely nothing! (Except @lbl if it's still live)
  7410. }
  7411. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7412. (
  7413. (
  7414. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7415. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7416. ) or (
  7417. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7418. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7419. )
  7420. ) and
  7421. GetNextInstruction(hp2, hp1_label) and
  7422. (hp1_label.typ = ait_label) and
  7423. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7424. begin
  7425. tai_label(hp1_label).labsym.DecRefs;
  7426. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7427. begin
  7428. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7429. RemoveInstruction(hp2);
  7430. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7431. end
  7432. else
  7433. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7434. RemoveInstruction(hp1);
  7435. RemoveCurrentp(p, hp2);
  7436. Result := True;
  7437. Exit;
  7438. end;
  7439. {
  7440. Try to optimise the following:
  7441. cmp $x,### ($x and $y can be registers or constants)
  7442. je @lbl1 (only reference)
  7443. cmp $y,### (### are identical)
  7444. @Lbl:
  7445. sete %reg1
  7446. Change to:
  7447. cmp $x,###
  7448. sete %reg2 (allocate new %reg2)
  7449. cmp $y,###
  7450. sete %reg1
  7451. orb %reg2,%reg1
  7452. (dealloc %reg2)
  7453. This adds an instruction (so don't perform under -Os), but it removes
  7454. a conditional branch.
  7455. }
  7456. if not (cs_opt_size in current_settings.optimizerswitches) and
  7457. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7458. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7459. { The first operand of CMP instructions can only be a register or
  7460. immediate anyway, so no need to check }
  7461. GetNextInstruction(hp2, p_label) and
  7462. (p_label.typ = ait_label) and
  7463. (tai_label(p_label).labsym.getrefs = 1) and
  7464. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7465. GetNextInstruction(p_label, p_dist) and
  7466. MatchInstruction(p_dist, A_SETcc, []) and
  7467. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7468. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7469. begin
  7470. TransferUsedRegs(TmpUsedRegs);
  7471. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7472. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7473. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7474. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7475. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7476. { Get the instruction after the SETcc instruction so we can
  7477. allocate a new register over the entire range }
  7478. GetNextInstruction(p_dist, hp1_dist) then
  7479. begin
  7480. { Register can appear in p if it's not used afterwards, so only
  7481. allocate between hp1 and hp1_dist }
  7482. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7483. if NewReg <> NR_NO then
  7484. begin
  7485. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7486. { Change the jump instruction into a SETcc instruction }
  7487. taicpu(hp1).opcode := A_SETcc;
  7488. taicpu(hp1).opsize := S_B;
  7489. taicpu(hp1).loadreg(0, NewReg);
  7490. { This is now a dead label }
  7491. tai_label(p_label).labsym.decrefs;
  7492. { Prefer adding before the next instruction so the FLAGS
  7493. register is deallicated first }
  7494. AsmL.InsertBefore(
  7495. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7496. hp1_dist
  7497. );
  7498. Result := True;
  7499. { Don't exit yet, as p wasn't changed and hp1, while
  7500. modified, is still intact and might be optimised by the
  7501. SETcc optimisation below }
  7502. end;
  7503. end;
  7504. end;
  7505. end;
  7506. if (taicpu(p).oper[0]^.typ = top_const) and
  7507. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7508. begin
  7509. if (taicpu(p).oper[0]^.val = 0) and
  7510. (taicpu(p).oper[1]^.typ = top_reg) then
  7511. begin
  7512. hp2 := p;
  7513. FirstMatch := True;
  7514. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7515. anything meaningful once it's converted to "test %reg,%reg";
  7516. additionally, some jumps will always (or never) branch, so
  7517. evaluate every jump immediately following the
  7518. comparison, optimising the conditions if possible.
  7519. Similarly with SETcc... those that are always set to 0 or 1
  7520. are changed to MOV instructions }
  7521. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7522. (
  7523. GetNextInstruction(hp2, hp1) and
  7524. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7525. ) do
  7526. begin
  7527. Prefetch(hp1.Next);
  7528. FirstMatch := False;
  7529. case taicpu(hp1).condition of
  7530. C_B, C_C, C_NAE, C_O:
  7531. { For B/NAE:
  7532. Will never branch since an unsigned integer can never be below zero
  7533. For C/O:
  7534. Result cannot overflow because 0 is being subtracted
  7535. }
  7536. begin
  7537. if taicpu(hp1).opcode = A_Jcc then
  7538. begin
  7539. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7540. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7541. RemoveInstruction(hp1);
  7542. { Since hp1 was deleted, hp2 must not be updated }
  7543. Continue;
  7544. end
  7545. else
  7546. begin
  7547. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7548. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7549. taicpu(hp1).opcode := A_MOV;
  7550. taicpu(hp1).ops := 2;
  7551. taicpu(hp1).condition := C_None;
  7552. taicpu(hp1).opsize := S_B;
  7553. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7554. taicpu(hp1).loadconst(0, 0);
  7555. end;
  7556. end;
  7557. C_BE, C_NA:
  7558. begin
  7559. { Will only branch if equal to zero }
  7560. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7561. taicpu(hp1).condition := C_E;
  7562. end;
  7563. C_A, C_NBE:
  7564. begin
  7565. { Will only branch if not equal to zero }
  7566. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7567. taicpu(hp1).condition := C_NE;
  7568. end;
  7569. C_AE, C_NB, C_NC, C_NO:
  7570. begin
  7571. { Will always branch }
  7572. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7573. if taicpu(hp1).opcode = A_Jcc then
  7574. begin
  7575. MakeUnconditional(taicpu(hp1));
  7576. { Any jumps/set that follow will now be dead code }
  7577. RemoveDeadCodeAfterJump(taicpu(hp1));
  7578. Break;
  7579. end
  7580. else
  7581. begin
  7582. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7583. taicpu(hp1).opcode := A_MOV;
  7584. taicpu(hp1).ops := 2;
  7585. taicpu(hp1).condition := C_None;
  7586. taicpu(hp1).opsize := S_B;
  7587. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7588. taicpu(hp1).loadconst(0, 1);
  7589. end;
  7590. end;
  7591. C_None:
  7592. InternalError(2020012201);
  7593. C_P, C_PE, C_NP, C_PO:
  7594. { We can't handle parity checks and they should never be generated
  7595. after a general-purpose CMP (it's used in some floating-point
  7596. comparisons that don't use CMP) }
  7597. InternalError(2020012202);
  7598. else
  7599. { Zero/Equality, Sign, their complements and all of the
  7600. signed comparisons do not need to be converted };
  7601. end;
  7602. hp2 := hp1;
  7603. end;
  7604. { Convert the instruction to a TEST }
  7605. taicpu(p).opcode := A_TEST;
  7606. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7607. Result := True;
  7608. Exit;
  7609. end
  7610. else
  7611. begin
  7612. TransferUsedRegs(TmpUsedRegs);
  7613. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7614. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7615. begin
  7616. if (taicpu(p).oper[0]^.val = 1) and
  7617. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7618. begin
  7619. { Convert; To:
  7620. cmp $1,r/m cmp $0,r/m
  7621. jl @lbl jle @lbl
  7622. (Also do inverted conditions)
  7623. }
  7624. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7625. taicpu(p).oper[0]^.val := 0;
  7626. if taicpu(hp1).condition in [C_L, C_NGE] then
  7627. taicpu(hp1).condition := C_LE
  7628. else
  7629. taicpu(hp1).condition := C_NLE;
  7630. { If the instruction is now "cmp $0,%reg", convert it to a
  7631. TEST (and effectively do the work of the "cmp $0,%reg" in
  7632. the block above)
  7633. }
  7634. if (taicpu(p).oper[1]^.typ = top_reg) then
  7635. begin
  7636. taicpu(p).opcode := A_TEST;
  7637. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7638. end;
  7639. Result := True;
  7640. Exit;
  7641. end
  7642. else if (taicpu(p).oper[1]^.typ = top_reg)
  7643. {$ifdef x86_64}
  7644. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7645. {$endif x86_64}
  7646. then
  7647. begin
  7648. { cmp register,$8000 neg register
  7649. je target --> jo target
  7650. .... only if register is deallocated before jump.}
  7651. case Taicpu(p).opsize of
  7652. S_B: v:=$80;
  7653. S_W: v:=$8000;
  7654. S_L: v:=qword($80000000);
  7655. else
  7656. internalerror(2013112905);
  7657. end;
  7658. if (taicpu(p).oper[0]^.val=v) and
  7659. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7660. begin
  7661. TransferUsedRegs(TmpUsedRegs);
  7662. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7663. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7664. begin
  7665. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7666. Taicpu(p).opcode:=A_NEG;
  7667. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7668. Taicpu(p).clearop(1);
  7669. Taicpu(p).ops:=1;
  7670. if Taicpu(hp1).condition=C_E then
  7671. Taicpu(hp1).condition:=C_O
  7672. else
  7673. Taicpu(hp1).condition:=C_NO;
  7674. Result:=true;
  7675. exit;
  7676. end;
  7677. end;
  7678. end;
  7679. end;
  7680. end;
  7681. end;
  7682. if TrySwapMovCmp(p, hp1) then
  7683. begin
  7684. Result := True;
  7685. Exit;
  7686. end;
  7687. end;
  7688. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7689. var
  7690. hp1: tai;
  7691. begin
  7692. {
  7693. remove the second (v)pxor from
  7694. pxor reg,reg
  7695. ...
  7696. pxor reg,reg
  7697. }
  7698. Result:=false;
  7699. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7700. MatchOpType(taicpu(p),top_reg,top_reg) and
  7701. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7702. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7703. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7704. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7705. begin
  7706. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7707. RemoveInstruction(hp1);
  7708. Result:=true;
  7709. Exit;
  7710. end
  7711. {
  7712. replace
  7713. pxor reg1,reg1
  7714. movapd/s reg1,reg2
  7715. dealloc reg1
  7716. by
  7717. pxor reg2,reg2
  7718. }
  7719. else if GetNextInstruction(p,hp1) and
  7720. { we mix single and double opperations here because we assume that the compiler
  7721. generates vmovapd only after double operations and vmovaps only after single operations }
  7722. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7723. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7724. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7725. (taicpu(p).oper[0]^.typ=top_reg) then
  7726. begin
  7727. TransferUsedRegs(TmpUsedRegs);
  7728. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7729. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7730. begin
  7731. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7732. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7733. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7734. RemoveInstruction(hp1);
  7735. result:=true;
  7736. end;
  7737. end;
  7738. end;
  7739. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7740. var
  7741. hp1: tai;
  7742. begin
  7743. {
  7744. remove the second (v)pxor from
  7745. (v)pxor reg,reg
  7746. ...
  7747. (v)pxor reg,reg
  7748. }
  7749. Result:=false;
  7750. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7751. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7752. begin
  7753. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7754. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7755. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7756. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7757. begin
  7758. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7759. RemoveInstruction(hp1);
  7760. Result:=true;
  7761. Exit;
  7762. end;
  7763. {$ifdef x86_64}
  7764. {
  7765. replace
  7766. vpxor reg1,reg1,reg1
  7767. vmov reg,mem
  7768. by
  7769. movq $0,mem
  7770. }
  7771. if GetNextInstruction(p,hp1) and
  7772. MatchInstruction(hp1,A_VMOVSD,[]) and
  7773. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7774. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7775. begin
  7776. TransferUsedRegs(TmpUsedRegs);
  7777. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7778. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7779. begin
  7780. taicpu(hp1).loadconst(0,0);
  7781. taicpu(hp1).opcode:=A_MOV;
  7782. taicpu(hp1).opsize:=S_Q;
  7783. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7784. RemoveCurrentP(p);
  7785. result:=true;
  7786. Exit;
  7787. end;
  7788. end;
  7789. {$endif x86_64}
  7790. end
  7791. {
  7792. replace
  7793. vpxor reg1,reg1,reg2
  7794. by
  7795. vpxor reg2,reg2,reg2
  7796. to avoid unncessary data dependencies
  7797. }
  7798. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7799. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7800. begin
  7801. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7802. { avoid unncessary data dependency }
  7803. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7804. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7805. result:=true;
  7806. exit;
  7807. end;
  7808. Result:=OptPass1VOP(p);
  7809. end;
  7810. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7811. var
  7812. hp1 : tai;
  7813. begin
  7814. result:=false;
  7815. { replace
  7816. IMul const,%mreg1,%mreg2
  7817. Mov %reg2,%mreg3
  7818. dealloc %mreg3
  7819. by
  7820. Imul const,%mreg1,%mreg23
  7821. }
  7822. if (taicpu(p).ops=3) and
  7823. GetNextInstruction(p,hp1) and
  7824. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7825. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7826. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7827. begin
  7828. TransferUsedRegs(TmpUsedRegs);
  7829. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7830. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7831. begin
  7832. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7833. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7834. RemoveInstruction(hp1);
  7835. result:=true;
  7836. end;
  7837. end;
  7838. end;
  7839. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7840. var
  7841. hp1 : tai;
  7842. begin
  7843. result:=false;
  7844. { replace
  7845. IMul %reg0,%reg1,%reg2
  7846. Mov %reg2,%reg3
  7847. dealloc %reg2
  7848. by
  7849. Imul %reg0,%reg1,%reg3
  7850. }
  7851. if GetNextInstruction(p,hp1) and
  7852. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7853. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7854. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7855. begin
  7856. TransferUsedRegs(TmpUsedRegs);
  7857. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7858. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7859. begin
  7860. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7861. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7862. RemoveInstruction(hp1);
  7863. result:=true;
  7864. end;
  7865. end;
  7866. end;
  7867. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7868. var
  7869. hp1: tai;
  7870. begin
  7871. Result:=false;
  7872. { get rid of
  7873. (v)cvtss2sd reg0,<reg1,>reg2
  7874. (v)cvtss2sd reg2,<reg2,>reg0
  7875. }
  7876. if GetNextInstruction(p,hp1) and
  7877. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7878. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7879. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7880. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7881. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7882. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7883. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7884. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7885. )
  7886. ) then
  7887. begin
  7888. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7889. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7890. begin
  7891. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7892. RemoveCurrentP(p);
  7893. RemoveInstruction(hp1);
  7894. end
  7895. else
  7896. begin
  7897. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7898. if taicpu(hp1).opcode=A_CVTSD2SS then
  7899. begin
  7900. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7901. taicpu(p).opcode:=A_MOVAPS;
  7902. end
  7903. else
  7904. begin
  7905. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7906. taicpu(p).opcode:=A_VMOVAPS;
  7907. end;
  7908. taicpu(p).ops:=2;
  7909. RemoveInstruction(hp1);
  7910. end;
  7911. Result:=true;
  7912. Exit;
  7913. end;
  7914. end;
  7915. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7916. var
  7917. hp1, hp2, hp3, hp4, hp5: tai;
  7918. ThisReg: TRegister;
  7919. begin
  7920. Result := False;
  7921. if not GetNextInstruction(p,hp1) then
  7922. Exit;
  7923. {
  7924. convert
  7925. j<c> .L1
  7926. mov 1,reg
  7927. jmp .L2
  7928. .L1
  7929. mov 0,reg
  7930. .L2
  7931. into
  7932. mov 0,reg
  7933. set<not(c)> reg
  7934. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7935. would destroy the flag contents
  7936. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7937. executed at the same time as a previous comparison.
  7938. set<not(c)> reg
  7939. movzx reg, reg
  7940. }
  7941. if MatchInstruction(hp1,A_MOV,[]) and
  7942. (taicpu(hp1).oper[0]^.typ = top_const) and
  7943. (
  7944. (
  7945. (taicpu(hp1).oper[1]^.typ = top_reg)
  7946. {$ifdef i386}
  7947. { Under i386, ESI, EDI, EBP and ESP
  7948. don't have an 8-bit representation }
  7949. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7950. {$endif i386}
  7951. ) or (
  7952. {$ifdef i386}
  7953. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7954. {$endif i386}
  7955. (taicpu(hp1).opsize = S_B)
  7956. )
  7957. ) and
  7958. GetNextInstruction(hp1,hp2) and
  7959. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7960. GetNextInstruction(hp2,hp3) and
  7961. (hp3.typ=ait_label) and
  7962. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7963. GetNextInstruction(hp3,hp4) and
  7964. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7965. (taicpu(hp4).oper[0]^.typ = top_const) and
  7966. (
  7967. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7968. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7969. ) and
  7970. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7971. GetNextInstruction(hp4,hp5) and
  7972. (hp5.typ=ait_label) and
  7973. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7974. begin
  7975. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7976. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7977. tai_label(hp3).labsym.DecRefs;
  7978. { If this isn't the only reference to the middle label, we can
  7979. still make a saving - only that the first jump and everything
  7980. that follows will remain. }
  7981. if (tai_label(hp3).labsym.getrefs = 0) then
  7982. begin
  7983. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7984. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7985. else
  7986. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7987. { remove jump, first label and second MOV (also catching any aligns) }
  7988. repeat
  7989. if not GetNextInstruction(hp2, hp3) then
  7990. InternalError(2021040810);
  7991. RemoveInstruction(hp2);
  7992. hp2 := hp3;
  7993. until hp2 = hp5;
  7994. { Don't decrement reference count before the removal loop
  7995. above, otherwise GetNextInstruction won't stop on the
  7996. the label }
  7997. tai_label(hp5).labsym.DecRefs;
  7998. end
  7999. else
  8000. begin
  8001. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8002. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8003. else
  8004. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8005. end;
  8006. taicpu(p).opcode:=A_SETcc;
  8007. taicpu(p).opsize:=S_B;
  8008. taicpu(p).is_jmp:=False;
  8009. if taicpu(hp1).opsize=S_B then
  8010. begin
  8011. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8012. if taicpu(hp1).oper[1]^.typ = top_reg then
  8013. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8014. RemoveInstruction(hp1);
  8015. end
  8016. else
  8017. begin
  8018. { Will be a register because the size can't be S_B otherwise }
  8019. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8020. taicpu(p).loadreg(0, ThisReg);
  8021. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8022. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8023. begin
  8024. case taicpu(hp1).opsize of
  8025. S_W:
  8026. taicpu(hp1).opsize := S_BW;
  8027. S_L:
  8028. taicpu(hp1).opsize := S_BL;
  8029. {$ifdef x86_64}
  8030. S_Q:
  8031. begin
  8032. taicpu(hp1).opsize := S_BL;
  8033. { Change the destination register to 32-bit }
  8034. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8035. end;
  8036. {$endif x86_64}
  8037. else
  8038. InternalError(2021040820);
  8039. end;
  8040. taicpu(hp1).opcode := A_MOVZX;
  8041. taicpu(hp1).loadreg(0, ThisReg);
  8042. end
  8043. else
  8044. begin
  8045. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8046. { hp1 is already a MOV instruction with the correct register }
  8047. taicpu(hp1).loadconst(0, 0);
  8048. { Inserting it right before p will guarantee that the flags are also tracked }
  8049. asml.Remove(hp1);
  8050. asml.InsertBefore(hp1, p);
  8051. end;
  8052. end;
  8053. Result:=true;
  8054. exit;
  8055. end
  8056. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8057. Result := TryJccStcClcOpt(p, hp1)
  8058. else if (hp1.typ = ait_label) then
  8059. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8060. end;
  8061. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8062. var
  8063. hp1, hp2, hp3: tai;
  8064. SourceRef, TargetRef: TReference;
  8065. CurrentReg: TRegister;
  8066. begin
  8067. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8068. if not UseAVX then
  8069. InternalError(2021100501);
  8070. Result := False;
  8071. { Look for the following to simplify:
  8072. vmovdqa/u x(mem1), %xmmreg
  8073. vmovdqa/u %xmmreg, y(mem2)
  8074. vmovdqa/u x+16(mem1), %xmmreg
  8075. vmovdqa/u %xmmreg, y+16(mem2)
  8076. Change to:
  8077. vmovdqa/u x(mem1), %ymmreg
  8078. vmovdqa/u %ymmreg, y(mem2)
  8079. vpxor %ymmreg, %ymmreg, %ymmreg
  8080. ( The VPXOR instruction is to zero the upper half, thus removing the
  8081. need to call the potentially expensive VZEROUPPER instruction. Other
  8082. peephole optimisations can remove VPXOR if it's unnecessary )
  8083. }
  8084. TransferUsedRegs(TmpUsedRegs);
  8085. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8086. { NOTE: In the optimisations below, if the references dictate that an
  8087. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8088. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8089. if (taicpu(p).opsize = S_XMM) and
  8090. MatchOpType(taicpu(p), top_ref, top_reg) and
  8091. GetNextInstruction(p, hp1) and
  8092. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8093. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8094. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8095. begin
  8096. SourceRef := taicpu(p).oper[0]^.ref^;
  8097. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8098. if GetNextInstruction(hp1, hp2) and
  8099. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8100. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8101. begin
  8102. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8103. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8104. Inc(SourceRef.offset, 16);
  8105. { Reuse the register in the first block move }
  8106. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8107. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8108. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8109. begin
  8110. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8111. Inc(TargetRef.offset, 16);
  8112. if GetNextInstruction(hp2, hp3) and
  8113. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8114. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8115. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8116. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8117. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8118. begin
  8119. { Update the register tracking to the new size }
  8120. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8121. { Remember that the offsets are 16 ahead }
  8122. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8123. if not (
  8124. ((SourceRef.offset mod 32) = 16) and
  8125. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8126. ) then
  8127. taicpu(p).opcode := A_VMOVDQU;
  8128. taicpu(p).opsize := S_YMM;
  8129. taicpu(p).oper[1]^.reg := CurrentReg;
  8130. if not (
  8131. ((TargetRef.offset mod 32) = 16) and
  8132. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8133. ) then
  8134. taicpu(hp1).opcode := A_VMOVDQU;
  8135. taicpu(hp1).opsize := S_YMM;
  8136. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8137. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8138. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8139. if (pi_uses_ymm in current_procinfo.flags) then
  8140. RemoveInstruction(hp2)
  8141. else
  8142. begin
  8143. taicpu(hp2).opcode := A_VPXOR;
  8144. taicpu(hp2).opsize := S_YMM;
  8145. taicpu(hp2).loadreg(0, CurrentReg);
  8146. taicpu(hp2).loadreg(1, CurrentReg);
  8147. taicpu(hp2).loadreg(2, CurrentReg);
  8148. taicpu(hp2).ops := 3;
  8149. end;
  8150. RemoveInstruction(hp3);
  8151. Result := True;
  8152. Exit;
  8153. end;
  8154. end
  8155. else
  8156. begin
  8157. { See if the next references are 16 less rather than 16 greater }
  8158. Dec(SourceRef.offset, 32); { -16 the other way }
  8159. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8160. begin
  8161. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8162. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8163. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8164. GetNextInstruction(hp2, hp3) and
  8165. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8166. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8167. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8168. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8169. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8170. begin
  8171. { Update the register tracking to the new size }
  8172. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8173. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8174. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8175. if not(
  8176. ((SourceRef.offset mod 32) = 0) and
  8177. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8178. ) then
  8179. taicpu(hp2).opcode := A_VMOVDQU;
  8180. taicpu(hp2).opsize := S_YMM;
  8181. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8182. if not (
  8183. ((TargetRef.offset mod 32) = 0) and
  8184. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8185. ) then
  8186. taicpu(hp3).opcode := A_VMOVDQU;
  8187. taicpu(hp3).opsize := S_YMM;
  8188. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8189. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8190. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8191. if (pi_uses_ymm in current_procinfo.flags) then
  8192. RemoveInstruction(hp1)
  8193. else
  8194. begin
  8195. taicpu(hp1).opcode := A_VPXOR;
  8196. taicpu(hp1).opsize := S_YMM;
  8197. taicpu(hp1).loadreg(0, CurrentReg);
  8198. taicpu(hp1).loadreg(1, CurrentReg);
  8199. taicpu(hp1).loadreg(2, CurrentReg);
  8200. taicpu(hp1).ops := 3;
  8201. Asml.Remove(hp1);
  8202. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8203. end;
  8204. RemoveCurrentP(p, hp2);
  8205. Result := True;
  8206. Exit;
  8207. end;
  8208. end;
  8209. end;
  8210. end;
  8211. end;
  8212. end;
  8213. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8214. var
  8215. hp2, hp3, first_assignment: tai;
  8216. IncCount, OperIdx: Integer;
  8217. OrigLabel: TAsmLabel;
  8218. begin
  8219. Count := 0;
  8220. Result := False;
  8221. first_assignment := nil;
  8222. if (LoopCount >= 20) then
  8223. begin
  8224. { Guard against infinite loops }
  8225. Exit;
  8226. end;
  8227. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8228. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8229. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8230. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8231. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8232. Exit;
  8233. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8234. {
  8235. change
  8236. jmp .L1
  8237. ...
  8238. .L1:
  8239. mov ##, ## ( multiple movs possible )
  8240. jmp/ret
  8241. into
  8242. mov ##, ##
  8243. jmp/ret
  8244. }
  8245. if not Assigned(hp1) then
  8246. begin
  8247. hp1 := GetLabelWithSym(OrigLabel);
  8248. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8249. Exit;
  8250. end;
  8251. hp2 := hp1;
  8252. while Assigned(hp2) do
  8253. begin
  8254. if Assigned(hp2) and (hp2.typ = ait_label) then
  8255. SkipLabels(hp2,hp2);
  8256. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8257. Break;
  8258. case taicpu(hp2).opcode of
  8259. A_MOVSD:
  8260. begin
  8261. if taicpu(hp2).ops = 0 then
  8262. { Wrong MOVSD }
  8263. Break;
  8264. Inc(Count);
  8265. if Count >= 5 then
  8266. { Too many to be worthwhile }
  8267. Break;
  8268. GetNextInstruction(hp2, hp2);
  8269. Continue;
  8270. end;
  8271. A_MOV,
  8272. A_MOVD,
  8273. A_MOVQ,
  8274. A_MOVSX,
  8275. {$ifdef x86_64}
  8276. A_MOVSXD,
  8277. {$endif x86_64}
  8278. A_MOVZX,
  8279. A_MOVAPS,
  8280. A_MOVUPS,
  8281. A_MOVSS,
  8282. A_MOVAPD,
  8283. A_MOVUPD,
  8284. A_MOVDQA,
  8285. A_MOVDQU,
  8286. A_VMOVSS,
  8287. A_VMOVAPS,
  8288. A_VMOVUPS,
  8289. A_VMOVSD,
  8290. A_VMOVAPD,
  8291. A_VMOVUPD,
  8292. A_VMOVDQA,
  8293. A_VMOVDQU:
  8294. begin
  8295. Inc(Count);
  8296. if Count >= 5 then
  8297. { Too many to be worthwhile }
  8298. Break;
  8299. GetNextInstruction(hp2, hp2);
  8300. Continue;
  8301. end;
  8302. A_JMP:
  8303. begin
  8304. { Guard against infinite loops }
  8305. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8306. Exit;
  8307. { Analyse this jump first in case it also duplicates assignments }
  8308. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8309. begin
  8310. { Something did change! }
  8311. Result := True;
  8312. Inc(Count, IncCount);
  8313. if Count >= 5 then
  8314. begin
  8315. { Too many to be worthwhile }
  8316. Exit;
  8317. end;
  8318. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8319. Break;
  8320. end;
  8321. Result := True;
  8322. Break;
  8323. end;
  8324. A_RET:
  8325. begin
  8326. Result := True;
  8327. Break;
  8328. end;
  8329. else
  8330. Break;
  8331. end;
  8332. end;
  8333. if Result then
  8334. begin
  8335. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8336. if Count = 0 then
  8337. begin
  8338. Result := False;
  8339. Exit;
  8340. end;
  8341. TransferUsedRegs(TmpUsedRegs);
  8342. hp3 := p;
  8343. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8344. while True do
  8345. begin
  8346. if Assigned(hp1) and (hp1.typ = ait_label) then
  8347. SkipLabels(hp1,hp1);
  8348. if (hp1.typ <> ait_instruction) then
  8349. InternalError(2021040720);
  8350. case taicpu(hp1).opcode of
  8351. A_JMP:
  8352. begin
  8353. { Change the original jump to the new destination }
  8354. OrigLabel.decrefs;
  8355. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8356. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8357. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8358. if not Assigned(first_assignment) then
  8359. InternalError(2021040810)
  8360. else
  8361. p := first_assignment;
  8362. Exit;
  8363. end;
  8364. A_RET:
  8365. begin
  8366. { Now change the jump into a RET instruction }
  8367. ConvertJumpToRET(p, hp1);
  8368. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8369. if not Assigned(first_assignment) then
  8370. InternalError(2021040811)
  8371. else
  8372. p := first_assignment;
  8373. Exit;
  8374. end;
  8375. else
  8376. begin
  8377. { Duplicate the MOV instruction }
  8378. hp3:=tai(hp1.getcopy);
  8379. asml.InsertBefore(hp3, p);
  8380. { Make sure the compiler knows about any final registers written here }
  8381. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8382. with taicpu(hp3).oper[OperIdx]^ do
  8383. begin
  8384. case typ of
  8385. top_ref:
  8386. begin
  8387. if (ref^.base <> NR_NO) and
  8388. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  8389. (
  8390. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  8391. (
  8392. { Allow the frame pointer if it's not being used by the procedure as such }
  8393. Assigned(current_procinfo) and
  8394. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8395. )
  8396. )
  8397. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8398. then
  8399. begin
  8400. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  8401. if not Assigned(first_assignment) then
  8402. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  8403. end;
  8404. if (ref^.index <> NR_NO) and
  8405. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  8406. (
  8407. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  8408. (
  8409. { Allow the frame pointer if it's not being used by the procedure as such }
  8410. Assigned(current_procinfo) and
  8411. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8412. )
  8413. )
  8414. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8415. (ref^.index <> ref^.base) then
  8416. begin
  8417. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  8418. if not Assigned(first_assignment) then
  8419. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  8420. end;
  8421. end;
  8422. top_reg:
  8423. begin
  8424. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  8425. if not Assigned(first_assignment) then
  8426. IncludeRegInUsedRegs(reg, UsedRegs);
  8427. end;
  8428. else
  8429. ;
  8430. end;
  8431. end;
  8432. if first_assignment = nil then
  8433. first_assignment := hp3;
  8434. end;
  8435. end;
  8436. if not GetNextInstruction(hp1, hp1) then
  8437. { Should have dropped out earlier }
  8438. InternalError(2021040710);
  8439. end;
  8440. end;
  8441. end;
  8442. const
  8443. WriteOp: array[0..3] of set of TInsChange = (
  8444. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8445. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8446. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8447. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8448. RegWriteFlags: array[0..7] of set of TInsChange = (
  8449. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8450. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8451. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8452. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8453. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8454. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8455. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8456. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8457. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8458. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8459. var
  8460. hp2: tai;
  8461. X: Integer;
  8462. begin
  8463. { If we have something like:
  8464. op ###,###
  8465. mov ###,###
  8466. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8467. interfere in regards to what they write to.
  8468. NOTE: p must be a 2-operand instruction
  8469. }
  8470. Result := False;
  8471. if (hp1.typ <> ait_instruction) or
  8472. taicpu(hp1).is_jmp or
  8473. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8474. Exit;
  8475. { NOP is a pipeline fence, likely marking the beginning of the function
  8476. epilogue, so drop out. Similarly, drop out if POP or RET are
  8477. encountered }
  8478. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8479. Exit;
  8480. if (taicpu(hp1).opcode = A_MOVSD) and
  8481. (taicpu(hp1).ops = 0) then
  8482. { Wrong MOVSD }
  8483. Exit;
  8484. { Check for writes to specific registers first }
  8485. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8486. for X := 0 to 7 do
  8487. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8488. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8489. Exit;
  8490. for X := 0 to taicpu(hp1).ops - 1 do
  8491. begin
  8492. { Check to see if this operand writes to something }
  8493. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8494. { And matches something in the CMP/TEST instruction }
  8495. (
  8496. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8497. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8498. (
  8499. { If it's a register, make sure the register written to doesn't
  8500. appear in the cmp instruction as part of a reference }
  8501. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8502. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8503. )
  8504. ) then
  8505. Exit;
  8506. end;
  8507. { Check p to make sure it doesn't write to something that affects hp1 }
  8508. { Check for writes to specific registers first }
  8509. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8510. for X := 0 to 7 do
  8511. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8512. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8513. Exit;
  8514. for X := 0 to taicpu(p).ops - 1 do
  8515. begin
  8516. { Check to see if this operand writes to something }
  8517. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8518. { And matches something in hp1 }
  8519. (taicpu(p).oper[X]^.typ = top_reg) and
  8520. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8521. Exit;
  8522. end;
  8523. { The instruction can be safely moved }
  8524. asml.Remove(hp1);
  8525. { Try to insert after the last instructions where the FLAGS register is not
  8526. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8527. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8528. asml.InsertBefore(hp1, hp2)
  8529. { Failing that, try to insert after the last instructions where the
  8530. FLAGS register is not yet in use }
  8531. else if GetLastInstruction(p, hp2) and
  8532. (
  8533. (hp2.typ <> ait_instruction) or
  8534. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8535. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8536. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8537. ) then
  8538. asml.InsertAfter(hp1, hp2)
  8539. else
  8540. { Note, if p.Previous is nil (even if it should logically never be the
  8541. case), FindRegAllocBackward immediately exits with False and so we
  8542. safely land here (we can't just pass p because FindRegAllocBackward
  8543. immediately exits on an instruction). [Kit] }
  8544. asml.InsertBefore(hp1, p);
  8545. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8546. { We can't trust UsedRegs because we're looking backwards, although we
  8547. know the registers are allocated after p at the very least, so manually
  8548. create tai_regalloc objects if needed }
  8549. for X := 0 to taicpu(hp1).ops - 1 do
  8550. case taicpu(hp1).oper[X]^.typ of
  8551. top_reg:
  8552. begin
  8553. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8554. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8555. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8556. end;
  8557. top_ref:
  8558. begin
  8559. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8560. begin
  8561. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8562. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8563. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8564. end;
  8565. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8566. begin
  8567. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8568. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8569. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8570. end;
  8571. end;
  8572. else
  8573. ;
  8574. end;
  8575. Result := True;
  8576. end;
  8577. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8578. var
  8579. hp2: tai;
  8580. X: Integer;
  8581. begin
  8582. { If we have something like:
  8583. cmp ###,%reg1
  8584. mov 0,%reg2
  8585. And no modified registers are shared, move the instruction to before
  8586. the comparison as this means it can be optimised without worrying
  8587. about the FLAGS register. (CMP/MOV is generated by
  8588. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8589. As long as the second instruction doesn't use the flags or one of the
  8590. registers used by CMP or TEST (also check any references that use the
  8591. registers), then it can be moved prior to the comparison.
  8592. }
  8593. Result := False;
  8594. if not TrySwapMovOp(p, hp1) then
  8595. Exit;
  8596. if taicpu(hp1).opcode = A_LEA then
  8597. { The flags will be overwritten by the CMP/TEST instruction }
  8598. ConvertLEA(taicpu(hp1));
  8599. Result := True;
  8600. { Can we move it one further back? }
  8601. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8602. { Check to see if CMP/TEST is a comparison against zero }
  8603. (
  8604. (
  8605. (taicpu(p).opcode = A_CMP) and
  8606. MatchOperand(taicpu(p).oper[0]^, 0)
  8607. ) or
  8608. (
  8609. (taicpu(p).opcode = A_TEST) and
  8610. (
  8611. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8612. MatchOperand(taicpu(p).oper[0]^, -1)
  8613. )
  8614. )
  8615. ) and
  8616. { These instructions set the zero flag if the result is zero }
  8617. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8618. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8619. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8620. TrySwapMovOp(hp2, hp1);
  8621. end;
  8622. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  8623. var
  8624. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  8625. JumpLabel: TAsmLabel;
  8626. TmpBool: Boolean;
  8627. begin
  8628. Result := False;
  8629. { Look for:
  8630. stc/clc
  8631. j(c) .L1
  8632. ...
  8633. .L1:
  8634. set(n)cb %reg
  8635. (flags deallocated)
  8636. j(c) .L2
  8637. Change to:
  8638. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  8639. j(c) .L2
  8640. }
  8641. p_last := p;
  8642. while GetNextInstruction(p_last, hp1) and
  8643. (hp1.typ = ait_instruction) and
  8644. IsJumpToLabel(taicpu(hp1)) do
  8645. begin
  8646. if DoJumpOptimizations(hp1, TmpBool) then
  8647. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8648. Continue;
  8649. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  8650. if not Assigned(JumpLabel) then
  8651. InternalError(2024012801);
  8652. { Optimise the J(c); stc/clc optimisation first since this will
  8653. get missed if the main optimisation takes place }
  8654. if (taicpu(hp1).opcode = A_JCC) then
  8655. begin
  8656. if GetNextInstruction(hp1, hp2) and
  8657. MatchInstruction(hp2, A_CLC, A_STC, []) and
  8658. TryJccStcClcOpt(hp1, hp2) then
  8659. begin
  8660. Result := True;
  8661. Exit;
  8662. end;
  8663. hp2 := nil; { Suppress compiler warning }
  8664. if (taicpu(hp1).condition in [C_C, C_NC]) and
  8665. { Make sure the flags aren't used again }
  8666. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  8667. begin
  8668. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8669. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  8670. begin
  8671. if (taicpu(p).opcode = A_STC) then
  8672. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  8673. else
  8674. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  8675. MakeUnconditional(taicpu(hp1));
  8676. { Move the jump to after the flag deallocations }
  8677. Asml.Remove(hp1);
  8678. Asml.InsertAfter(hp1, hp2);
  8679. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8680. Result := True;
  8681. Exit;
  8682. end
  8683. else
  8684. begin
  8685. if (taicpu(p).opcode = A_STC) then
  8686. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  8687. else
  8688. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  8689. { In this case, the jump is deterministic in that it will never be taken }
  8690. JumpLabel.DecRefs;
  8691. RemoveInstruction(hp1);
  8692. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  8693. Result := True;
  8694. Exit;
  8695. end;
  8696. end;
  8697. end;
  8698. hp2 := nil; { Suppress compiler warning }
  8699. if
  8700. { Make sure the carry flag doesn't appear in the jump conditions }
  8701. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8702. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  8703. GetNextInstruction(hp2, p_dist) and
  8704. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  8705. (taicpu(p_dist).condition in [C_C, C_NC]) then
  8706. begin
  8707. case taicpu(p_dist).opcode of
  8708. A_Jcc:
  8709. begin
  8710. if DoJumpOptimizations(p_dist, TmpBool) then
  8711. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8712. Continue;
  8713. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8714. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  8715. begin
  8716. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  8717. JumpLabel.decrefs;
  8718. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  8719. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8720. Result := True;
  8721. Exit;
  8722. end
  8723. else if GetNextInstruction(p_dist, hp1_dist) and
  8724. (hp1_dist.typ = ait_label) then
  8725. begin
  8726. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  8727. JumpLabel.decrefs;
  8728. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  8729. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8730. Result := True;
  8731. Exit;
  8732. end;
  8733. end;
  8734. A_SETcc:
  8735. if { Make sure the flags aren't used again }
  8736. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  8737. GetNextInstruction(hp2, hp1_dist) and
  8738. (hp1_dist.typ = ait_instruction) and
  8739. IsJumpToLabel(taicpu(hp1_dist)) and
  8740. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8741. { This works if hp1_dist or both are regular JMP instructions }
  8742. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  8743. (
  8744. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  8745. { Make sure the register isn't still in use, otherwise it
  8746. may get corrupted (fixes #40659) }
  8747. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  8748. ) then
  8749. begin
  8750. taicpu(p).allocate_oper(2);
  8751. taicpu(p).ops := 2;
  8752. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  8753. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  8754. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  8755. taicpu(p).opcode := A_MOV;
  8756. taicpu(p).opsize := S_B;
  8757. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8758. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  8759. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  8760. JumpLabel.decrefs;
  8761. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  8762. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  8763. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  8764. (tai_regalloc(hp2).ratype = ra_alloc) then
  8765. begin
  8766. Asml.Remove(hp2);
  8767. Asml.InsertAfter(hp2, p);
  8768. end;
  8769. Result := True;
  8770. Exit;
  8771. end;
  8772. else
  8773. ;
  8774. end;
  8775. end;
  8776. p_last := hp1;
  8777. end;
  8778. end;
  8779. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  8780. var
  8781. hp2, hp3: tai;
  8782. TempBool: Boolean;
  8783. begin
  8784. Result := False;
  8785. {
  8786. j(c) .L1
  8787. stc/clc
  8788. .L1:
  8789. jc/jnc .L2
  8790. (Flags deallocated)
  8791. Change to:
  8792. j)c) .L1
  8793. jmp .L2
  8794. .L1:
  8795. jc/jnc .L2
  8796. Then call DoJumpOptimizations to convert to:
  8797. j(nc) .L2
  8798. .L1: (may become a dead label)
  8799. jc/jnc .L2
  8800. }
  8801. if GetNextInstruction(hp1, hp2) and
  8802. (hp2.typ = ait_label) and
  8803. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  8804. GetNextInstruction(hp2, hp3) and
  8805. MatchInstruction(hp3, A_Jcc, []) and
  8806. (
  8807. (
  8808. (taicpu(hp3).condition = C_C) and
  8809. (taicpu(hp1).opcode = A_STC)
  8810. ) or (
  8811. (taicpu(hp3).condition = C_NC) and
  8812. (taicpu(hp1).opcode = A_CLC)
  8813. )
  8814. ) and
  8815. { Make sure the flags aren't used again }
  8816. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  8817. begin
  8818. taicpu(hp1).allocate_oper(1);
  8819. taicpu(hp1).ops := 1;
  8820. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  8821. taicpu(hp1).opcode := A_JMP;
  8822. taicpu(hp1).is_jmp := True;
  8823. TempBool := True; { Prevent compiler warnings }
  8824. if DoJumpOptimizations(p, TempBool) then
  8825. Result := True
  8826. else
  8827. Include(OptsToCheck, aoc_ForceNewIteration);
  8828. end;
  8829. end;
  8830. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  8831. begin
  8832. { This generally only executes under -O3 and above }
  8833. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  8834. end;
  8835. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  8836. var
  8837. hp1, hp2: tai;
  8838. FoundComparison: Boolean;
  8839. begin
  8840. { Run the pass 1 optimisations as well, since they may have some effect
  8841. after the CMOV blocks are created in OptPass2Jcc }
  8842. Result := False;
  8843. { Result := OptPass1CMOVcc(p);
  8844. if Result then
  8845. Exit;}
  8846. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  8847. and make a slightly inefficent result on branching-type blocks, notably
  8848. when setting a function result then jumping to the function epilogue.
  8849. In this case, change:
  8850. cmov(c) %reg1,%reg2
  8851. j(c) @lbl
  8852. (%reg2 deallocated)
  8853. To:
  8854. mov %reg11,%reg2
  8855. j(c) @lbl
  8856. Note, we can't use GetNextInstructionUsingReg to find the conditional
  8857. jump because if it's not present, we may end up with a jump that's
  8858. completely unrelated.
  8859. }
  8860. hp1 := p;
  8861. while GetNextInstruction(hp1, hp1) and
  8862. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  8863. if (hp1.typ = ait_instruction) and
  8864. (taicpu(hp1).opcode = A_Jcc) and
  8865. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  8866. begin
  8867. TransferUsedRegs(TmpUsedRegs);
  8868. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  8869. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  8870. (
  8871. { See if we can find a more distant instruction that overwrites
  8872. the destination register }
  8873. (cs_opt_level3 in current_settings.optimizerswitches) and
  8874. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8875. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  8876. ) then
  8877. begin
  8878. if (taicpu(p).oper[0]^.typ = top_reg) then
  8879. begin
  8880. { Search backwards to see if the source register is set to a
  8881. constant }
  8882. FoundComparison := False;
  8883. hp1 := p;
  8884. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  8885. begin
  8886. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  8887. begin
  8888. FoundComparison := True;
  8889. Continue;
  8890. end;
  8891. { Once we find the CMP, TEST or similar instruction, we
  8892. have to stop if we find anything other than a MOV }
  8893. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  8894. Break;
  8895. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  8896. { Destination register was modified }
  8897. Break;
  8898. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  8899. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  8900. begin
  8901. { Found a constant! }
  8902. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  8903. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  8904. { The source register is no longer in use }
  8905. RemoveInstruction(hp1);
  8906. Break;
  8907. end;
  8908. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  8909. { Some other instruction has modified the source register }
  8910. Break;
  8911. end;
  8912. end;
  8913. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  8914. taicpu(p).opcode := A_MOV;
  8915. taicpu(p).condition := C_None;
  8916. { Rely on the post peephole stage to put the MOV before the
  8917. CMP/TEST instruction that appears prior }
  8918. Result := True;
  8919. Exit;
  8920. end;
  8921. end;
  8922. end;
  8923. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8924. function IsXCHGAcceptable: Boolean; inline;
  8925. begin
  8926. { Always accept if optimising for size }
  8927. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8928. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8929. than 3, so it becomes a saving compared to three MOVs with two of
  8930. them able to execute simultaneously. [Kit] }
  8931. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8932. end;
  8933. var
  8934. NewRef: TReference;
  8935. hp1, hp2, hp3, hp4: Tai;
  8936. {$ifndef x86_64}
  8937. OperIdx: Integer;
  8938. {$endif x86_64}
  8939. NewInstr : Taicpu;
  8940. NewAligh : Tai_align;
  8941. DestLabel: TAsmLabel;
  8942. TempTracking: TAllUsedRegs;
  8943. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8944. var
  8945. NextInstr: tai;
  8946. begin
  8947. Result := False;
  8948. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8949. if not GetNextInstruction(InputInstr, NextInstr) or
  8950. (
  8951. { The FLAGS register isn't always tracked properly, so do not
  8952. perform this optimisation if a conditional statement follows }
  8953. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8954. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8955. ) then
  8956. begin
  8957. reference_reset(NewRef, 1, []);
  8958. NewRef.base := taicpu(p).oper[0]^.reg;
  8959. NewRef.scalefactor := 1;
  8960. if taicpu(InputInstr).opcode = A_ADD then
  8961. begin
  8962. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8963. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8964. end
  8965. else
  8966. begin
  8967. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8968. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8969. end;
  8970. taicpu(p).opcode := A_LEA;
  8971. taicpu(p).loadref(0, NewRef);
  8972. RemoveInstruction(InputInstr);
  8973. Result := True;
  8974. end;
  8975. end;
  8976. begin
  8977. Result:=false;
  8978. { This optimisation adds an instruction, so only do it for speed }
  8979. if not (cs_opt_size in current_settings.optimizerswitches) and
  8980. MatchOpType(taicpu(p), top_const, top_reg) and
  8981. (taicpu(p).oper[0]^.val = 0) then
  8982. begin
  8983. { To avoid compiler warning }
  8984. DestLabel := nil;
  8985. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8986. InternalError(2021040750);
  8987. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8988. Exit;
  8989. case hp1.typ of
  8990. ait_label:
  8991. begin
  8992. { Change:
  8993. mov $0,%reg mov $0,%reg
  8994. @Lbl1: @Lbl1:
  8995. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8996. je @Lbl2 jne @Lbl2
  8997. To: To:
  8998. mov $0,%reg mov $0,%reg
  8999. jmp @Lbl2 jmp @Lbl3
  9000. (align) (align)
  9001. @Lbl1: @Lbl1:
  9002. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9003. je @Lbl2 je @Lbl2
  9004. @Lbl3: <-- Only if label exists
  9005. (Not if it's optimised for size)
  9006. }
  9007. if not GetNextInstruction(hp1, hp2) then
  9008. Exit;
  9009. if (hp2.typ = ait_instruction) and
  9010. (
  9011. { Register sizes must exactly match }
  9012. (
  9013. (taicpu(hp2).opcode = A_CMP) and
  9014. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9015. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9016. ) or (
  9017. (taicpu(hp2).opcode = A_TEST) and
  9018. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9019. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9020. )
  9021. ) and GetNextInstruction(hp2, hp3) and
  9022. (hp3.typ = ait_instruction) and
  9023. (taicpu(hp3).opcode = A_JCC) and
  9024. (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
  9025. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9026. begin
  9027. { Check condition of jump }
  9028. { Always true? }
  9029. if condition_in(C_E, taicpu(hp3).condition) then
  9030. begin
  9031. { Copy label symbol and obtain matching label entry for the
  9032. conditional jump, as this will be our destination}
  9033. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9034. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9035. Result := True;
  9036. end
  9037. { Always false? }
  9038. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9039. begin
  9040. { This is only worth it if there's a jump to take }
  9041. case hp2.typ of
  9042. ait_instruction:
  9043. begin
  9044. if taicpu(hp2).opcode = A_JMP then
  9045. begin
  9046. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9047. { An unconditional jump follows the conditional jump which will always be false,
  9048. so use this jump's destination for the new jump }
  9049. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9050. Result := True;
  9051. end
  9052. else if taicpu(hp2).opcode = A_JCC then
  9053. begin
  9054. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9055. if condition_in(C_E, taicpu(hp2).condition) then
  9056. begin
  9057. { A second conditional jump follows the conditional jump which will always be false,
  9058. while the second jump is always True, so use this jump's destination for the new jump }
  9059. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9060. Result := True;
  9061. end;
  9062. { Don't risk it if the jump isn't always true (Result remains False) }
  9063. end;
  9064. end;
  9065. else
  9066. { If anything else don't optimise };
  9067. end;
  9068. end;
  9069. if Result then
  9070. begin
  9071. { Just so we have something to insert as a paremeter}
  9072. reference_reset(NewRef, 1, []);
  9073. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9074. { Now actually load the correct parameter (this also
  9075. increases the reference count) }
  9076. NewInstr.loadsymbol(0, DestLabel, 0);
  9077. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9078. begin
  9079. { Get instruction before original label (may not be p under -O3) }
  9080. if not GetLastInstruction(hp1, hp2) then
  9081. { Shouldn't fail here }
  9082. InternalError(2021040701);
  9083. end
  9084. else
  9085. hp2 := p;
  9086. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9087. AsmL.InsertAfter(NewInstr, hp2);
  9088. { Add new alignment field }
  9089. (* AsmL.InsertAfter(
  9090. cai_align.create_max(
  9091. current_settings.alignment.jumpalign,
  9092. current_settings.alignment.jumpalignskipmax
  9093. ),
  9094. NewInstr
  9095. ); *)
  9096. end;
  9097. Exit;
  9098. end;
  9099. end;
  9100. else
  9101. ;
  9102. end;
  9103. end;
  9104. if not GetNextInstruction(p, hp1) then
  9105. Exit;
  9106. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9107. begin
  9108. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9109. begin
  9110. Result := True;
  9111. Exit;
  9112. end;
  9113. { This optimisation is only effective on a second run of Pass 2,
  9114. hence -O3 or above.
  9115. Change:
  9116. mov %reg1,%reg2
  9117. cmp/test (contains %reg1)
  9118. mov x, %reg1
  9119. (another mov or a j(c))
  9120. To:
  9121. mov %reg1,%reg2
  9122. mov x, %reg1
  9123. cmp (%reg1 replaced with %reg2)
  9124. (another mov or a j(c))
  9125. The requirement of an additional MOV or a jump ensures there
  9126. isn't performance loss, since a j(c) will permit macro-fusion
  9127. with the cmp instruction, while another MOV likely means it's
  9128. not all being executed in a single cycle due to parallelisation.
  9129. }
  9130. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9131. MatchOpType(taicpu(p), top_reg, top_reg) and
  9132. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9133. GetNextInstruction(hp1, hp2) and
  9134. MatchInstruction(hp2, A_MOV, []) and
  9135. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9136. { Registers don't have to be the same size in this case }
  9137. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9138. GetNextInstruction(hp2, hp3) and
  9139. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9140. { Make sure the operands in the camparison can be safely replaced }
  9141. (
  9142. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9143. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9144. ) and
  9145. (
  9146. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9147. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9148. ) then
  9149. begin
  9150. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9151. AsmL.Remove(hp2);
  9152. AsmL.InsertAfter(hp2, p);
  9153. Result := True;
  9154. Exit;
  9155. end;
  9156. end;
  9157. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9158. begin
  9159. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9160. further, but we can't just put this jump optimisation in pass 1
  9161. because it tends to perform worse when conditional jumps are
  9162. nearby (e.g. when converting CMOV instructions). [Kit] }
  9163. CopyUsedRegs(TempTracking);
  9164. UpdateUsedRegs(tai(p.Next));
  9165. if OptPass2JMP(hp1) then
  9166. begin
  9167. { Restore register state }
  9168. RestoreUsedRegs(TempTracking);
  9169. ReleaseUsedRegs(TempTracking);
  9170. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9171. OptPass1MOV(p);
  9172. Result := True;
  9173. Exit;
  9174. end;
  9175. { If OptPass2JMP returned False, no optimisations were done to
  9176. the jump and there are no further optimisations that can be done
  9177. to the MOV instruction on this pass other than FuncMov2Func }
  9178. { Restore register state }
  9179. RestoreUsedRegs(TempTracking);
  9180. ReleaseUsedRegs(TempTracking);
  9181. Result := FuncMov2Func(p, hp1);
  9182. Exit;
  9183. end;
  9184. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9185. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9186. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9187. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9188. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9189. begin
  9190. { Change:
  9191. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9192. addl/q $x,%reg2 subl/q $x,%reg2
  9193. To:
  9194. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9195. }
  9196. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9197. { be lazy, checking separately for sub would be slightly better }
  9198. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9199. begin
  9200. TransferUsedRegs(TmpUsedRegs);
  9201. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9202. if TryMovArith2Lea(hp1) then
  9203. begin
  9204. Result := True;
  9205. Exit;
  9206. end
  9207. end
  9208. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9209. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9210. { Same as above, but also adds or subtracts to %reg2 in between.
  9211. It's still valid as long as the flags aren't in use }
  9212. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9213. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9214. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9215. { be lazy, checking separately for sub would be slightly better }
  9216. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9217. begin
  9218. TransferUsedRegs(TmpUsedRegs);
  9219. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9220. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9221. if TryMovArith2Lea(hp2) then
  9222. begin
  9223. Result := True;
  9224. Exit;
  9225. end;
  9226. end;
  9227. end;
  9228. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9229. {$ifdef x86_64}
  9230. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9231. {$else x86_64}
  9232. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9233. {$endif x86_64}
  9234. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9235. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9236. { mov reg1, reg2 mov reg1, reg2
  9237. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9238. begin
  9239. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9240. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9241. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9242. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9243. TransferUsedRegs(TmpUsedRegs);
  9244. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9245. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9246. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9247. then
  9248. begin
  9249. RemoveCurrentP(p, hp1);
  9250. Result:=true;
  9251. end;
  9252. Exit;
  9253. end;
  9254. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9255. IsXCHGAcceptable and
  9256. { XCHG doesn't support 8-bit registers }
  9257. (taicpu(p).opsize <> S_B) and
  9258. MatchInstruction(hp1, A_MOV, []) and
  9259. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9260. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9261. GetNextInstruction(hp1, hp2) and
  9262. MatchInstruction(hp2, A_MOV, []) and
  9263. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9264. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9265. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9266. begin
  9267. { mov %reg1,%reg2
  9268. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9269. mov %reg2,%reg3
  9270. (%reg2 not used afterwards)
  9271. Note that xchg takes 3 cycles to execute, and generally mov's take
  9272. only one cycle apiece, but the first two mov's can be executed in
  9273. parallel, only taking 2 cycles overall. Older processors should
  9274. therefore only optimise for size. [Kit]
  9275. }
  9276. TransferUsedRegs(TmpUsedRegs);
  9277. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9278. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9279. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9280. begin
  9281. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9282. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9283. taicpu(hp1).opcode := A_XCHG;
  9284. RemoveCurrentP(p, hp1);
  9285. RemoveInstruction(hp2);
  9286. Result := True;
  9287. Exit;
  9288. end;
  9289. end;
  9290. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9291. MatchInstruction(hp1, A_SAR, []) then
  9292. begin
  9293. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9294. begin
  9295. { the use of %edx also covers the opsize being S_L }
  9296. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9297. begin
  9298. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9299. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9300. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9301. begin
  9302. { Change:
  9303. movl %eax,%edx
  9304. sarl $31,%edx
  9305. To:
  9306. cltd
  9307. }
  9308. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9309. RemoveInstruction(hp1);
  9310. taicpu(p).opcode := A_CDQ;
  9311. taicpu(p).opsize := S_NO;
  9312. taicpu(p).clearop(1);
  9313. taicpu(p).clearop(0);
  9314. taicpu(p).ops:=0;
  9315. Result := True;
  9316. Exit;
  9317. end
  9318. else if (cs_opt_size in current_settings.optimizerswitches) and
  9319. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9320. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9321. begin
  9322. { Change:
  9323. movl %edx,%eax
  9324. sarl $31,%edx
  9325. To:
  9326. movl %edx,%eax
  9327. cltd
  9328. Note that this creates a dependency between the two instructions,
  9329. so only perform if optimising for size.
  9330. }
  9331. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9332. taicpu(hp1).opcode := A_CDQ;
  9333. taicpu(hp1).opsize := S_NO;
  9334. taicpu(hp1).clearop(1);
  9335. taicpu(hp1).clearop(0);
  9336. taicpu(hp1).ops:=0;
  9337. Include(OptsToCheck, aoc_ForceNewIteration);
  9338. Exit;
  9339. end;
  9340. {$ifndef x86_64}
  9341. end
  9342. { Don't bother if CMOV is supported, because a more optimal
  9343. sequence would have been generated for the Abs() intrinsic }
  9344. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9345. { the use of %eax also covers the opsize being S_L }
  9346. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9347. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9348. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9349. GetNextInstruction(hp1, hp2) and
  9350. MatchInstruction(hp2, A_XOR, [S_L]) and
  9351. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9352. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9353. GetNextInstruction(hp2, hp3) and
  9354. MatchInstruction(hp3, A_SUB, [S_L]) and
  9355. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9356. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9357. begin
  9358. { Change:
  9359. movl %eax,%edx
  9360. sarl $31,%eax
  9361. xorl %eax,%edx
  9362. subl %eax,%edx
  9363. (Instruction that uses %edx)
  9364. (%eax deallocated)
  9365. (%edx deallocated)
  9366. To:
  9367. cltd
  9368. xorl %edx,%eax <-- Note the registers have swapped
  9369. subl %edx,%eax
  9370. (Instruction that uses %eax) <-- %eax rather than %edx
  9371. }
  9372. TransferUsedRegs(TmpUsedRegs);
  9373. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9374. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9375. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9376. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9377. begin
  9378. if GetNextInstruction(hp3, hp4) and
  9379. not RegModifiedByInstruction(NR_EDX, hp4) and
  9380. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9381. begin
  9382. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9383. taicpu(p).opcode := A_CDQ;
  9384. taicpu(p).clearop(1);
  9385. taicpu(p).clearop(0);
  9386. taicpu(p).ops:=0;
  9387. RemoveInstruction(hp1);
  9388. taicpu(hp2).loadreg(0, NR_EDX);
  9389. taicpu(hp2).loadreg(1, NR_EAX);
  9390. taicpu(hp3).loadreg(0, NR_EDX);
  9391. taicpu(hp3).loadreg(1, NR_EAX);
  9392. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9393. { Convert references in the following instruction (hp4) from %edx to %eax }
  9394. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9395. with taicpu(hp4).oper[OperIdx]^ do
  9396. case typ of
  9397. top_reg:
  9398. if getsupreg(reg) = RS_EDX then
  9399. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9400. top_ref:
  9401. begin
  9402. if getsupreg(reg) = RS_EDX then
  9403. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9404. if getsupreg(reg) = RS_EDX then
  9405. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9406. end;
  9407. else
  9408. ;
  9409. end;
  9410. Result := True;
  9411. Exit;
  9412. end;
  9413. end;
  9414. {$else x86_64}
  9415. end;
  9416. end
  9417. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9418. { the use of %rdx also covers the opsize being S_Q }
  9419. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9420. begin
  9421. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9422. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9423. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9424. begin
  9425. { Change:
  9426. movq %rax,%rdx
  9427. sarq $63,%rdx
  9428. To:
  9429. cqto
  9430. }
  9431. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9432. RemoveInstruction(hp1);
  9433. taicpu(p).opcode := A_CQO;
  9434. taicpu(p).opsize := S_NO;
  9435. taicpu(p).clearop(1);
  9436. taicpu(p).clearop(0);
  9437. taicpu(p).ops:=0;
  9438. Result := True;
  9439. Exit;
  9440. end
  9441. else if (cs_opt_size in current_settings.optimizerswitches) and
  9442. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9443. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9444. begin
  9445. { Change:
  9446. movq %rdx,%rax
  9447. sarq $63,%rdx
  9448. To:
  9449. movq %rdx,%rax
  9450. cqto
  9451. Note that this creates a dependency between the two instructions,
  9452. so only perform if optimising for size.
  9453. }
  9454. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9455. taicpu(hp1).opcode := A_CQO;
  9456. taicpu(hp1).opsize := S_NO;
  9457. taicpu(hp1).clearop(1);
  9458. taicpu(hp1).clearop(0);
  9459. taicpu(hp1).ops:=0;
  9460. Include(OptsToCheck, aoc_ForceNewIteration);
  9461. Exit;
  9462. {$endif x86_64}
  9463. end;
  9464. end;
  9465. end;
  9466. if MatchInstruction(hp1, A_MOV, []) and
  9467. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9468. { Though "GetNextInstruction" could be factored out, along with
  9469. the instructions that depend on hp2, it is an expensive call that
  9470. should be delayed for as long as possible, hence we do cheaper
  9471. checks first that are likely to be False. [Kit] }
  9472. begin
  9473. if (
  9474. (
  9475. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9476. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9477. (
  9478. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9479. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9480. )
  9481. ) or
  9482. (
  9483. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9484. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9485. (
  9486. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9487. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9488. )
  9489. )
  9490. ) and
  9491. GetNextInstruction(hp1, hp2) and
  9492. MatchInstruction(hp2, A_SAR, []) and
  9493. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9494. begin
  9495. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9496. begin
  9497. { Change:
  9498. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9499. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9500. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9501. To:
  9502. movl r/m,%eax <- Note the change in register
  9503. cltd
  9504. }
  9505. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9506. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9507. taicpu(p).loadreg(1, NR_EAX);
  9508. taicpu(hp1).opcode := A_CDQ;
  9509. taicpu(hp1).clearop(1);
  9510. taicpu(hp1).clearop(0);
  9511. taicpu(hp1).ops:=0;
  9512. RemoveInstruction(hp2);
  9513. Include(OptsToCheck, aoc_ForceNewIteration);
  9514. (*
  9515. {$ifdef x86_64}
  9516. end
  9517. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9518. { This code sequence does not get generated - however it might become useful
  9519. if and when 128-bit signed integer types make an appearance, so the code
  9520. is kept here for when it is eventually needed. [Kit] }
  9521. (
  9522. (
  9523. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9524. (
  9525. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9526. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9527. )
  9528. ) or
  9529. (
  9530. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9531. (
  9532. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9533. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9534. )
  9535. )
  9536. ) and
  9537. GetNextInstruction(hp1, hp2) and
  9538. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9539. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9540. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9541. begin
  9542. { Change:
  9543. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9544. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9545. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9546. To:
  9547. movq r/m,%rax <- Note the change in register
  9548. cqto
  9549. }
  9550. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9551. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9552. taicpu(p).loadreg(1, NR_RAX);
  9553. taicpu(hp1).opcode := A_CQO;
  9554. taicpu(hp1).clearop(1);
  9555. taicpu(hp1).clearop(0);
  9556. taicpu(hp1).ops:=0;
  9557. RemoveInstruction(hp2);
  9558. Include(OptsToCheck, aoc_ForceNewIteration);
  9559. {$endif x86_64}
  9560. *)
  9561. end;
  9562. end;
  9563. {$ifdef x86_64}
  9564. end;
  9565. if (taicpu(p).opsize = S_L) and
  9566. (taicpu(p).oper[1]^.typ = top_reg) and
  9567. (
  9568. MatchInstruction(hp1, A_MOV,[]) and
  9569. (taicpu(hp1).opsize = S_L) and
  9570. (taicpu(hp1).oper[1]^.typ = top_reg)
  9571. ) and (
  9572. GetNextInstruction(hp1, hp2) and
  9573. (tai(hp2).typ=ait_instruction) and
  9574. (taicpu(hp2).opsize = S_Q) and
  9575. (
  9576. (
  9577. MatchInstruction(hp2, A_ADD,[]) and
  9578. (taicpu(hp2).opsize = S_Q) and
  9579. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9580. (
  9581. (
  9582. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9583. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9584. ) or (
  9585. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9586. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9587. )
  9588. )
  9589. ) or (
  9590. MatchInstruction(hp2, A_LEA,[]) and
  9591. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9592. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9593. (
  9594. (
  9595. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9596. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9597. ) or (
  9598. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9599. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9600. )
  9601. ) and (
  9602. (
  9603. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9604. ) or (
  9605. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9606. )
  9607. )
  9608. )
  9609. )
  9610. ) and (
  9611. GetNextInstruction(hp2, hp3) and
  9612. MatchInstruction(hp3, A_SHR,[]) and
  9613. (taicpu(hp3).opsize = S_Q) and
  9614. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9615. (taicpu(hp3).oper[0]^.val = 1) and
  9616. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9617. ) then
  9618. begin
  9619. { Change movl x, reg1d movl x, reg1d
  9620. movl y, reg2d movl y, reg2d
  9621. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9622. shrq $1, reg1q shrq $1, reg1q
  9623. ( reg1d and reg2d can be switched around in the first two instructions )
  9624. To movl x, reg1d
  9625. addl y, reg1d
  9626. rcrl $1, reg1d
  9627. This corresponds to the common expression (x + y) shr 1, where
  9628. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9629. smaller code, but won't account for x + y causing an overflow). [Kit]
  9630. }
  9631. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9632. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9633. begin
  9634. { Change first MOV command to have the same register as the final output }
  9635. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  9636. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  9637. Result := True;
  9638. end
  9639. else
  9640. begin
  9641. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9642. Include(OptsToCheck, aoc_ForceNewIteration);
  9643. end;
  9644. { Change second MOV command to an ADD command. This is easier than
  9645. converting the existing command because it means we don't have to
  9646. touch 'y', which might be a complicated reference, and also the
  9647. fact that the third command might either be ADD or LEA. [Kit] }
  9648. taicpu(hp1).opcode := A_ADD;
  9649. { Delete old ADD/LEA instruction }
  9650. RemoveInstruction(hp2);
  9651. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9652. taicpu(hp3).opcode := A_RCR;
  9653. taicpu(hp3).changeopsize(S_L);
  9654. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9655. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  9656. called, so FuncMov2Func below is safe to call }
  9657. {$endif x86_64}
  9658. end;
  9659. if FuncMov2Func(p, hp1) then
  9660. begin
  9661. Result := True;
  9662. Exit;
  9663. end;
  9664. end;
  9665. {$push}
  9666. {$q-}{$r-}
  9667. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9668. var
  9669. ThisReg: TRegister;
  9670. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9671. TargetSubReg: TSubRegister;
  9672. hp1, hp2: tai;
  9673. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9674. { Store list of found instructions so we don't have to call
  9675. GetNextInstructionUsingReg multiple times }
  9676. InstrList: array of taicpu;
  9677. InstrMax, Index: Integer;
  9678. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9679. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9680. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9681. WorkingValue: TCgInt;
  9682. PreMessage: string;
  9683. { Data flow analysis }
  9684. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9685. BitwiseOnly, OrXorUsed,
  9686. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9687. function CheckOverflowConditions: Boolean;
  9688. begin
  9689. Result := True;
  9690. if (TestValSignedMax > SignedUpperLimit) then
  9691. UpperSignedOverflow := True;
  9692. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9693. LowerSignedOverflow := True;
  9694. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9695. LowerUnsignedOverflow := True;
  9696. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9697. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9698. begin
  9699. { Absolute overflow }
  9700. Result := False;
  9701. Exit;
  9702. end;
  9703. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9704. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9705. ShiftDownOverflow := True;
  9706. if (TestValMin < 0) or (TestValMax < 0) then
  9707. begin
  9708. LowerUnsignedOverflow := True;
  9709. UpperUnsignedOverflow := True;
  9710. end;
  9711. end;
  9712. function AdjustInitialLoadAndSize: Boolean;
  9713. begin
  9714. Result := False;
  9715. if not p_removed then
  9716. begin
  9717. if TargetSize = MinSize then
  9718. begin
  9719. { Convert the input MOVZX to a MOV }
  9720. if (taicpu(p).oper[0]^.typ = top_reg) and
  9721. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9722. begin
  9723. { Or remove it completely! }
  9724. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9725. RemoveCurrentP(p);
  9726. p_removed := True;
  9727. end
  9728. else
  9729. begin
  9730. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9731. taicpu(p).opcode := A_MOV;
  9732. taicpu(p).oper[1]^.reg := ThisReg;
  9733. taicpu(p).opsize := TargetSize;
  9734. end;
  9735. Result := True;
  9736. end
  9737. else if TargetSize <> MaxSize then
  9738. begin
  9739. case MaxSize of
  9740. S_L:
  9741. if TargetSize = S_W then
  9742. begin
  9743. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9744. taicpu(p).opsize := S_BW;
  9745. taicpu(p).oper[1]^.reg := ThisReg;
  9746. Result := True;
  9747. end
  9748. else
  9749. InternalError(2020112341);
  9750. S_W:
  9751. if TargetSize = S_L then
  9752. begin
  9753. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9754. taicpu(p).opsize := S_BL;
  9755. taicpu(p).oper[1]^.reg := ThisReg;
  9756. Result := True;
  9757. end
  9758. else
  9759. InternalError(2020112342);
  9760. else
  9761. ;
  9762. end;
  9763. end
  9764. else if not hp1_removed and not RegInUse then
  9765. begin
  9766. { If we have something like:
  9767. movzbl (oper),%regd
  9768. add x, %regd
  9769. movzbl %regb, %regd
  9770. We can reduce the register size to the input of the final
  9771. movzbl instruction. Overflows won't have any effect.
  9772. }
  9773. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9774. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9775. begin
  9776. TargetSize := S_B;
  9777. setsubreg(ThisReg, R_SUBL);
  9778. Result := True;
  9779. end
  9780. else if (taicpu(p).opsize = S_WL) and
  9781. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9782. begin
  9783. TargetSize := S_W;
  9784. setsubreg(ThisReg, R_SUBW);
  9785. Result := True;
  9786. end;
  9787. if Result then
  9788. begin
  9789. { Convert the input MOVZX to a MOV }
  9790. if (taicpu(p).oper[0]^.typ = top_reg) and
  9791. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9792. begin
  9793. { Or remove it completely! }
  9794. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9795. RemoveCurrentP(p);
  9796. p_removed := True;
  9797. end
  9798. else
  9799. begin
  9800. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9801. taicpu(p).opcode := A_MOV;
  9802. taicpu(p).oper[1]^.reg := ThisReg;
  9803. taicpu(p).opsize := TargetSize;
  9804. end;
  9805. end;
  9806. end;
  9807. end;
  9808. end;
  9809. procedure AdjustFinalLoad;
  9810. begin
  9811. if not LowerUnsignedOverflow then
  9812. begin
  9813. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9814. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9815. begin
  9816. { Convert the output MOVZX to a MOV }
  9817. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9818. begin
  9819. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9820. if (MinSize = S_B) or
  9821. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9822. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9823. begin
  9824. { Remove it completely! }
  9825. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9826. { Be careful; if p = hp1 and p was also removed, p
  9827. will become a dangling pointer }
  9828. if p = hp1 then
  9829. begin
  9830. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9831. p_removed := True;
  9832. end
  9833. else
  9834. RemoveInstruction(hp1);
  9835. hp1_removed := True;
  9836. end;
  9837. end
  9838. else
  9839. begin
  9840. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9841. taicpu(hp1).opcode := A_MOV;
  9842. taicpu(hp1).oper[0]^.reg := ThisReg;
  9843. taicpu(hp1).opsize := TargetSize;
  9844. end;
  9845. end
  9846. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9847. begin
  9848. { Need to change the size of the output }
  9849. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9850. taicpu(hp1).oper[0]^.reg := ThisReg;
  9851. taicpu(hp1).opsize := S_BL;
  9852. end;
  9853. end;
  9854. end;
  9855. function CompressInstructions: Boolean;
  9856. var
  9857. LocalIndex: Integer;
  9858. begin
  9859. Result := False;
  9860. { The objective here is to try to find a combination that
  9861. removes one of the MOV/Z instructions. }
  9862. if (
  9863. (taicpu(p).oper[0]^.typ <> top_reg) or
  9864. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9865. ) and
  9866. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9867. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9868. begin
  9869. { Make a preference to remove the second MOVZX instruction }
  9870. case taicpu(hp1).opsize of
  9871. S_BL, S_WL:
  9872. begin
  9873. TargetSize := S_L;
  9874. TargetSubReg := R_SUBD;
  9875. end;
  9876. S_BW:
  9877. begin
  9878. TargetSize := S_W;
  9879. TargetSubReg := R_SUBW;
  9880. end;
  9881. else
  9882. InternalError(2020112302);
  9883. end;
  9884. end
  9885. else
  9886. begin
  9887. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9888. begin
  9889. { Exceeded lower bound but not upper bound }
  9890. TargetSize := MaxSize;
  9891. end
  9892. else if not LowerUnsignedOverflow then
  9893. begin
  9894. { Size didn't exceed lower bound }
  9895. TargetSize := MinSize;
  9896. end
  9897. else
  9898. Exit;
  9899. end;
  9900. case TargetSize of
  9901. S_B:
  9902. TargetSubReg := R_SUBL;
  9903. S_W:
  9904. TargetSubReg := R_SUBW;
  9905. S_L:
  9906. TargetSubReg := R_SUBD;
  9907. else
  9908. InternalError(2020112350);
  9909. end;
  9910. { Update the register to its new size }
  9911. setsubreg(ThisReg, TargetSubReg);
  9912. RegInUse := False;
  9913. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9914. begin
  9915. { Check to see if the active register is used afterwards;
  9916. if not, we can change it and make a saving. }
  9917. TransferUsedRegs(TmpUsedRegs);
  9918. { The target register may be marked as in use to cross
  9919. a jump to a distant label, so exclude it }
  9920. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9921. hp2 := p;
  9922. repeat
  9923. { Explicitly check for the excluded register (don't include the first
  9924. instruction as it may be reading from here }
  9925. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9926. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9927. begin
  9928. RegInUse := True;
  9929. Break;
  9930. end;
  9931. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9932. if not GetNextInstruction(hp2, hp2) then
  9933. InternalError(2020112340);
  9934. until (hp2 = hp1);
  9935. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9936. { We might still be able to get away with this }
  9937. RegInUse := not
  9938. (
  9939. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9940. (hp2.typ = ait_instruction) and
  9941. (
  9942. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9943. instruction that doesn't actually contain ThisReg }
  9944. (cs_opt_level3 in current_settings.optimizerswitches) or
  9945. RegInInstruction(ThisReg, hp2)
  9946. ) and
  9947. RegLoadedWithNewValue(ThisReg, hp2)
  9948. );
  9949. if not RegInUse then
  9950. begin
  9951. { Force the register size to the same as this instruction so it can be removed}
  9952. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9953. begin
  9954. TargetSize := S_L;
  9955. TargetSubReg := R_SUBD;
  9956. end
  9957. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9958. begin
  9959. TargetSize := S_W;
  9960. TargetSubReg := R_SUBW;
  9961. end;
  9962. ThisReg := taicpu(hp1).oper[1]^.reg;
  9963. setsubreg(ThisReg, TargetSubReg);
  9964. RegChanged := True;
  9965. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9966. TransferUsedRegs(TmpUsedRegs);
  9967. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9968. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9969. if p = hp1 then
  9970. begin
  9971. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9972. p_removed := True;
  9973. end
  9974. else
  9975. RemoveInstruction(hp1);
  9976. hp1_removed := True;
  9977. { Instruction will become "mov %reg,%reg" }
  9978. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9979. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9980. begin
  9981. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9982. RemoveCurrentP(p);
  9983. p_removed := True;
  9984. end
  9985. else
  9986. taicpu(p).oper[1]^.reg := ThisReg;
  9987. Result := True;
  9988. end
  9989. else
  9990. begin
  9991. if TargetSize <> MaxSize then
  9992. begin
  9993. { Since the register is in use, we have to force it to
  9994. MaxSize otherwise part of it may become undefined later on }
  9995. TargetSize := MaxSize;
  9996. case TargetSize of
  9997. S_B:
  9998. TargetSubReg := R_SUBL;
  9999. S_W:
  10000. TargetSubReg := R_SUBW;
  10001. S_L:
  10002. TargetSubReg := R_SUBD;
  10003. else
  10004. InternalError(2020112351);
  10005. end;
  10006. setsubreg(ThisReg, TargetSubReg);
  10007. end;
  10008. AdjustFinalLoad;
  10009. end;
  10010. end
  10011. else
  10012. AdjustFinalLoad;
  10013. Result := AdjustInitialLoadAndSize or Result;
  10014. { Now go through every instruction we found and change the
  10015. size. If TargetSize = MaxSize, then almost no changes are
  10016. needed and Result can remain False if it hasn't been set
  10017. yet.
  10018. If RegChanged is True, then the register requires changing
  10019. and so the point about TargetSize = MaxSize doesn't apply. }
  10020. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10021. begin
  10022. for LocalIndex := 0 to InstrMax do
  10023. begin
  10024. { If p_removed is true, then the original MOV/Z was removed
  10025. and removing the AND instruction may not be safe if it
  10026. appears first }
  10027. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10028. InternalError(2020112310);
  10029. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10030. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10031. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10032. InstrList[LocalIndex].opsize := TargetSize;
  10033. end;
  10034. Result := True;
  10035. end;
  10036. end;
  10037. begin
  10038. Result := False;
  10039. p_removed := False;
  10040. hp1_removed := False;
  10041. ThisReg := taicpu(p).oper[1]^.reg;
  10042. { Check for:
  10043. movs/z ###,%ecx (or %cx or %rcx)
  10044. ...
  10045. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10046. (dealloc %ecx)
  10047. Change to:
  10048. mov ###,%cl (if ### = %cl, then remove completely)
  10049. ...
  10050. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10051. }
  10052. if (getsupreg(ThisReg) = RS_ECX) and
  10053. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10054. (hp1.typ = ait_instruction) and
  10055. (
  10056. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10057. instruction that doesn't actually contain ECX }
  10058. (cs_opt_level3 in current_settings.optimizerswitches) or
  10059. RegInInstruction(NR_ECX, hp1) or
  10060. (
  10061. { It's common for the shift/rotate's read/write register to be
  10062. initialised in between, so under -O2 and under, search ahead
  10063. one more instruction
  10064. }
  10065. GetNextInstruction(hp1, hp1) and
  10066. (hp1.typ = ait_instruction) and
  10067. RegInInstruction(NR_ECX, hp1)
  10068. )
  10069. ) and
  10070. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10071. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10072. begin
  10073. TransferUsedRegs(TmpUsedRegs);
  10074. hp2 := p;
  10075. repeat
  10076. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10077. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10078. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10079. begin
  10080. case taicpu(p).opsize of
  10081. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10082. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10083. begin
  10084. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10085. RemoveCurrentP(p);
  10086. end
  10087. else
  10088. begin
  10089. taicpu(p).opcode := A_MOV;
  10090. taicpu(p).opsize := S_B;
  10091. taicpu(p).oper[1]^.reg := NR_CL;
  10092. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10093. end;
  10094. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10095. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10096. begin
  10097. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10098. RemoveCurrentP(p);
  10099. end
  10100. else
  10101. begin
  10102. taicpu(p).opcode := A_MOV;
  10103. taicpu(p).opsize := S_W;
  10104. taicpu(p).oper[1]^.reg := NR_CX;
  10105. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10106. end;
  10107. {$ifdef x86_64}
  10108. S_LQ:
  10109. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10110. begin
  10111. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10112. RemoveCurrentP(p);
  10113. end
  10114. else
  10115. begin
  10116. taicpu(p).opcode := A_MOV;
  10117. taicpu(p).opsize := S_L;
  10118. taicpu(p).oper[1]^.reg := NR_ECX;
  10119. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10120. end;
  10121. {$endif x86_64}
  10122. else
  10123. InternalError(2021120401);
  10124. end;
  10125. Result := True;
  10126. Exit;
  10127. end;
  10128. end;
  10129. { This is anything but quick! }
  10130. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10131. Exit;
  10132. SetLength(InstrList, 0);
  10133. InstrMax := -1;
  10134. case taicpu(p).opsize of
  10135. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10136. begin
  10137. {$if defined(i386) or defined(i8086)}
  10138. { If the target size is 8-bit, make sure we can actually encode it }
  10139. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10140. Exit;
  10141. {$endif i386 or i8086}
  10142. LowerLimit := $FF;
  10143. SignedLowerLimit := $7F;
  10144. SignedLowerLimitBottom := -128;
  10145. MinSize := S_B;
  10146. if taicpu(p).opsize = S_BW then
  10147. begin
  10148. MaxSize := S_W;
  10149. UpperLimit := $FFFF;
  10150. SignedUpperLimit := $7FFF;
  10151. SignedUpperLimitBottom := -32768;
  10152. end
  10153. else
  10154. begin
  10155. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10156. MaxSize := S_L;
  10157. UpperLimit := $FFFFFFFF;
  10158. SignedUpperLimit := $7FFFFFFF;
  10159. SignedUpperLimitBottom := -2147483648;
  10160. end;
  10161. end;
  10162. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10163. begin
  10164. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10165. LowerLimit := $FFFF;
  10166. SignedLowerLimit := $7FFF;
  10167. SignedLowerLimitBottom := -32768;
  10168. UpperLimit := $FFFFFFFF;
  10169. SignedUpperLimit := $7FFFFFFF;
  10170. SignedUpperLimitBottom := -2147483648;
  10171. MinSize := S_W;
  10172. MaxSize := S_L;
  10173. end;
  10174. {$ifdef x86_64}
  10175. S_LQ:
  10176. begin
  10177. { Both the lower and upper limits are set to 32-bit. If a limit
  10178. is breached, then optimisation is impossible }
  10179. LowerLimit := $FFFFFFFF;
  10180. SignedLowerLimit := $7FFFFFFF;
  10181. SignedLowerLimitBottom := -2147483648;
  10182. UpperLimit := $FFFFFFFF;
  10183. SignedUpperLimit := $7FFFFFFF;
  10184. SignedUpperLimitBottom := -2147483648;
  10185. MinSize := S_L;
  10186. MaxSize := S_L;
  10187. end;
  10188. {$endif x86_64}
  10189. else
  10190. InternalError(2020112301);
  10191. end;
  10192. TestValMin := 0;
  10193. TestValMax := LowerLimit;
  10194. TestValSignedMax := SignedLowerLimit;
  10195. TryShiftDownLimit := LowerLimit;
  10196. TryShiftDown := S_NO;
  10197. ShiftDownOverflow := False;
  10198. RegChanged := False;
  10199. BitwiseOnly := True;
  10200. OrXorUsed := False;
  10201. UpperSignedOverflow := False;
  10202. LowerSignedOverflow := False;
  10203. UpperUnsignedOverflow := False;
  10204. LowerUnsignedOverflow := False;
  10205. hp1 := p;
  10206. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10207. (hp1.typ = ait_instruction) and
  10208. (
  10209. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10210. instruction that doesn't actually contain ThisReg }
  10211. (cs_opt_level3 in current_settings.optimizerswitches) or
  10212. { This allows this Movx optimisation to work through the SETcc instructions
  10213. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10214. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10215. skip over these SETcc instructions). }
  10216. (taicpu(hp1).opcode = A_SETcc) or
  10217. RegInInstruction(ThisReg, hp1)
  10218. ) do
  10219. begin
  10220. case taicpu(hp1).opcode of
  10221. A_INC,A_DEC:
  10222. begin
  10223. { Has to be an exact match on the register }
  10224. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10225. Break;
  10226. if taicpu(hp1).opcode = A_INC then
  10227. begin
  10228. Inc(TestValMin);
  10229. Inc(TestValMax);
  10230. Inc(TestValSignedMax);
  10231. end
  10232. else
  10233. begin
  10234. Dec(TestValMin);
  10235. Dec(TestValMax);
  10236. Dec(TestValSignedMax);
  10237. end;
  10238. end;
  10239. A_TEST, A_CMP:
  10240. begin
  10241. if (
  10242. { Too high a risk of non-linear behaviour that breaks DFA
  10243. here, unless it's cmp $0,%reg, which is equivalent to
  10244. test %reg,%reg }
  10245. OrXorUsed and
  10246. (taicpu(hp1).opcode = A_CMP) and
  10247. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10248. ) or
  10249. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10250. { Has to be an exact match on the register }
  10251. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10252. (
  10253. { Permit "test %reg,%reg" }
  10254. (taicpu(hp1).opcode = A_TEST) and
  10255. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10256. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10257. ) or
  10258. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10259. { Make sure the comparison value is not smaller than the
  10260. smallest allowed signed value for the minimum size (e.g.
  10261. -128 for 8-bit) }
  10262. not (
  10263. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10264. { Is it in the negative range? }
  10265. (
  10266. (taicpu(hp1).oper[0]^.val < 0) and
  10267. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10268. )
  10269. ) then
  10270. Break;
  10271. { Check to see if the active register is used afterwards }
  10272. TransferUsedRegs(TmpUsedRegs);
  10273. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10274. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10275. begin
  10276. { Make sure the comparison or any previous instructions
  10277. hasn't pushed the test values outside of the range of
  10278. MinSize }
  10279. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10280. begin
  10281. { Exceeded lower bound but not upper bound }
  10282. Exit;
  10283. end
  10284. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10285. begin
  10286. { Size didn't exceed lower bound }
  10287. TargetSize := MinSize;
  10288. end
  10289. else
  10290. Break;
  10291. case TargetSize of
  10292. S_B:
  10293. TargetSubReg := R_SUBL;
  10294. S_W:
  10295. TargetSubReg := R_SUBW;
  10296. S_L:
  10297. TargetSubReg := R_SUBD;
  10298. else
  10299. InternalError(2021051002);
  10300. end;
  10301. if TargetSize <> MaxSize then
  10302. begin
  10303. { Update the register to its new size }
  10304. setsubreg(ThisReg, TargetSubReg);
  10305. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10306. taicpu(hp1).oper[1]^.reg := ThisReg;
  10307. taicpu(hp1).opsize := TargetSize;
  10308. { Convert the input MOVZX to a MOV if necessary }
  10309. AdjustInitialLoadAndSize;
  10310. if (InstrMax >= 0) then
  10311. begin
  10312. for Index := 0 to InstrMax do
  10313. begin
  10314. { If p_removed is true, then the original MOV/Z was removed
  10315. and removing the AND instruction may not be safe if it
  10316. appears first }
  10317. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10318. InternalError(2020112311);
  10319. if InstrList[Index].oper[0]^.typ = top_reg then
  10320. InstrList[Index].oper[0]^.reg := ThisReg;
  10321. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10322. InstrList[Index].opsize := MinSize;
  10323. end;
  10324. end;
  10325. Result := True;
  10326. end;
  10327. Exit;
  10328. end;
  10329. end;
  10330. A_SETcc:
  10331. begin
  10332. { This allows this Movx optimisation to work through the SETcc instructions
  10333. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10334. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10335. skip over these SETcc instructions). }
  10336. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10337. { Of course, break out if the current register is used }
  10338. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10339. Break
  10340. else
  10341. { We must use Continue so the instruction doesn't get added
  10342. to InstrList }
  10343. Continue;
  10344. end;
  10345. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10346. begin
  10347. if
  10348. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10349. { Has to be an exact match on the register }
  10350. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10351. (
  10352. (
  10353. (taicpu(hp1).oper[0]^.typ = top_const) and
  10354. (
  10355. (
  10356. (taicpu(hp1).opcode = A_SHL) and
  10357. (
  10358. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10359. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10360. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10361. )
  10362. ) or (
  10363. (taicpu(hp1).opcode <> A_SHL) and
  10364. (
  10365. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10366. { Is it in the negative range? }
  10367. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10368. )
  10369. )
  10370. )
  10371. ) or (
  10372. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10373. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10374. )
  10375. ) then
  10376. Break;
  10377. { Only process OR and XOR if there are only bitwise operations,
  10378. since otherwise they can too easily fool the data flow
  10379. analysis (they can cause non-linear behaviour) }
  10380. case taicpu(hp1).opcode of
  10381. A_ADD:
  10382. begin
  10383. if OrXorUsed then
  10384. { Too high a risk of non-linear behaviour that breaks DFA here }
  10385. Break
  10386. else
  10387. BitwiseOnly := False;
  10388. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10389. begin
  10390. TestValMin := TestValMin * 2;
  10391. TestValMax := TestValMax * 2;
  10392. TestValSignedMax := TestValSignedMax * 2;
  10393. end
  10394. else
  10395. begin
  10396. WorkingValue := taicpu(hp1).oper[0]^.val;
  10397. TestValMin := TestValMin + WorkingValue;
  10398. TestValMax := TestValMax + WorkingValue;
  10399. TestValSignedMax := TestValSignedMax + WorkingValue;
  10400. end;
  10401. end;
  10402. A_SUB:
  10403. begin
  10404. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10405. begin
  10406. TestValMin := 0;
  10407. TestValMax := 0;
  10408. TestValSignedMax := 0;
  10409. end
  10410. else
  10411. begin
  10412. if OrXorUsed then
  10413. { Too high a risk of non-linear behaviour that breaks DFA here }
  10414. Break
  10415. else
  10416. BitwiseOnly := False;
  10417. WorkingValue := taicpu(hp1).oper[0]^.val;
  10418. TestValMin := TestValMin - WorkingValue;
  10419. TestValMax := TestValMax - WorkingValue;
  10420. TestValSignedMax := TestValSignedMax - WorkingValue;
  10421. end;
  10422. end;
  10423. A_AND:
  10424. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10425. begin
  10426. { we might be able to go smaller if AND appears first }
  10427. if InstrMax = -1 then
  10428. case MinSize of
  10429. S_B:
  10430. ;
  10431. S_W:
  10432. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10433. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10434. begin
  10435. TryShiftDown := S_B;
  10436. TryShiftDownLimit := $FF;
  10437. end;
  10438. S_L:
  10439. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10440. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10441. begin
  10442. TryShiftDown := S_B;
  10443. TryShiftDownLimit := $FF;
  10444. end
  10445. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10446. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10447. begin
  10448. TryShiftDown := S_W;
  10449. TryShiftDownLimit := $FFFF;
  10450. end;
  10451. else
  10452. InternalError(2020112320);
  10453. end;
  10454. WorkingValue := taicpu(hp1).oper[0]^.val;
  10455. TestValMin := TestValMin and WorkingValue;
  10456. TestValMax := TestValMax and WorkingValue;
  10457. TestValSignedMax := TestValSignedMax and WorkingValue;
  10458. end;
  10459. A_OR:
  10460. begin
  10461. if not BitwiseOnly then
  10462. Break;
  10463. OrXorUsed := True;
  10464. WorkingValue := taicpu(hp1).oper[0]^.val;
  10465. TestValMin := TestValMin or WorkingValue;
  10466. TestValMax := TestValMax or WorkingValue;
  10467. TestValSignedMax := TestValSignedMax or WorkingValue;
  10468. end;
  10469. A_XOR:
  10470. begin
  10471. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10472. begin
  10473. TestValMin := 0;
  10474. TestValMax := 0;
  10475. TestValSignedMax := 0;
  10476. end
  10477. else
  10478. begin
  10479. if not BitwiseOnly then
  10480. Break;
  10481. OrXorUsed := True;
  10482. WorkingValue := taicpu(hp1).oper[0]^.val;
  10483. TestValMin := TestValMin xor WorkingValue;
  10484. TestValMax := TestValMax xor WorkingValue;
  10485. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10486. end;
  10487. end;
  10488. A_SHL:
  10489. begin
  10490. BitwiseOnly := False;
  10491. WorkingValue := taicpu(hp1).oper[0]^.val;
  10492. TestValMin := TestValMin shl WorkingValue;
  10493. TestValMax := TestValMax shl WorkingValue;
  10494. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10495. end;
  10496. A_SHR,
  10497. { The first instruction was MOVZX, so the value won't be negative }
  10498. A_SAR:
  10499. begin
  10500. if InstrMax <> -1 then
  10501. BitwiseOnly := False
  10502. else
  10503. { we might be able to go smaller if SHR appears first }
  10504. case MinSize of
  10505. S_B:
  10506. ;
  10507. S_W:
  10508. if (taicpu(hp1).oper[0]^.val >= 8) then
  10509. begin
  10510. TryShiftDown := S_B;
  10511. TryShiftDownLimit := $FF;
  10512. TryShiftDownSignedLimit := $7F;
  10513. TryShiftDownSignedLimitLower := -128;
  10514. end;
  10515. S_L:
  10516. if (taicpu(hp1).oper[0]^.val >= 24) then
  10517. begin
  10518. TryShiftDown := S_B;
  10519. TryShiftDownLimit := $FF;
  10520. TryShiftDownSignedLimit := $7F;
  10521. TryShiftDownSignedLimitLower := -128;
  10522. end
  10523. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10524. begin
  10525. TryShiftDown := S_W;
  10526. TryShiftDownLimit := $FFFF;
  10527. TryShiftDownSignedLimit := $7FFF;
  10528. TryShiftDownSignedLimitLower := -32768;
  10529. end;
  10530. else
  10531. InternalError(2020112321);
  10532. end;
  10533. WorkingValue := taicpu(hp1).oper[0]^.val;
  10534. if taicpu(hp1).opcode = A_SAR then
  10535. begin
  10536. TestValMin := SarInt64(TestValMin, WorkingValue);
  10537. TestValMax := SarInt64(TestValMax, WorkingValue);
  10538. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10539. end
  10540. else
  10541. begin
  10542. TestValMin := TestValMin shr WorkingValue;
  10543. TestValMax := TestValMax shr WorkingValue;
  10544. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10545. end;
  10546. end;
  10547. else
  10548. InternalError(2020112303);
  10549. end;
  10550. end;
  10551. (*
  10552. A_IMUL:
  10553. case taicpu(hp1).ops of
  10554. 2:
  10555. begin
  10556. if not MatchOpType(hp1, top_reg, top_reg) or
  10557. { Has to be an exact match on the register }
  10558. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10559. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10560. Break;
  10561. TestValMin := TestValMin * TestValMin;
  10562. TestValMax := TestValMax * TestValMax;
  10563. TestValSignedMax := TestValSignedMax * TestValMax;
  10564. end;
  10565. 3:
  10566. begin
  10567. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10568. { Has to be an exact match on the register }
  10569. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10570. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10571. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10572. { Is it in the negative range? }
  10573. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10574. Break;
  10575. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10576. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10577. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10578. end;
  10579. else
  10580. Break;
  10581. end;
  10582. A_IDIV:
  10583. case taicpu(hp1).ops of
  10584. 3:
  10585. begin
  10586. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10587. { Has to be an exact match on the register }
  10588. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10589. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10590. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10591. { Is it in the negative range? }
  10592. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10593. Break;
  10594. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10595. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10596. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10597. end;
  10598. else
  10599. Break;
  10600. end;
  10601. *)
  10602. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10603. begin
  10604. { If there are no instructions in between, then we might be able to make a saving }
  10605. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10606. Break;
  10607. { We have something like:
  10608. movzbw %dl,%dx
  10609. ...
  10610. movswl %dx,%edx
  10611. Change the latter to a zero-extension then enter the
  10612. A_MOVZX case branch.
  10613. }
  10614. {$ifdef x86_64}
  10615. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10616. begin
  10617. { this becomes a zero extension from 32-bit to 64-bit, but
  10618. the upper 32 bits are already zero, so just delete the
  10619. instruction }
  10620. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10621. RemoveInstruction(hp1);
  10622. Result := True;
  10623. Exit;
  10624. end
  10625. else
  10626. {$endif x86_64}
  10627. begin
  10628. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10629. taicpu(hp1).opcode := A_MOVZX;
  10630. {$ifdef x86_64}
  10631. case taicpu(hp1).opsize of
  10632. S_BQ:
  10633. begin
  10634. taicpu(hp1).opsize := S_BL;
  10635. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10636. end;
  10637. S_WQ:
  10638. begin
  10639. taicpu(hp1).opsize := S_WL;
  10640. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10641. end;
  10642. S_LQ:
  10643. begin
  10644. taicpu(hp1).opcode := A_MOV;
  10645. taicpu(hp1).opsize := S_L;
  10646. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10647. { In this instance, we need to break out because the
  10648. instruction is no longer MOVZX or MOVSXD }
  10649. Result := True;
  10650. Exit;
  10651. end;
  10652. else
  10653. ;
  10654. end;
  10655. {$endif x86_64}
  10656. Result := CompressInstructions;
  10657. Exit;
  10658. end;
  10659. end;
  10660. A_MOVZX:
  10661. begin
  10662. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10663. Break;
  10664. if (InstrMax = -1) then
  10665. begin
  10666. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10667. begin
  10668. { Optimise around i40003 }
  10669. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10670. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10671. {$ifndef x86_64}
  10672. and (
  10673. (taicpu(p).oper[0]^.typ <> top_reg) or
  10674. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10675. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10676. )
  10677. {$endif not x86_64}
  10678. then
  10679. begin
  10680. if (taicpu(p).oper[0]^.typ = top_reg) then
  10681. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10682. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10683. taicpu(p).opsize := S_BL;
  10684. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10685. RemoveInstruction(hp1);
  10686. Result := True;
  10687. Exit;
  10688. end;
  10689. end
  10690. else
  10691. begin
  10692. { Will return false if the second parameter isn't ThisReg
  10693. (can happen on -O2 and under) }
  10694. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10695. begin
  10696. { The two MOVZX instructions are adjacent, so remove the first one }
  10697. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10698. RemoveCurrentP(p);
  10699. Result := True;
  10700. Exit;
  10701. end;
  10702. Break;
  10703. end;
  10704. end;
  10705. Result := CompressInstructions;
  10706. Exit;
  10707. end;
  10708. else
  10709. { This includes ADC, SBB and IDIV }
  10710. Break;
  10711. end;
  10712. if not CheckOverflowConditions then
  10713. Break;
  10714. { Contains highest index (so instruction count - 1) }
  10715. Inc(InstrMax);
  10716. if InstrMax > High(InstrList) then
  10717. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10718. InstrList[InstrMax] := taicpu(hp1);
  10719. end;
  10720. end;
  10721. {$pop}
  10722. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10723. var
  10724. hp1 : tai;
  10725. begin
  10726. Result:=false;
  10727. if (taicpu(p).ops >= 2) and
  10728. ((taicpu(p).oper[0]^.typ = top_const) or
  10729. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10730. (taicpu(p).oper[1]^.typ = top_reg) and
  10731. ((taicpu(p).ops = 2) or
  10732. ((taicpu(p).oper[2]^.typ = top_reg) and
  10733. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10734. GetLastInstruction(p,hp1) and
  10735. MatchInstruction(hp1,A_MOV,[]) and
  10736. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10737. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10738. begin
  10739. TransferUsedRegs(TmpUsedRegs);
  10740. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10741. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10742. { change
  10743. mov reg1,reg2
  10744. imul y,reg2 to imul y,reg1,reg2 }
  10745. begin
  10746. taicpu(p).ops := 3;
  10747. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10748. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10749. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10750. RemoveInstruction(hp1);
  10751. result:=true;
  10752. end;
  10753. end;
  10754. end;
  10755. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10756. var
  10757. ThisLabel: TAsmLabel;
  10758. begin
  10759. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10760. ThisLabel.decrefs;
  10761. taicpu(p).condition := C_None;
  10762. taicpu(p).opcode := A_RET;
  10763. taicpu(p).is_jmp := false;
  10764. taicpu(p).ops := taicpu(ret_p).ops;
  10765. case taicpu(ret_p).ops of
  10766. 0:
  10767. taicpu(p).clearop(0);
  10768. 1:
  10769. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10770. else
  10771. internalerror(2016041301);
  10772. end;
  10773. { If the original label is now dead, it might turn out that the label
  10774. immediately follows p. As a result, everything beyond it, which will
  10775. be just some final register configuration and a RET instruction, is
  10776. now dead code. [Kit] }
  10777. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10778. running RemoveDeadCodeAfterJump for each RET instruction, because
  10779. this optimisation rarely happens and most RETs appear at the end of
  10780. routines where there is nothing that can be stripped. [Kit] }
  10781. if not ThisLabel.is_used then
  10782. RemoveDeadCodeAfterJump(p);
  10783. end;
  10784. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10785. var
  10786. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10787. Unconditional, PotentialModified: Boolean;
  10788. OperPtr: POper;
  10789. NewRef: TReference;
  10790. InstrList: array of taicpu;
  10791. InstrMax, Index: Integer;
  10792. const
  10793. {$ifdef DEBUG_AOPTCPU}
  10794. SNoFlags: shortstring = ' so the flags aren''t modified';
  10795. {$else DEBUG_AOPTCPU}
  10796. SNoFlags = '';
  10797. {$endif DEBUG_AOPTCPU}
  10798. begin
  10799. Result:=false;
  10800. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10801. begin
  10802. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10803. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10804. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10805. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10806. GetNextInstruction(hp1, hp2) and
  10807. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10808. { Change from: To:
  10809. set(C) %reg j(~C) label
  10810. test %reg,%reg/cmp $0,%reg
  10811. je label
  10812. set(C) %reg j(C) label
  10813. test %reg,%reg/cmp $0,%reg
  10814. jne label
  10815. (Also do something similar with sete/setne instead of je/jne)
  10816. }
  10817. begin
  10818. { Before we do anything else, we need to check the instructions
  10819. in between SETcc and TEST to make sure they don't modify the
  10820. FLAGS register - if -O2 or under, there won't be any
  10821. instructions between SET and TEST }
  10822. TransferUsedRegs(TmpUsedRegs);
  10823. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10824. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10825. begin
  10826. next := p;
  10827. SetLength(InstrList, 0);
  10828. InstrMax := -1;
  10829. PotentialModified := False;
  10830. { Make a note of every instruction that modifies the FLAGS
  10831. register }
  10832. while GetNextInstruction(next, next) and (next <> hp1) do
  10833. begin
  10834. if next.typ <> ait_instruction then
  10835. { GetNextInstructionUsingReg should have returned False }
  10836. InternalError(2021051701);
  10837. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10838. begin
  10839. case taicpu(next).opcode of
  10840. A_SETcc,
  10841. A_CMOVcc,
  10842. A_Jcc:
  10843. begin
  10844. if PotentialModified then
  10845. { Not safe because the flags were modified earlier }
  10846. Exit
  10847. else
  10848. { Condition is the same as the initial SETcc, so this is safe
  10849. (don't add to instruction list though) }
  10850. Continue;
  10851. end;
  10852. A_ADD:
  10853. begin
  10854. if (taicpu(next).opsize = S_B) or
  10855. { LEA doesn't support 8-bit operands }
  10856. (taicpu(next).oper[1]^.typ <> top_reg) or
  10857. { Must write to a register }
  10858. (taicpu(next).oper[0]^.typ = top_ref) then
  10859. { Require a constant or a register }
  10860. Exit;
  10861. PotentialModified := True;
  10862. end;
  10863. A_SUB:
  10864. begin
  10865. if (taicpu(next).opsize = S_B) or
  10866. { LEA doesn't support 8-bit operands }
  10867. (taicpu(next).oper[1]^.typ <> top_reg) or
  10868. { Must write to a register }
  10869. (taicpu(next).oper[0]^.typ <> top_const) or
  10870. (taicpu(next).oper[0]^.val = $80000000) then
  10871. { Can't subtract a register with LEA - also
  10872. check that the value isn't -2^31, as this
  10873. can't be negated }
  10874. Exit;
  10875. PotentialModified := True;
  10876. end;
  10877. A_SAL,
  10878. A_SHL:
  10879. begin
  10880. if (taicpu(next).opsize = S_B) or
  10881. { LEA doesn't support 8-bit operands }
  10882. (taicpu(next).oper[1]^.typ <> top_reg) or
  10883. { Must write to a register }
  10884. (taicpu(next).oper[0]^.typ <> top_const) or
  10885. (taicpu(next).oper[0]^.val < 0) or
  10886. (taicpu(next).oper[0]^.val > 3) then
  10887. Exit;
  10888. PotentialModified := True;
  10889. end;
  10890. A_IMUL:
  10891. begin
  10892. if (taicpu(next).ops <> 3) or
  10893. (taicpu(next).oper[1]^.typ <> top_reg) or
  10894. { Must write to a register }
  10895. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10896. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10897. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10898. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10899. Exit
  10900. else
  10901. PotentialModified := True;
  10902. end;
  10903. else
  10904. { Don't know how to change this, so abort }
  10905. Exit;
  10906. end;
  10907. { Contains highest index (so instruction count - 1) }
  10908. Inc(InstrMax);
  10909. if InstrMax > High(InstrList) then
  10910. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10911. InstrList[InstrMax] := taicpu(next);
  10912. end;
  10913. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10914. end;
  10915. if not Assigned(next) or (next <> hp1) then
  10916. { It should be equal to hp1 }
  10917. InternalError(2021051702);
  10918. { Cycle through each instruction and check to see if we can
  10919. change them to versions that don't modify the flags }
  10920. if (InstrMax >= 0) then
  10921. begin
  10922. for Index := 0 to InstrMax do
  10923. case InstrList[Index].opcode of
  10924. A_ADD:
  10925. begin
  10926. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10927. InstrList[Index].opcode := A_LEA;
  10928. reference_reset(NewRef, 1, []);
  10929. NewRef.base := InstrList[Index].oper[1]^.reg;
  10930. if InstrList[Index].oper[0]^.typ = top_reg then
  10931. begin
  10932. NewRef.index := InstrList[Index].oper[0]^.reg;
  10933. NewRef.scalefactor := 1;
  10934. end
  10935. else
  10936. NewRef.offset := InstrList[Index].oper[0]^.val;
  10937. InstrList[Index].loadref(0, NewRef);
  10938. end;
  10939. A_SUB:
  10940. begin
  10941. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10942. InstrList[Index].opcode := A_LEA;
  10943. reference_reset(NewRef, 1, []);
  10944. NewRef.base := InstrList[Index].oper[1]^.reg;
  10945. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10946. InstrList[Index].loadref(0, NewRef);
  10947. end;
  10948. A_SHL,
  10949. A_SAL:
  10950. begin
  10951. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10952. InstrList[Index].opcode := A_LEA;
  10953. reference_reset(NewRef, 1, []);
  10954. NewRef.index := InstrList[Index].oper[1]^.reg;
  10955. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10956. InstrList[Index].loadref(0, NewRef);
  10957. end;
  10958. A_IMUL:
  10959. begin
  10960. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10961. InstrList[Index].opcode := A_LEA;
  10962. reference_reset(NewRef, 1, []);
  10963. NewRef.index := InstrList[Index].oper[1]^.reg;
  10964. case InstrList[Index].oper[0]^.val of
  10965. 2, 4, 8:
  10966. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10967. else {3, 5 and 9}
  10968. begin
  10969. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10970. NewRef.base := InstrList[Index].oper[1]^.reg;
  10971. end;
  10972. end;
  10973. InstrList[Index].loadref(0, NewRef);
  10974. end;
  10975. else
  10976. InternalError(2021051710);
  10977. end;
  10978. end;
  10979. { Mark the FLAGS register as used across this whole block }
  10980. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10981. end;
  10982. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10983. JumpC := taicpu(hp2).condition;
  10984. Unconditional := False;
  10985. if conditions_equal(JumpC, C_E) then
  10986. SetC := inverse_cond(taicpu(p).condition)
  10987. else if conditions_equal(JumpC, C_NE) then
  10988. SetC := taicpu(p).condition
  10989. else
  10990. { We've got something weird here (and inefficent) }
  10991. begin
  10992. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10993. SetC := C_NONE;
  10994. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10995. if condition_in(C_AE, JumpC) then
  10996. Unconditional := True
  10997. else
  10998. { Not sure what to do with this jump - drop out }
  10999. Exit;
  11000. end;
  11001. RemoveInstruction(hp1);
  11002. if Unconditional then
  11003. MakeUnconditional(taicpu(hp2))
  11004. else
  11005. begin
  11006. if SetC = C_NONE then
  11007. InternalError(2018061402);
  11008. taicpu(hp2).SetCondition(SetC);
  11009. end;
  11010. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11011. TmpUsedRegs }
  11012. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11013. begin
  11014. RemoveCurrentp(p, hp2);
  11015. if taicpu(hp2).opcode = A_SETcc then
  11016. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11017. else
  11018. begin
  11019. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11020. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11021. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11022. end;
  11023. end
  11024. else
  11025. if taicpu(hp2).opcode = A_SETcc then
  11026. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11027. else
  11028. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11029. Result := True;
  11030. end
  11031. else if
  11032. { Make sure the instructions are adjacent }
  11033. (
  11034. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11035. GetNextInstruction(p, hp1)
  11036. ) and
  11037. MatchInstruction(hp1, A_MOV, [S_B]) and
  11038. { Writing to memory is allowed }
  11039. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11040. begin
  11041. {
  11042. Watch out for sequences such as:
  11043. set(c)b %regb
  11044. movb %regb,(ref)
  11045. movb $0,1(ref)
  11046. movb $0,2(ref)
  11047. movb $0,3(ref)
  11048. Much more efficient to turn it into:
  11049. movl $0,%regl
  11050. set(c)b %regb
  11051. movl %regl,(ref)
  11052. Or:
  11053. set(c)b %regb
  11054. movzbl %regb,%regl
  11055. movl %regl,(ref)
  11056. }
  11057. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11058. GetNextInstruction(hp1, hp2) and
  11059. MatchInstruction(hp2, A_MOV, [S_B]) and
  11060. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11061. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11062. begin
  11063. { Don't do anything else except set Result to True }
  11064. end
  11065. else
  11066. begin
  11067. if taicpu(p).oper[0]^.typ = top_reg then
  11068. begin
  11069. TransferUsedRegs(TmpUsedRegs);
  11070. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11071. end;
  11072. { If it's not a register, it's a memory address }
  11073. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11074. begin
  11075. { Even if the register is still in use, we can minimise the
  11076. pipeline stall by changing the MOV into another SETcc. }
  11077. taicpu(hp1).opcode := A_SETcc;
  11078. taicpu(hp1).condition := taicpu(p).condition;
  11079. if taicpu(hp1).oper[1]^.typ = top_ref then
  11080. begin
  11081. { Swapping the operand pointers like this is probably a
  11082. bit naughty, but it is far faster than using loadoper
  11083. to transfer the reference from oper[1] to oper[0] if
  11084. you take into account the extra procedure calls and
  11085. the memory allocation and deallocation required }
  11086. OperPtr := taicpu(hp1).oper[1];
  11087. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11088. taicpu(hp1).oper[0] := OperPtr;
  11089. end
  11090. else
  11091. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11092. taicpu(hp1).clearop(1);
  11093. taicpu(hp1).ops := 1;
  11094. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11095. end
  11096. else
  11097. begin
  11098. if taicpu(hp1).oper[1]^.typ = top_reg then
  11099. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11100. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11101. RemoveInstruction(hp1);
  11102. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11103. end
  11104. end;
  11105. Result := True;
  11106. end;
  11107. end;
  11108. end;
  11109. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11110. var
  11111. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11112. TargetReg: TRegister;
  11113. condition, inverted_condition: TAsmCond;
  11114. FoundMOV: Boolean;
  11115. begin
  11116. Result := False;
  11117. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11118. create the most optimial instructions possible due to limited
  11119. register availability, and there are situations where two
  11120. complementary "simple" CMOV blocks are created which, after the fact
  11121. can be merged into a "double" block. For example:
  11122. movw $257,%ax
  11123. movw $2,%r8w
  11124. xorl r9d,%r9d
  11125. testw $16,18(%rcx)
  11126. cmovew %ax,%dx
  11127. cmovew %r8w,%bx
  11128. cmovel %r9d,%r14d
  11129. movw $1283,%ax
  11130. movw $4,%r8w
  11131. movl $9,%r9d
  11132. cmovnew %ax,%dx
  11133. cmovnew %r8w,%bx
  11134. cmovnel %r9d,%r14d
  11135. The CMOVNE instructions at the end can be removed, and the
  11136. destination registers copied into the MOV instructions directly
  11137. above them, before finally being moved to before the first CMOVE
  11138. instructions, to produce:
  11139. movw $257,%ax
  11140. movw $2,%r8w
  11141. xorl r9d,%r9d
  11142. testw $16,18(%rcx)
  11143. movw $1283,%dx
  11144. movw $4,%bx
  11145. movl $9,%r14d
  11146. cmovew %ax,%dx
  11147. cmovew %r8w,%bx
  11148. cmovel %r9d,%r14d
  11149. Which can then be later optimised to:
  11150. movw $257,%ax
  11151. movw $2,%r8w
  11152. xorl r9d,%r9d
  11153. movw $1283,%dx
  11154. movw $4,%bx
  11155. movl $9,%r14d
  11156. testw $16,18(%rcx)
  11157. cmovew %ax,%dx
  11158. cmovew %r8w,%bx
  11159. cmovel %r9d,%r14d
  11160. }
  11161. TargetReg := taicpu(hp1).oper[1]^.reg;
  11162. condition := taicpu(hp1).condition;
  11163. inverted_condition := inverse_cond(condition);
  11164. pFirstMov := nil;
  11165. pLastMov := nil;
  11166. pCMOV := nil;
  11167. if (p.typ = ait_instruction) then
  11168. pCond := p
  11169. else if not GetNextInstruction(p, pCond) then
  11170. InternalError(2024012501);
  11171. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11172. { We should get the CMP or TEST instructeion }
  11173. InternalError(2024012502);
  11174. if (
  11175. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11176. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11177. ) then
  11178. begin
  11179. { We have to tread carefully here, hence why we're not using
  11180. GetNextInstructionUsingReg... we can only accept MOV and other
  11181. CMOV instructions. Anything else and we must drop out}
  11182. hp2 := hp1;
  11183. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11184. begin
  11185. if (hp2.typ <> ait_instruction) then
  11186. Exit;
  11187. case taicpu(hp2).opcode of
  11188. A_MOV:
  11189. begin
  11190. if not Assigned(pFirstMov) then
  11191. pFirstMov := hp2;
  11192. pLastMOV := hp2;
  11193. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11194. { Something different - drop out }
  11195. Exit;
  11196. { Otherwise, leave it for now }
  11197. end;
  11198. A_CMOVcc:
  11199. begin
  11200. if taicpu(hp2).condition = inverted_condition then
  11201. begin
  11202. { We found what we're looking for }
  11203. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11204. begin
  11205. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11206. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11207. begin
  11208. pCMOV := hp2;
  11209. Break;
  11210. end
  11211. else
  11212. { Unsafe reference - drop out }
  11213. Exit;
  11214. end;
  11215. end
  11216. else if taicpu(hp2).condition <> condition then
  11217. { Something weird - drop out }
  11218. Exit;
  11219. end;
  11220. else
  11221. { Invalid }
  11222. Exit;
  11223. end;
  11224. end;
  11225. if not Assigned(pCMOV) then
  11226. { No complementary CMOV found }
  11227. Exit;
  11228. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11229. begin
  11230. { Don't need to do anything special or search for a matching MOV }
  11231. Asml.Remove(pCMOV);
  11232. if RegInInstruction(TargetReg, pCond) then
  11233. { Make sure we don't overwrite the register if it's being used in the condition }
  11234. Asml.InsertAfter(pCMOV, pCond)
  11235. else
  11236. Asml.InsertBefore(pCMOV, pCond);
  11237. taicpu(pCMOV).opcode := A_MOV;
  11238. taicpu(pCMOV).condition := C_None;
  11239. { Don't need to worry about allocating new registers in these cases }
  11240. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11241. Result := True;
  11242. Exit;
  11243. end
  11244. else
  11245. begin
  11246. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11247. FoundMOV := False;
  11248. { Search for the MOV that sets the target register }
  11249. hp2 := pFirstMov;
  11250. repeat
  11251. if (taicpu(hp2).opcode = A_MOV) and
  11252. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11253. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11254. begin
  11255. { Change the destination }
  11256. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11257. if not FoundMOV then
  11258. begin
  11259. FoundMOV := True;
  11260. { Make sure the register is allocated }
  11261. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11262. end;
  11263. hp1 := tai(hp2.Previous);
  11264. Asml.Remove(hp2);
  11265. if RegInInstruction(TargetReg, pCond) then
  11266. { Make sure we don't overwrite the register if it's being used in the condition }
  11267. Asml.InsertAfter(hp2, pCond)
  11268. else
  11269. Asml.InsertBefore(hp2, pCond);
  11270. if (hp2 = pLastMov) then
  11271. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11272. Break;
  11273. hp2 := hp1;
  11274. end;
  11275. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11276. if FoundMOV then
  11277. { Delete the CMOV }
  11278. RemoveInstruction(pCMOV)
  11279. else
  11280. begin
  11281. { If no MOV was found, we have to actually move and transmute the CMOV }
  11282. Asml.Remove(pCMOV);
  11283. if RegInInstruction(TargetReg, pCond) then
  11284. { Make sure we don't overwrite the register if it's being used in the condition }
  11285. Asml.InsertAfter(pCMOV, pCond)
  11286. else
  11287. Asml.InsertBefore(pCMOV, pCond);
  11288. taicpu(pCMOV).opcode := A_MOV;
  11289. taicpu(pCMOV).condition := C_None;
  11290. end;
  11291. Result := True;
  11292. Exit;
  11293. end;
  11294. end;
  11295. end;
  11296. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11297. var
  11298. hp1, hp2, pCond: tai;
  11299. begin
  11300. Result := False;
  11301. { Search ahead for CMOV instructions }
  11302. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11303. begin
  11304. hp1 := p;
  11305. hp2 := p;
  11306. pCond := nil; { To prevent compiler warnings }
  11307. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11308. DEFAULTFLAGS }
  11309. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11310. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11311. pCond := p;
  11312. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11313. begin
  11314. if (hp1.typ <> ait_instruction) then
  11315. { Break out on markers and labels etc. }
  11316. Break;
  11317. case taicpu(hp1).opcode of
  11318. A_MOV:
  11319. { Ignore regular MOVs unless they are obviously not related
  11320. to a CMOV block }
  11321. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11322. Break;
  11323. A_CMOVcc:
  11324. if TryCmpCMovOpts(pCond, hp1) then
  11325. begin
  11326. hp1 := hp2;
  11327. { p itself isn't changed, and we're still inside a
  11328. while loop to catch subsequent CMOVs, so just flag
  11329. a new iteration }
  11330. Include(OptsToCheck, aoc_ForceNewIteration);
  11331. Continue;
  11332. end;
  11333. else
  11334. { Drop out if we find anything else }
  11335. Break;
  11336. end;
  11337. hp2 := hp1;
  11338. end;
  11339. end;
  11340. end;
  11341. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11342. var
  11343. hp1, hp2, pCond: tai;
  11344. SourceReg, TargetReg: TRegister;
  11345. begin
  11346. Result := False;
  11347. { In some situations, we end up with an inefficient arrangement of
  11348. instructions in the form of:
  11349. or %reg1,%reg2
  11350. (%reg1 deallocated)
  11351. test %reg2,%reg2
  11352. mov x,%reg2
  11353. we may be able to swap and rearrange the registers to produce:
  11354. or %reg2,%reg1
  11355. mov x,%reg2
  11356. test %reg1,%reg1
  11357. (%reg1 deallocated)
  11358. }
  11359. if (cs_opt_level3 in current_settings.optimizerswitches) and
  11360. (taicpu(p).oper[1]^.typ = top_reg) and
  11361. (
  11362. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  11363. MatchOperand(taicpu(p).oper[0]^, -1)
  11364. ) and
  11365. GetNextInstruction(p, hp1) and
  11366. MatchInstruction(hp1, A_MOV, []) and
  11367. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11368. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  11369. begin
  11370. TargetReg := taicpu(p).oper[1]^.reg;
  11371. { Now look backwards to find a simple commutative operation: ADD,
  11372. IMUL (2-register version), OR, AND or XOR - whose destination
  11373. register is the same as TEST }
  11374. hp2 := p;
  11375. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  11376. if RegInInstruction(TargetReg, hp2) then
  11377. begin
  11378. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  11379. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11380. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  11381. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  11382. begin
  11383. SourceReg := taicpu(hp2).oper[0]^.reg;
  11384. if
  11385. { Make sure the MOV doesn't use the other register }
  11386. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  11387. { And make sure the source register is not used afterwards }
  11388. not RegInUsedRegs(SourceReg, UsedRegs) then
  11389. begin
  11390. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  11391. taicpu(hp2).oper[0]^.reg := TargetReg;
  11392. taicpu(hp2).oper[1]^.reg := SourceReg;
  11393. if taicpu(p).oper[0]^.typ = top_reg then
  11394. taicpu(p).oper[0]^.reg := SourceReg;
  11395. taicpu(p).oper[1]^.reg := SourceReg;
  11396. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  11397. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  11398. Include(OptsToCheck, aoc_ForceNewIteration);
  11399. { We can still check the following optimisations since
  11400. the instruction is still a TEST }
  11401. end;
  11402. end;
  11403. Break;
  11404. end;
  11405. end;
  11406. { Search ahead3 for CMOV instructions }
  11407. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11408. begin
  11409. hp1 := p;
  11410. hp2 := p;
  11411. pCond := nil; { To prevent compiler warnings }
  11412. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11413. DEFAULTFLAGS }
  11414. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11415. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11416. pCond := p;
  11417. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11418. begin
  11419. if (hp1.typ <> ait_instruction) then
  11420. { Break out on markers and labels etc. }
  11421. Break;
  11422. case taicpu(hp1).opcode of
  11423. A_MOV:
  11424. { Ignore regular MOVs unless they are obviously not related
  11425. to a CMOV block }
  11426. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11427. Break;
  11428. A_CMOVcc:
  11429. if TryCmpCMovOpts(pCond, hp1) then
  11430. begin
  11431. hp1 := hp2;
  11432. { p itself isn't changed, and we're still inside a
  11433. while loop to catch subsequent CMOVs, so just flag
  11434. a new iteration }
  11435. Include(OptsToCheck, aoc_ForceNewIteration);
  11436. Continue;
  11437. end;
  11438. else
  11439. { Drop out if we find anything else }
  11440. Break;
  11441. end;
  11442. hp2 := hp1;
  11443. end;
  11444. end;
  11445. end;
  11446. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11447. var
  11448. hp1: tai;
  11449. Count: Integer;
  11450. OrigLabel: TAsmLabel;
  11451. begin
  11452. result := False;
  11453. { Sometimes, the optimisations below can permit this }
  11454. RemoveDeadCodeAfterJump(p);
  11455. 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
  11456. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11457. begin
  11458. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11459. { Also a side-effect of optimisations }
  11460. if CollapseZeroDistJump(p, OrigLabel) then
  11461. begin
  11462. Result := True;
  11463. Exit;
  11464. end;
  11465. hp1 := GetLabelWithSym(OrigLabel);
  11466. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11467. begin
  11468. if taicpu(hp1).opcode = A_RET then
  11469. begin
  11470. {
  11471. change
  11472. jmp .L1
  11473. ...
  11474. .L1:
  11475. ret
  11476. into
  11477. ret
  11478. }
  11479. begin
  11480. ConvertJumpToRET(p, hp1);
  11481. result:=true;
  11482. end;
  11483. end
  11484. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11485. not (cs_opt_size in current_settings.optimizerswitches) and
  11486. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11487. begin
  11488. Result := True;
  11489. Exit;
  11490. end;
  11491. end;
  11492. end;
  11493. end;
  11494. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11495. begin
  11496. Result := assigned(p) and
  11497. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11498. (taicpu(p).oper[1]^.typ = top_reg) and
  11499. (
  11500. (taicpu(p).oper[0]^.typ = top_reg) or
  11501. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11502. it is not expected that this can cause a seg. violation }
  11503. (
  11504. (taicpu(p).oper[0]^.typ = top_ref) and
  11505. { TODO: Can we detect which references become constants at this
  11506. stage so we don't have to do a blanket ban? }
  11507. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11508. (
  11509. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11510. (
  11511. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11512. not RefModified and
  11513. { If the reference also appears in the condition, then we know it's safe, otherwise
  11514. any kind of access violation would have occurred already }
  11515. Assigned(cond_p) and
  11516. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11517. (cond_p.typ = ait_instruction) and
  11518. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11519. { Just consider 2-operand comparison instructions for now to be safe }
  11520. (taicpu(cond_p).ops = 2) and
  11521. (
  11522. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11523. (
  11524. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11525. { Don't risk identical registers but different offsets, as we may have constructs
  11526. such as buffer streams with things like length fields that indicate whether
  11527. any more data follows. And there are probably some contrived examples where
  11528. writing to offsets behind the one being read also lead to access violations }
  11529. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11530. (
  11531. { Check that we're not modifying a register that appears in the reference }
  11532. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11533. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11534. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11535. )
  11536. )
  11537. )
  11538. )
  11539. )
  11540. )
  11541. );
  11542. end;
  11543. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11544. begin
  11545. { Update integer registers, ignoring deallocations }
  11546. repeat
  11547. while assigned(p) and
  11548. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11549. (p.typ = ait_label) or
  11550. ((p.typ = ait_marker) and
  11551. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11552. p := tai(p.next);
  11553. while assigned(p) and
  11554. (p.typ=ait_RegAlloc) Do
  11555. begin
  11556. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11557. begin
  11558. case tai_regalloc(p).ratype of
  11559. ra_alloc :
  11560. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11561. else
  11562. ;
  11563. end;
  11564. end;
  11565. p := tai(p.next);
  11566. end;
  11567. until not(assigned(p)) or
  11568. (not(p.typ in SkipInstr) and
  11569. not((p.typ = ait_label) and
  11570. labelCanBeSkipped(tai_label(p))));
  11571. end;
  11572. {$ifndef 8086}
  11573. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11574. begin
  11575. Result := False;
  11576. EndJump := nil;
  11577. BlockStop := nil;
  11578. while (BlockStart <> fOptimizer.BlockEnd) and
  11579. { stop on labels }
  11580. (BlockStart.typ <> ait_label) do
  11581. begin
  11582. { Keep track of all integer registers that are used }
  11583. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11584. if BlockStart.typ = ait_instruction then
  11585. begin
  11586. if (taicpu(BlockStart).opcode = A_JMP) then
  11587. begin
  11588. if not IsJumpToLabel(taicpu(BlockStart)) or
  11589. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11590. Exit;
  11591. EndJump := BlockStart;
  11592. Break;
  11593. end
  11594. { Check to see if we have a valid MOV instruction instead }
  11595. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11596. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11597. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11598. begin
  11599. Exit;
  11600. end
  11601. else
  11602. { This will be a valid MOV }
  11603. fAllocationRange := BlockStart;
  11604. end;
  11605. OneBeforeBlock := BlockStart;
  11606. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11607. end;
  11608. if (BlockStart = fOptimizer.BlockEnd) then
  11609. Exit;
  11610. BlockStop := BlockStart;
  11611. Result := True;
  11612. end;
  11613. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  11614. var
  11615. hp1: tai;
  11616. RefModified: Boolean;
  11617. begin
  11618. Result := 0;
  11619. hp1 := BlockStart;
  11620. RefModified := False; { As long as the condition is inverted, this can be reset }
  11621. while assigned(hp1) and
  11622. (hp1 <> BlockStop) do
  11623. begin
  11624. case hp1.typ of
  11625. ait_instruction:
  11626. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11627. begin
  11628. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  11629. begin
  11630. Inc(Result);
  11631. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11632. Assigned(fCondition) and
  11633. { Will have 2 operands }
  11634. (
  11635. (
  11636. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  11637. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  11638. ) or
  11639. (
  11640. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  11641. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  11642. )
  11643. ) then
  11644. { It is no longer safe to use the reference in the condition.
  11645. this prevents problems such as:
  11646. mov (%reg),%reg
  11647. mov (%reg),...
  11648. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11649. (fixes #40165)
  11650. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11651. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11652. }
  11653. RefModified := True;
  11654. end
  11655. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11656. { CMOV with constants grows the code size }
  11657. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  11658. begin
  11659. { Register was reserved by TryCMOVConst and
  11660. stored on ConstRegs }
  11661. end
  11662. else
  11663. begin
  11664. Result := -1;
  11665. Exit;
  11666. end;
  11667. end
  11668. else
  11669. begin
  11670. Result := -1;
  11671. Exit;
  11672. end;
  11673. else
  11674. { Most likely an align };
  11675. end;
  11676. fOptimizer.GetNextInstruction(hp1, hp1);
  11677. end;
  11678. end;
  11679. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  11680. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  11681. (this is done as a separate stage because the double types are extensions of the branching type,
  11682. but we can't discount the conditional jump until the last step) }
  11683. procedure EvaluateBranchingType;
  11684. begin
  11685. Inc(CMOVScore);
  11686. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  11687. { Too many instructions to be worthwhile }
  11688. fState := tsInvalid;
  11689. end;
  11690. var
  11691. hp1: tai;
  11692. Count: Integer;
  11693. begin
  11694. { Table of valid CMOV block types
  11695. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  11696. ---------- --------- --------- --------- --------- ---------
  11697. tsSimple X Yes X X X
  11698. tsDetour = 1st X X X X
  11699. tsBranching <> Mid Yes X X X
  11700. tsDouble End-label Yes * Yes X Yes
  11701. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  11702. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  11703. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  11704. * Only one reference allowed
  11705. }
  11706. hp1 := nil; { To prevent compiler warnings }
  11707. Optimizer.CopyUsedRegs(RegisterTracking);
  11708. fOptimizer := Optimizer;
  11709. fLabel := AFirstLabel;
  11710. CMOVScore := 0;
  11711. ConstCount := 0;
  11712. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11713. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11714. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11715. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11716. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11717. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11718. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11719. fInsertionPoint := p_initialjump;
  11720. fCondition := nil;
  11721. fInitialJump := p_initialjump;
  11722. fFirstMovBlock := p_initialmov;
  11723. fFirstMovBlockStop := nil;
  11724. fSecondJump := nil;
  11725. fSecondMovBlock := nil;
  11726. fSecondMovBlockStop := nil;
  11727. fMidLabel := nil;
  11728. fSecondJump := nil;
  11729. fSecondMovBlock := nil;
  11730. fEndLabel := nil;
  11731. fAllocationRange := nil;
  11732. { Assume it all goes horribly wrong! }
  11733. fState := tsInvalid;
  11734. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  11735. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  11736. 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
  11737. begin
  11738. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11739. for Count := 0 to 1 do
  11740. with taicpu(fCondition).oper[Count]^ do
  11741. case typ of
  11742. top_reg:
  11743. if getregtype(reg) = R_INTREGISTER then
  11744. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11745. top_ref:
  11746. begin
  11747. if
  11748. {$ifdef x86_64}
  11749. (ref^.base <> NR_RIP) and
  11750. {$endif x86_64}
  11751. (ref^.base <> NR_NO) then
  11752. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11753. if (ref^.index <> NR_NO) then
  11754. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11755. end
  11756. else
  11757. ;
  11758. end;
  11759. { When inserting instructions before hp_prev, try to insert them
  11760. before the allocation of the FLAGS register }
  11761. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  11762. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  11763. { If not found, set it equal to the condition so it's something sensible }
  11764. fInsertionPoint := fCondition;
  11765. { When dealing with a comparison against zero, take note of the
  11766. instruction before it to see if we can move instructions further
  11767. back in order to benefit PostPeepholeOptTestOr.
  11768. }
  11769. if (
  11770. (
  11771. (taicpu(fCondition).opcode = A_CMP) and
  11772. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  11773. ) or
  11774. (
  11775. (taicpu(fCondition).opcode = A_TEST) and
  11776. (
  11777. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  11778. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  11779. )
  11780. )
  11781. ) and
  11782. Optimizer.GetLastInstruction(fCondition, hp1) then
  11783. begin
  11784. { These instructions set the zero flag if the result is zero }
  11785. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11786. begin
  11787. fInsertionPoint := hp1;
  11788. { Also mark all the registers in this previous instruction
  11789. as 'in use', even if they've just been deallocated }
  11790. for Count := 0 to 1 do
  11791. with taicpu(hp1).oper[Count]^ do
  11792. case typ of
  11793. top_reg:
  11794. if getregtype(reg) = R_INTREGISTER then
  11795. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11796. top_ref:
  11797. begin
  11798. if
  11799. {$ifdef x86_64}
  11800. (ref^.base <> NR_RIP) and
  11801. {$endif x86_64}
  11802. (ref^.base <> NR_NO) then
  11803. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11804. if (ref^.index <> NR_NO) then
  11805. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11806. end
  11807. else
  11808. ;
  11809. end;
  11810. end;
  11811. end;
  11812. end
  11813. else
  11814. fCondition := nil;
  11815. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  11816. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  11817. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  11818. { If not found, set it equal to p so it's something sensible }
  11819. fInsertionPoint := hp1;
  11820. hp1 := p_initialmov;
  11821. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  11822. Exit;
  11823. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  11824. if (hp1.typ <> ait_label) then { should be on a jump }
  11825. begin
  11826. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  11827. { Need a label afterwards }
  11828. Exit;
  11829. end
  11830. else
  11831. fMidLabel := hp1;
  11832. if tai_label(fMidLabel).labsym <> AFirstLabel then
  11833. { Not the correct label }
  11834. fMidLabel := nil;
  11835. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  11836. { If there's neither a 2nd jump nor correct label, then it's invalid
  11837. (see above table) }
  11838. Exit;
  11839. { Analyse the first block of MOVs more closely }
  11840. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  11841. if Assigned(fSecondJump) then
  11842. begin
  11843. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  11844. begin
  11845. fState := tsDetour
  11846. end
  11847. else
  11848. begin
  11849. { Need the correct mid-label for this one }
  11850. if not Assigned(fMidLabel) then
  11851. Exit;
  11852. fState := tsBranching;
  11853. end;
  11854. end
  11855. else
  11856. { No jump. but mid-label is present }
  11857. fState := tsSimple;
  11858. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  11859. begin
  11860. { Invalid or too many instructions to be worthwhile }
  11861. fState := tsInvalid;
  11862. Exit;
  11863. end;
  11864. { check further for
  11865. jCC xxx
  11866. <several movs 1>
  11867. jmp yyy
  11868. xxx:
  11869. <several movs 2>
  11870. yyy:
  11871. etc.
  11872. }
  11873. if (fState = tsBranching) and
  11874. { Estimate for required savings for extra jump }
  11875. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  11876. { Only one reference is allowed for double blocks }
  11877. (AFirstLabel.getrefs = 1) then
  11878. begin
  11879. Optimizer.GetNextInstruction(fMidLabel, hp1);
  11880. fSecondMovBlock := hp1;
  11881. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  11882. begin
  11883. EvaluateBranchingType;
  11884. Exit;
  11885. end;
  11886. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  11887. if (hp1.typ <> ait_label) then { should be on a jump }
  11888. begin
  11889. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  11890. begin
  11891. { Need a label afterwards }
  11892. EvaluateBranchingType;
  11893. Exit;
  11894. end;
  11895. end
  11896. else
  11897. fEndLabel := hp1;
  11898. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  11899. { Second jump doesn't go to the end }
  11900. fEndLabel := nil;
  11901. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  11902. begin
  11903. { If there's neither a 3rd jump nor correct end label, then it's
  11904. not a invalid double block, but is a valid single branching
  11905. block (see above table) }
  11906. EvaluateBranchingType;
  11907. Exit;
  11908. end;
  11909. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  11910. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  11911. { Invalid or too many instructions to be worthwhile }
  11912. Exit;
  11913. Inc(CMOVScore, Count);
  11914. if Assigned(fThirdJump) then
  11915. begin
  11916. if not Assigned(fSecondJump) then
  11917. fState := tsDoubleSecondBranching
  11918. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  11919. fState := tsDoubleBranchSame
  11920. else
  11921. fState := tsDoubleBranchDifferent;
  11922. end
  11923. else
  11924. fState := tsDouble;
  11925. end;
  11926. if fState = tsBranching then
  11927. EvaluateBranchingType;
  11928. end;
  11929. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  11930. new register to store the constant }
  11931. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  11932. var
  11933. RegSize: TSubRegister;
  11934. CurrentVal: TCGInt;
  11935. ANewReg: TRegister;
  11936. X: ShortInt;
  11937. begin
  11938. Result := False;
  11939. if not MatchOpType(taicpu(p), top_const, top_reg) then
  11940. Exit;
  11941. if ConstCount >= MAX_CMOV_REGISTERS then
  11942. { Arrays are full }
  11943. Exit;
  11944. { Remember that CMOV can't encode 8-bit registers }
  11945. case taicpu(p).opsize of
  11946. S_W:
  11947. RegSize := R_SUBW;
  11948. S_L:
  11949. RegSize := R_SUBD;
  11950. {$ifdef x86_64}
  11951. S_Q:
  11952. RegSize := R_SUBQ;
  11953. {$endif x86_64}
  11954. else
  11955. InternalError(2021100401);
  11956. end;
  11957. { See if the value has already been reserved for another CMOV instruction }
  11958. CurrentVal := taicpu(p).oper[0]^.val;
  11959. for X := 0 to ConstCount - 1 do
  11960. if ConstVals[X] = CurrentVal then
  11961. begin
  11962. ConstRegs[ConstCount] := ConstRegs[X];
  11963. ConstSizes[ConstCount] := RegSize;
  11964. ConstVals[ConstCount] := CurrentVal;
  11965. Inc(ConstCount);
  11966. Inc(Count);
  11967. Result := True;
  11968. Exit;
  11969. end;
  11970. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  11971. if ANewReg = NR_NO then
  11972. { No free registers }
  11973. Exit;
  11974. { Reserve the register so subsequent TryCMOVConst calls don't all end
  11975. up vying for the same register }
  11976. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  11977. ConstRegs[ConstCount] := ANewReg;
  11978. ConstSizes[ConstCount] := RegSize;
  11979. ConstVals[ConstCount] := CurrentVal;
  11980. Inc(ConstCount);
  11981. Inc(Count);
  11982. Result := True;
  11983. end;
  11984. destructor TCMOVTracking.Done;
  11985. begin
  11986. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  11987. end;
  11988. procedure TCMOVTracking.Process(out new_p: tai);
  11989. var
  11990. Count, Writes: LongInt;
  11991. RegMatch: Boolean;
  11992. hp1, hp_new: tai;
  11993. inverted_condition, condition: TAsmCond;
  11994. begin
  11995. if (fState in [tsInvalid, tsProcessed]) then
  11996. InternalError(2023110701);
  11997. { Repurpose RegisterTracking to mark registers that we've defined }
  11998. RegisterTracking[R_INTREGISTER].Clear;
  11999. Count := 0;
  12000. Writes := 0;
  12001. condition := taicpu(fInitialJump).condition;
  12002. inverted_condition := inverse_cond(condition);
  12003. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12004. doesn't get CMOVs in this case }
  12005. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12006. begin
  12007. { Include the jump in the flag tracking }
  12008. if Assigned(fThirdJump) then
  12009. begin
  12010. if (fState = tsDoubleBranchSame) then
  12011. begin
  12012. { Will be an unconditional jump, so track to the instruction before it }
  12013. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12014. InternalError(2023110710);
  12015. end
  12016. else
  12017. hp1 := fThirdJump;
  12018. end
  12019. else
  12020. hp1 := fSecondMovBlockStop;
  12021. end
  12022. else
  12023. begin
  12024. { Include a conditional jump in the flag tracking }
  12025. if Assigned(fSecondJump) then
  12026. begin
  12027. if (fState = tsDetour) then
  12028. begin
  12029. { Will be an unconditional jump, so track to the instruction before it }
  12030. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12031. InternalError(2023110711);
  12032. end
  12033. else
  12034. hp1 := fSecondJump;
  12035. end
  12036. else
  12037. hp1 := fFirstMovBlockStop;
  12038. end;
  12039. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12040. { Process the second set of MOVs first, because if a destination
  12041. register is shared between the first and second MOV sets, it is more
  12042. efficient to turn the first one into a MOV instruction and place it
  12043. before the CMP if possible, but we won't know which registers are
  12044. shared until we've processed at least one list, so we might as well
  12045. make it the second one since that won't be modified again. }
  12046. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12047. begin
  12048. hp1 := fSecondMovBlock;
  12049. repeat
  12050. if not Assigned(hp1) then
  12051. InternalError(2018062902);
  12052. if (hp1.typ = ait_instruction) then
  12053. begin
  12054. { Extra safeguard }
  12055. if (taicpu(hp1).opcode <> A_MOV) then
  12056. InternalError(2018062903);
  12057. { Note: tsDoubleBranchDifferent is essentially identical to
  12058. tsBranching and the 2nd block is best left largely
  12059. untouched, but we need to evaluate which registers the MOVs
  12060. write to in order to track what would be complementary CMOV
  12061. pairs that can be further optimised. [Kit] }
  12062. if fState <> tsDoubleBranchDifferent then
  12063. begin
  12064. if taicpu(hp1).oper[0]^.typ = top_const then
  12065. begin
  12066. RegMatch := False;
  12067. for Count := 0 to ConstCount - 1 do
  12068. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12069. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12070. begin
  12071. RegMatch := True;
  12072. { If it's in RegisterTracking, then this register
  12073. is being used more than once and hence has
  12074. already had its value defined (it gets added to
  12075. UsedRegs through AllocRegBetween below) }
  12076. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12077. begin
  12078. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12079. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12080. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12081. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12082. ConstMovs[Count] := hp_new;
  12083. end
  12084. else
  12085. { We just need an instruction between hp_prev and hp1
  12086. where we know the register is marked as in use }
  12087. hp_new := fSecondMovBlock;
  12088. { Keep track of largest write for this register so it can be optimised later }
  12089. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12090. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12091. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12092. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12093. Break;
  12094. end;
  12095. if not RegMatch then
  12096. InternalError(2021100411);
  12097. end;
  12098. taicpu(hp1).opcode := A_CMOVcc;
  12099. taicpu(hp1).condition := condition;
  12100. end;
  12101. { Store these writes to search for duplicates later on }
  12102. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12103. Inc(Writes);
  12104. end;
  12105. fOptimizer.GetNextInstruction(hp1, hp1);
  12106. until (hp1 = fSecondMovBlockStop);
  12107. end;
  12108. { Now do the first set of MOVs }
  12109. hp1 := fFirstMovBlock;
  12110. repeat
  12111. if not Assigned(hp1) then
  12112. InternalError(2018062904);
  12113. if (hp1.typ = ait_instruction) then
  12114. begin
  12115. RegMatch := False;
  12116. { Extra safeguard }
  12117. if (taicpu(hp1).opcode <> A_MOV) then
  12118. InternalError(2018062905);
  12119. { Search through the RegWrites list to see if there are any
  12120. opposing CMOV pairs that write to the same register }
  12121. for Count := 0 to Writes - 1 do
  12122. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12123. begin
  12124. { We have a match. Keep this as a MOV }
  12125. { Move ahead in preparation }
  12126. fOptimizer.GetNextInstruction(hp1, hp1);
  12127. RegMatch := True;
  12128. Break;
  12129. end;
  12130. if RegMatch then
  12131. Continue;
  12132. if taicpu(hp1).oper[0]^.typ = top_const then
  12133. begin
  12134. for Count := 0 to ConstCount - 1 do
  12135. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12136. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12137. begin
  12138. RegMatch := True;
  12139. { If it's in RegisterTracking, then this register is
  12140. being used more than once and hence has already had
  12141. its value defined (it gets added to UsedRegs through
  12142. AllocRegBetween below) }
  12143. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12144. begin
  12145. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12146. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12147. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12148. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12149. ConstMovs[Count] := hp_new;
  12150. end
  12151. else
  12152. { We just need an instruction between hp_prev and hp1
  12153. where we know the register is marked as in use }
  12154. hp_new := fFirstMovBlock;
  12155. { Keep track of largest write for this register so it can be optimised later }
  12156. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12157. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12158. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12159. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12160. Break;
  12161. end;
  12162. if not RegMatch then
  12163. InternalError(2021100412);
  12164. end;
  12165. taicpu(hp1).opcode := A_CMOVcc;
  12166. taicpu(hp1).condition := inverted_condition;
  12167. if (fState = tsDoubleBranchDifferent) then
  12168. begin
  12169. { Store these writes to search for duplicates later on }
  12170. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12171. Inc(Writes);
  12172. end;
  12173. end;
  12174. fOptimizer.GetNextInstruction(hp1, hp1);
  12175. until (hp1 = fFirstMovBlockStop);
  12176. { Update initialisation MOVs to the smallest possible size }
  12177. for Count := 0 to ConstCount - 1 do
  12178. if Assigned(ConstMovs[Count]) then
  12179. begin
  12180. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12181. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12182. end;
  12183. case fState of
  12184. tsSimple:
  12185. begin
  12186. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12187. { No branch to delete }
  12188. end;
  12189. tsDetour:
  12190. begin
  12191. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12192. { Preserve jump }
  12193. end;
  12194. tsBranching, tsDoubleBranchDifferent:
  12195. begin
  12196. if (fState = tsBranching) then
  12197. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12198. else
  12199. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12200. taicpu(fSecondJump).opcode := A_JCC;
  12201. taicpu(fSecondJump).condition := inverted_condition;
  12202. end;
  12203. tsDouble, tsDoubleBranchSame:
  12204. begin
  12205. if (fState = tsDouble) then
  12206. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12207. else
  12208. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12209. { Delete second jump }
  12210. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12211. fOptimizer.RemoveInstruction(fSecondJump);
  12212. end;
  12213. tsDoubleSecondBranching:
  12214. begin
  12215. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12216. { Delete second jump, preserve third jump as conditional }
  12217. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12218. fOptimizer.RemoveInstruction(fSecondJump);
  12219. taicpu(fThirdJump).opcode := A_JCC;
  12220. taicpu(fThirdJump).condition := condition;
  12221. end;
  12222. else
  12223. InternalError(2023110720);
  12224. end;
  12225. { Now we can safely decrement the reference count }
  12226. tasmlabel(fLabel).decrefs;
  12227. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12228. { Remove the original jump }
  12229. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12230. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12231. fState := tsProcessed;
  12232. end;
  12233. {$endif 8086}
  12234. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12235. var
  12236. hp1,hp2: tai;
  12237. carryadd_opcode : TAsmOp;
  12238. symbol: TAsmSymbol;
  12239. increg, tmpreg: TRegister;
  12240. {$ifndef i8086}
  12241. CMOVTracking: PCMOVTracking;
  12242. hp3,hp4,hp5: tai;
  12243. {$endif i8086}
  12244. TempBool: Boolean;
  12245. begin
  12246. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12247. DoJumpOptimizations(p, TempBool) then
  12248. Exit(True);
  12249. result:=false;
  12250. if GetNextInstruction(p,hp1) then
  12251. begin
  12252. if (hp1.typ=ait_label) then
  12253. begin
  12254. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12255. Exit;
  12256. end
  12257. else if (hp1.typ<>ait_instruction) then
  12258. Exit;
  12259. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12260. if (
  12261. (
  12262. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12263. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12264. (Taicpu(hp1).oper[0]^.val=1)
  12265. ) or
  12266. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12267. ) and
  12268. GetNextInstruction(hp1,hp2) and
  12269. (hp2.typ = ait_label) and
  12270. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  12271. { jb @@1 cmc
  12272. inc/dec operand --> adc/sbb operand,0
  12273. @@1:
  12274. ... and ...
  12275. jnb @@1
  12276. inc/dec operand --> adc/sbb operand,0
  12277. @@1: }
  12278. begin
  12279. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12280. begin
  12281. case taicpu(hp1).opcode of
  12282. A_INC,
  12283. A_ADD:
  12284. carryadd_opcode:=A_ADC;
  12285. A_DEC,
  12286. A_SUB:
  12287. carryadd_opcode:=A_SBB;
  12288. else
  12289. InternalError(2021011001);
  12290. end;
  12291. Taicpu(p).clearop(0);
  12292. Taicpu(p).ops:=0;
  12293. Taicpu(p).is_jmp:=false;
  12294. Taicpu(p).opcode:=A_CMC;
  12295. Taicpu(p).condition:=C_NONE;
  12296. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12297. Taicpu(hp1).ops:=2;
  12298. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12299. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12300. else
  12301. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12302. Taicpu(hp1).loadconst(0,0);
  12303. Taicpu(hp1).opcode:=carryadd_opcode;
  12304. result:=true;
  12305. exit;
  12306. end
  12307. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12308. begin
  12309. case taicpu(hp1).opcode of
  12310. A_INC,
  12311. A_ADD:
  12312. carryadd_opcode:=A_ADC;
  12313. A_DEC,
  12314. A_SUB:
  12315. carryadd_opcode:=A_SBB;
  12316. else
  12317. InternalError(2021011002);
  12318. end;
  12319. Taicpu(hp1).ops:=2;
  12320. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12321. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12322. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12323. else
  12324. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12325. Taicpu(hp1).loadconst(0,0);
  12326. Taicpu(hp1).opcode:=carryadd_opcode;
  12327. RemoveCurrentP(p, hp1);
  12328. result:=true;
  12329. exit;
  12330. end
  12331. {
  12332. jcc @@1 setcc tmpreg
  12333. inc/dec/add/sub operand -> (movzx tmpreg)
  12334. @@1: add/sub tmpreg,operand
  12335. While this increases code size slightly, it makes the code much faster if the
  12336. jump is unpredictable
  12337. }
  12338. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12339. begin
  12340. { search for an available register which is volatile }
  12341. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12342. if increg <> NR_NO then
  12343. begin
  12344. { We don't need to check if tmpreg is in hp1 or not, because
  12345. it will be marked as in use at p (if not, this is
  12346. indictive of a compiler bug). }
  12347. TAsmLabel(symbol).decrefs;
  12348. Taicpu(p).clearop(0);
  12349. Taicpu(p).ops:=1;
  12350. Taicpu(p).is_jmp:=false;
  12351. Taicpu(p).opcode:=A_SETcc;
  12352. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12353. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12354. Taicpu(p).loadreg(0,increg);
  12355. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12356. begin
  12357. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12358. R_SUBW:
  12359. begin
  12360. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12361. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12362. end;
  12363. R_SUBD:
  12364. begin
  12365. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12366. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12367. end;
  12368. {$ifdef x86_64}
  12369. R_SUBQ:
  12370. begin
  12371. { MOVZX doesn't have a 64-bit variant, because
  12372. the 32-bit version implicitly zeroes the
  12373. upper 32-bits of the destination register }
  12374. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12375. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12376. setsubreg(tmpreg, R_SUBQ);
  12377. end;
  12378. {$endif x86_64}
  12379. else
  12380. Internalerror(2020030601);
  12381. end;
  12382. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12383. asml.InsertAfter(hp2,p);
  12384. end
  12385. else
  12386. tmpreg := increg;
  12387. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12388. begin
  12389. Taicpu(hp1).ops:=2;
  12390. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12391. end;
  12392. Taicpu(hp1).loadreg(0,tmpreg);
  12393. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12394. Result := True;
  12395. { p is no longer a Jcc instruction, so exit }
  12396. Exit;
  12397. end;
  12398. end;
  12399. end;
  12400. { Detect the following:
  12401. jmp<cond> @Lbl1
  12402. jmp @Lbl2
  12403. ...
  12404. @Lbl1:
  12405. ret
  12406. Change to:
  12407. jmp<inv_cond> @Lbl2
  12408. ret
  12409. }
  12410. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12411. begin
  12412. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12413. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12414. MatchInstruction(hp2,A_RET,[S_NO]) then
  12415. begin
  12416. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12417. { Change label address to that of the unconditional jump }
  12418. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12419. TAsmLabel(symbol).DecRefs;
  12420. taicpu(hp1).opcode := A_RET;
  12421. taicpu(hp1).is_jmp := false;
  12422. taicpu(hp1).ops := taicpu(hp2).ops;
  12423. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12424. case taicpu(hp2).ops of
  12425. 0:
  12426. taicpu(hp1).clearop(0);
  12427. 1:
  12428. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12429. else
  12430. internalerror(2016041302);
  12431. end;
  12432. end;
  12433. {$ifndef i8086}
  12434. end
  12435. {
  12436. convert
  12437. j<c> .L1
  12438. mov 1,reg
  12439. jmp .L2
  12440. .L1
  12441. mov 0,reg
  12442. .L2
  12443. into
  12444. mov 0,reg
  12445. set<not(c)> reg
  12446. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12447. would destroy the flag contents
  12448. }
  12449. else if MatchInstruction(hp1,A_MOV,[]) and
  12450. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12451. {$ifdef i386}
  12452. (
  12453. { Under i386, ESI, EDI, EBP and ESP
  12454. don't have an 8-bit representation }
  12455. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12456. ) and
  12457. {$endif i386}
  12458. (taicpu(hp1).oper[0]^.val=1) and
  12459. GetNextInstruction(hp1,hp2) and
  12460. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12461. GetNextInstruction(hp2,hp3) and
  12462. (hp3.typ=ait_label) and
  12463. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12464. (tai_label(hp3).labsym.getrefs=1) and
  12465. GetNextInstruction(hp3,hp4) and
  12466. MatchInstruction(hp4,A_MOV,[]) and
  12467. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12468. (taicpu(hp4).oper[0]^.val=0) and
  12469. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12470. GetNextInstruction(hp4,hp5) and
  12471. (hp5.typ=ait_label) and
  12472. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12473. (tai_label(hp5).labsym.getrefs=1) then
  12474. begin
  12475. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12476. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12477. { remove last label }
  12478. RemoveInstruction(hp5);
  12479. { remove second label }
  12480. RemoveInstruction(hp3);
  12481. { remove jmp }
  12482. RemoveInstruction(hp2);
  12483. if taicpu(hp1).opsize=S_B then
  12484. RemoveInstruction(hp1)
  12485. else
  12486. taicpu(hp1).loadconst(0,0);
  12487. taicpu(hp4).opcode:=A_SETcc;
  12488. taicpu(hp4).opsize:=S_B;
  12489. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12490. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12491. taicpu(hp4).opercnt:=1;
  12492. taicpu(hp4).ops:=1;
  12493. taicpu(hp4).freeop(1);
  12494. RemoveCurrentP(p);
  12495. Result:=true;
  12496. exit;
  12497. end
  12498. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12499. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12500. begin
  12501. { check for
  12502. jCC xxx
  12503. <several movs>
  12504. xxx:
  12505. Also spot:
  12506. Jcc xxx
  12507. <several movs>
  12508. jmp xxx
  12509. Change to:
  12510. <several cmovs with inverted condition>
  12511. jmp xxx (only for the 2nd case)
  12512. }
  12513. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12514. if CMOVTracking^.State <> tsInvalid then
  12515. begin
  12516. CMovTracking^.Process(p);
  12517. Result := True;
  12518. end;
  12519. CMOVTracking^.Done;
  12520. {$endif i8086}
  12521. end;
  12522. end;
  12523. end;
  12524. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12525. var
  12526. hp1,hp2,hp3: tai;
  12527. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12528. NewSize: TOpSize;
  12529. NewRegSize: TSubRegister;
  12530. Limit: TCgInt;
  12531. SwapOper: POper;
  12532. begin
  12533. result:=false;
  12534. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12535. GetNextInstruction(p,hp1) and
  12536. (hp1.typ = ait_instruction);
  12537. if reg_and_hp1_is_instr and
  12538. (
  12539. (taicpu(hp1).opcode <> A_LEA) or
  12540. { If the LEA instruction can be converted into an arithmetic instruction,
  12541. it may be possible to then fold it. }
  12542. (
  12543. { If the flags register is in use, don't change the instruction
  12544. to an ADD otherwise this will scramble the flags. [Kit] }
  12545. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12546. ConvertLEA(taicpu(hp1))
  12547. )
  12548. ) and
  12549. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12550. GetNextInstruction(hp1,hp2) and
  12551. MatchInstruction(hp2,A_MOV,[]) and
  12552. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12553. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12554. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12555. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12556. {$ifdef i386}
  12557. { not all registers have byte size sub registers on i386 }
  12558. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12559. {$endif i386}
  12560. (((taicpu(hp1).ops=2) and
  12561. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12562. ((taicpu(hp1).ops=1) and
  12563. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12564. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12565. begin
  12566. { change movsX/movzX reg/ref, reg2
  12567. add/sub/or/... reg3/$const, reg2
  12568. mov reg2 reg/ref
  12569. to add/sub/or/... reg3/$const, reg/ref }
  12570. { by example:
  12571. movswl %si,%eax movswl %si,%eax p
  12572. decl %eax addl %edx,%eax hp1
  12573. movw %ax,%si movw %ax,%si hp2
  12574. ->
  12575. movswl %si,%eax movswl %si,%eax p
  12576. decw %eax addw %edx,%eax hp1
  12577. movw %ax,%si movw %ax,%si hp2
  12578. }
  12579. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12580. {
  12581. ->
  12582. movswl %si,%eax movswl %si,%eax p
  12583. decw %si addw %dx,%si hp1
  12584. movw %ax,%si movw %ax,%si hp2
  12585. }
  12586. case taicpu(hp1).ops of
  12587. 1:
  12588. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12589. 2:
  12590. begin
  12591. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12592. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12593. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12594. end;
  12595. else
  12596. internalerror(2008042702);
  12597. end;
  12598. {
  12599. ->
  12600. decw %si addw %dx,%si p
  12601. }
  12602. DebugMsg(SPeepholeOptimization + 'var3',p);
  12603. RemoveCurrentP(p, hp1);
  12604. RemoveInstruction(hp2);
  12605. Result := True;
  12606. Exit;
  12607. end;
  12608. if reg_and_hp1_is_instr and
  12609. (taicpu(hp1).opcode = A_MOV) and
  12610. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12611. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12612. {$ifdef x86_64}
  12613. { check for implicit extension to 64 bit }
  12614. or
  12615. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12616. (taicpu(hp1).opsize=S_Q) and
  12617. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  12618. )
  12619. {$endif x86_64}
  12620. )
  12621. then
  12622. begin
  12623. { change
  12624. movx %reg1,%reg2
  12625. mov %reg2,%reg3
  12626. dealloc %reg2
  12627. into
  12628. movx %reg,%reg3
  12629. }
  12630. TransferUsedRegs(TmpUsedRegs);
  12631. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12632. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  12633. begin
  12634. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  12635. {$ifdef x86_64}
  12636. if (taicpu(p).opsize in [S_BL,S_WL]) and
  12637. (taicpu(hp1).opsize=S_Q) then
  12638. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  12639. else
  12640. {$endif x86_64}
  12641. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  12642. RemoveInstruction(hp1);
  12643. Result := True;
  12644. Exit;
  12645. end;
  12646. end;
  12647. if reg_and_hp1_is_instr and
  12648. ((taicpu(hp1).opcode=A_MOV) or
  12649. (taicpu(hp1).opcode=A_ADD) or
  12650. (taicpu(hp1).opcode=A_SUB) or
  12651. (taicpu(hp1).opcode=A_CMP) or
  12652. (taicpu(hp1).opcode=A_OR) or
  12653. (taicpu(hp1).opcode=A_XOR) or
  12654. (taicpu(hp1).opcode=A_AND)
  12655. ) and
  12656. (taicpu(hp1).oper[1]^.typ = top_reg) then
  12657. begin
  12658. AndTest := (taicpu(hp1).opcode=A_AND) and
  12659. GetNextInstruction(hp1, hp2) and
  12660. (hp2.typ = ait_instruction) and
  12661. (
  12662. (
  12663. (taicpu(hp2).opcode=A_TEST) and
  12664. (
  12665. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  12666. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  12667. (
  12668. { If the AND and TEST instructions share a constant, this is also valid }
  12669. (taicpu(hp1).oper[0]^.typ = top_const) and
  12670. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  12671. )
  12672. ) and
  12673. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12674. ) or
  12675. (
  12676. (taicpu(hp2).opcode=A_CMP) and
  12677. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  12678. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12679. )
  12680. );
  12681. { change
  12682. movx (oper),%reg2
  12683. and $x,%reg2
  12684. test %reg2,%reg2
  12685. dealloc %reg2
  12686. into
  12687. op %reg1,%reg3
  12688. if the second op accesses only the bits stored in reg1
  12689. }
  12690. if ((taicpu(p).oper[0]^.typ=top_reg) or
  12691. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  12692. (taicpu(hp1).oper[0]^.typ = top_const) and
  12693. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12694. AndTest then
  12695. begin
  12696. { Check if the AND constant is in range }
  12697. case taicpu(p).opsize of
  12698. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12699. begin
  12700. NewSize := S_B;
  12701. Limit := $FF;
  12702. end;
  12703. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12704. begin
  12705. NewSize := S_W;
  12706. Limit := $FFFF;
  12707. end;
  12708. {$ifdef x86_64}
  12709. S_LQ:
  12710. begin
  12711. NewSize := S_L;
  12712. Limit := $FFFFFFFF;
  12713. end;
  12714. {$endif x86_64}
  12715. else
  12716. InternalError(2021120303);
  12717. end;
  12718. if (
  12719. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  12720. { Check for negative operands }
  12721. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  12722. ) and
  12723. GetNextInstruction(hp2,hp3) and
  12724. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  12725. (taicpu(hp3).condition in [C_E,C_NE]) then
  12726. begin
  12727. TransferUsedRegs(TmpUsedRegs);
  12728. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12729. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12730. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  12731. begin
  12732. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  12733. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12734. taicpu(hp1).opcode := A_TEST;
  12735. taicpu(hp1).opsize := NewSize;
  12736. RemoveInstruction(hp2);
  12737. RemoveCurrentP(p, hp1);
  12738. Result:=true;
  12739. exit;
  12740. end;
  12741. end;
  12742. end;
  12743. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12744. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  12745. (taicpu(hp1).opsize=S_B)) or
  12746. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  12747. (taicpu(hp1).opsize=S_W))
  12748. {$ifdef x86_64}
  12749. or ((taicpu(p).opsize=S_LQ) and
  12750. (taicpu(hp1).opsize=S_L))
  12751. {$endif x86_64}
  12752. ) and
  12753. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  12754. begin
  12755. { change
  12756. movx %reg1,%reg2
  12757. op %reg2,%reg3
  12758. dealloc %reg2
  12759. into
  12760. op %reg1,%reg3
  12761. if the second op accesses only the bits stored in reg1
  12762. }
  12763. TransferUsedRegs(TmpUsedRegs);
  12764. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12765. if AndTest then
  12766. begin
  12767. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12768. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12769. end
  12770. else
  12771. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12772. if not RegUsed then
  12773. begin
  12774. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  12775. if taicpu(p).oper[0]^.typ=top_reg then
  12776. begin
  12777. case taicpu(hp1).opsize of
  12778. S_B:
  12779. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  12780. S_W:
  12781. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  12782. S_L:
  12783. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  12784. else
  12785. Internalerror(2020102301);
  12786. end;
  12787. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  12788. end
  12789. else
  12790. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  12791. RemoveCurrentP(p);
  12792. if AndTest then
  12793. RemoveInstruction(hp2);
  12794. result:=true;
  12795. exit;
  12796. end;
  12797. end
  12798. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12799. (
  12800. { Bitwise operations only }
  12801. (taicpu(hp1).opcode=A_AND) or
  12802. (taicpu(hp1).opcode=A_TEST) or
  12803. (
  12804. (taicpu(hp1).oper[0]^.typ = top_const) and
  12805. (
  12806. (taicpu(hp1).opcode=A_OR) or
  12807. (taicpu(hp1).opcode=A_XOR)
  12808. )
  12809. )
  12810. ) and
  12811. (
  12812. (taicpu(hp1).oper[0]^.typ = top_const) or
  12813. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  12814. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  12815. ) then
  12816. begin
  12817. { change
  12818. movx %reg2,%reg2
  12819. op const,%reg2
  12820. into
  12821. op const,%reg2 (smaller version)
  12822. movx %reg2,%reg2
  12823. also change
  12824. movx %reg1,%reg2
  12825. and/test (oper),%reg2
  12826. dealloc %reg2
  12827. into
  12828. and/test (oper),%reg1
  12829. }
  12830. case taicpu(p).opsize of
  12831. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12832. begin
  12833. NewSize := S_B;
  12834. NewRegSize := R_SUBL;
  12835. Limit := $FF;
  12836. end;
  12837. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12838. begin
  12839. NewSize := S_W;
  12840. NewRegSize := R_SUBW;
  12841. Limit := $FFFF;
  12842. end;
  12843. {$ifdef x86_64}
  12844. S_LQ:
  12845. begin
  12846. NewSize := S_L;
  12847. NewRegSize := R_SUBD;
  12848. Limit := $FFFFFFFF;
  12849. end;
  12850. {$endif x86_64}
  12851. else
  12852. Internalerror(2021120302);
  12853. end;
  12854. TransferUsedRegs(TmpUsedRegs);
  12855. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12856. if AndTest then
  12857. begin
  12858. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12859. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12860. end
  12861. else
  12862. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12863. if
  12864. (
  12865. (taicpu(p).opcode = A_MOVZX) and
  12866. (
  12867. (taicpu(hp1).opcode=A_AND) or
  12868. (taicpu(hp1).opcode=A_TEST)
  12869. ) and
  12870. not (
  12871. { If both are references, then the final instruction will have
  12872. both operands as references, which is not allowed }
  12873. (taicpu(p).oper[0]^.typ = top_ref) and
  12874. (taicpu(hp1).oper[0]^.typ = top_ref)
  12875. ) and
  12876. not RegUsed
  12877. ) or
  12878. (
  12879. (
  12880. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  12881. not RegUsed
  12882. ) and
  12883. (taicpu(p).oper[0]^.typ = top_reg) and
  12884. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12885. (taicpu(hp1).oper[0]^.typ = top_const) and
  12886. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  12887. ) then
  12888. begin
  12889. {$if defined(i386) or defined(i8086)}
  12890. { If the target size is 8-bit, make sure we can actually encode it }
  12891. 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
  12892. Exit;
  12893. {$endif i386 or i8086}
  12894. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  12895. taicpu(hp1).opsize := NewSize;
  12896. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12897. if AndTest then
  12898. begin
  12899. RemoveInstruction(hp2);
  12900. if not RegUsed then
  12901. begin
  12902. taicpu(hp1).opcode := A_TEST;
  12903. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  12904. begin
  12905. { Make sure the reference is the second operand }
  12906. SwapOper := taicpu(hp1).oper[0];
  12907. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  12908. taicpu(hp1).oper[1] := SwapOper;
  12909. end;
  12910. end;
  12911. end;
  12912. case taicpu(hp1).oper[0]^.typ of
  12913. top_reg:
  12914. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  12915. top_const:
  12916. { For the AND/TEST case }
  12917. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  12918. else
  12919. ;
  12920. end;
  12921. if RegUsed then
  12922. begin
  12923. AsmL.Remove(p);
  12924. AsmL.InsertAfter(p, hp1);
  12925. p := hp1;
  12926. end
  12927. else
  12928. RemoveCurrentP(p, hp1);
  12929. result:=true;
  12930. exit;
  12931. end;
  12932. end;
  12933. end;
  12934. if reg_and_hp1_is_instr and
  12935. (taicpu(p).oper[0]^.typ = top_reg) and
  12936. (
  12937. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  12938. ) and
  12939. (taicpu(hp1).oper[0]^.typ = top_const) and
  12940. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12941. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12942. { Minimum shift value allowed is the bit difference between the sizes }
  12943. (taicpu(hp1).oper[0]^.val >=
  12944. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12945. 8 * (
  12946. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  12947. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12948. )
  12949. ) then
  12950. begin
  12951. { For:
  12952. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  12953. shl/sal ##, %reg1
  12954. Remove the movsx/movzx instruction if the shift overwrites the
  12955. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  12956. }
  12957. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  12958. RemoveCurrentP(p, hp1);
  12959. Result := True;
  12960. Exit;
  12961. end
  12962. else if reg_and_hp1_is_instr and
  12963. (taicpu(p).oper[0]^.typ = top_reg) and
  12964. (
  12965. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  12966. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  12967. ) and
  12968. (taicpu(hp1).oper[0]^.typ = top_const) and
  12969. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12970. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12971. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  12972. (taicpu(hp1).oper[0]^.val <
  12973. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12974. 8 * (
  12975. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12976. )
  12977. ) then
  12978. begin
  12979. { For:
  12980. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  12981. sar ##, %reg1 shr ##, %reg1
  12982. Move the shift to before the movx instruction if the shift value
  12983. is not too large.
  12984. }
  12985. asml.Remove(hp1);
  12986. asml.InsertBefore(hp1, p);
  12987. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12988. case taicpu(p).opsize of
  12989. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  12990. taicpu(hp1).opsize := S_B;
  12991. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  12992. taicpu(hp1).opsize := S_W;
  12993. {$ifdef x86_64}
  12994. S_LQ:
  12995. taicpu(hp1).opsize := S_L;
  12996. {$endif}
  12997. else
  12998. InternalError(2020112401);
  12999. end;
  13000. if (taicpu(hp1).opcode = A_SHR) then
  13001. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13002. else
  13003. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13004. Result := True;
  13005. end;
  13006. if reg_and_hp1_is_instr and
  13007. (taicpu(p).oper[0]^.typ = top_reg) and
  13008. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13009. (
  13010. (taicpu(hp1).opcode = taicpu(p).opcode)
  13011. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13012. {$ifdef x86_64}
  13013. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13014. {$endif x86_64}
  13015. ) then
  13016. begin
  13017. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13018. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13019. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13020. begin
  13021. {
  13022. For example:
  13023. movzbw %al,%ax
  13024. movzwl %ax,%eax
  13025. Compress into:
  13026. movzbl %al,%eax
  13027. }
  13028. RegUsed := False;
  13029. case taicpu(p).opsize of
  13030. S_BW:
  13031. case taicpu(hp1).opsize of
  13032. S_WL:
  13033. begin
  13034. taicpu(p).opsize := S_BL;
  13035. RegUsed := True;
  13036. end;
  13037. {$ifdef x86_64}
  13038. S_WQ:
  13039. begin
  13040. if taicpu(p).opcode = A_MOVZX then
  13041. begin
  13042. taicpu(p).opsize := S_BL;
  13043. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13044. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13045. end
  13046. else
  13047. taicpu(p).opsize := S_BQ;
  13048. RegUsed := True;
  13049. end;
  13050. {$endif x86_64}
  13051. else
  13052. ;
  13053. end;
  13054. {$ifdef x86_64}
  13055. S_BL:
  13056. case taicpu(hp1).opsize of
  13057. S_LQ:
  13058. begin
  13059. if taicpu(p).opcode = A_MOVZX then
  13060. begin
  13061. taicpu(p).opsize := S_BL;
  13062. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13063. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13064. end
  13065. else
  13066. taicpu(p).opsize := S_BQ;
  13067. RegUsed := True;
  13068. end;
  13069. else
  13070. ;
  13071. end;
  13072. S_WL:
  13073. case taicpu(hp1).opsize of
  13074. S_LQ:
  13075. begin
  13076. if taicpu(p).opcode = A_MOVZX then
  13077. begin
  13078. taicpu(p).opsize := S_WL;
  13079. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13080. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13081. end
  13082. else
  13083. taicpu(p).opsize := S_WQ;
  13084. RegUsed := True;
  13085. end;
  13086. else
  13087. ;
  13088. end;
  13089. {$endif x86_64}
  13090. else
  13091. ;
  13092. end;
  13093. if RegUsed then
  13094. begin
  13095. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13096. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13097. RemoveInstruction(hp1);
  13098. Result := True;
  13099. Exit;
  13100. end;
  13101. end;
  13102. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13103. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13104. GetNextInstruction(hp1, hp2) and
  13105. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13106. (
  13107. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13108. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13109. {$ifdef x86_64}
  13110. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13111. {$endif x86_64}
  13112. ) and
  13113. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13114. (
  13115. (
  13116. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13117. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13118. ) or
  13119. (
  13120. { Only allow the operands in reverse order for TEST instructions }
  13121. (taicpu(hp2).opcode = A_TEST) and
  13122. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13123. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13124. )
  13125. ) then
  13126. begin
  13127. {
  13128. For example:
  13129. movzbl %al,%eax
  13130. movzbl (ref),%edx
  13131. andl %edx,%eax
  13132. (%edx deallocated)
  13133. Change to:
  13134. andb (ref),%al
  13135. movzbl %al,%eax
  13136. Rules are:
  13137. - First two instructions have the same opcode and opsize
  13138. - First instruction's operands are the same super-register
  13139. - Second instruction operates on a different register
  13140. - Third instruction is AND, OR, XOR or TEST
  13141. - Third instruction's operands are the destination registers of the first two instructions
  13142. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13143. - Second instruction's destination register is deallocated afterwards
  13144. }
  13145. TransferUsedRegs(TmpUsedRegs);
  13146. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13147. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13148. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13149. begin
  13150. case taicpu(p).opsize of
  13151. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13152. NewSize := S_B;
  13153. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13154. NewSize := S_W;
  13155. {$ifdef x86_64}
  13156. S_LQ:
  13157. NewSize := S_L;
  13158. {$endif x86_64}
  13159. else
  13160. InternalError(2021120301);
  13161. end;
  13162. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13163. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13164. taicpu(hp2).opsize := NewSize;
  13165. RemoveInstruction(hp1);
  13166. { With TEST, it's best to keep the MOVX instruction at the top }
  13167. if (taicpu(hp2).opcode <> A_TEST) then
  13168. begin
  13169. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13170. asml.Remove(p);
  13171. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13172. asml.InsertAfter(p, hp2);
  13173. p := hp2;
  13174. end
  13175. else
  13176. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13177. Result := True;
  13178. Exit;
  13179. end;
  13180. end;
  13181. end;
  13182. if taicpu(p).opcode=A_MOVZX then
  13183. begin
  13184. { removes superfluous And's after movzx's }
  13185. if reg_and_hp1_is_instr and
  13186. (taicpu(hp1).opcode = A_AND) and
  13187. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13188. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13189. {$ifdef x86_64}
  13190. { check for implicit extension to 64 bit }
  13191. or
  13192. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13193. (taicpu(hp1).opsize=S_Q) and
  13194. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13195. )
  13196. {$endif x86_64}
  13197. )
  13198. then
  13199. begin
  13200. case taicpu(p).opsize Of
  13201. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13202. if (taicpu(hp1).oper[0]^.val = $ff) then
  13203. begin
  13204. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13205. RemoveInstruction(hp1);
  13206. Result:=true;
  13207. exit;
  13208. end;
  13209. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13210. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13211. begin
  13212. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13213. RemoveInstruction(hp1);
  13214. Result:=true;
  13215. exit;
  13216. end;
  13217. {$ifdef x86_64}
  13218. S_LQ:
  13219. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13220. begin
  13221. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13222. RemoveInstruction(hp1);
  13223. Result:=true;
  13224. exit;
  13225. end;
  13226. {$endif x86_64}
  13227. else
  13228. ;
  13229. end;
  13230. { we cannot get rid of the and, but can we get rid of the movz ?}
  13231. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13232. begin
  13233. case taicpu(p).opsize Of
  13234. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13235. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13236. begin
  13237. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13238. RemoveCurrentP(p,hp1);
  13239. Result:=true;
  13240. exit;
  13241. end;
  13242. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13243. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13244. begin
  13245. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13246. RemoveCurrentP(p,hp1);
  13247. Result:=true;
  13248. exit;
  13249. end;
  13250. {$ifdef x86_64}
  13251. S_LQ:
  13252. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13253. begin
  13254. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13255. RemoveCurrentP(p,hp1);
  13256. Result:=true;
  13257. exit;
  13258. end;
  13259. {$endif x86_64}
  13260. else
  13261. ;
  13262. end;
  13263. end;
  13264. end;
  13265. { changes some movzx constructs to faster synonyms (all examples
  13266. are given with eax/ax, but are also valid for other registers)}
  13267. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13268. begin
  13269. case taicpu(p).opsize of
  13270. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13271. (the machine code is equivalent to movzbl %al,%eax), but the
  13272. code generator still generates that assembler instruction and
  13273. it is silently converted. This should probably be checked.
  13274. [Kit] }
  13275. S_BW:
  13276. begin
  13277. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13278. (
  13279. not IsMOVZXAcceptable
  13280. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13281. or (
  13282. (cs_opt_size in current_settings.optimizerswitches) and
  13283. (taicpu(p).oper[1]^.reg = NR_AX)
  13284. )
  13285. ) then
  13286. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13287. begin
  13288. DebugMsg(SPeepholeOptimization + 'var7',p);
  13289. taicpu(p).opcode := A_AND;
  13290. taicpu(p).changeopsize(S_W);
  13291. taicpu(p).loadConst(0,$ff);
  13292. Result := True;
  13293. end
  13294. else if not IsMOVZXAcceptable and
  13295. GetNextInstruction(p, hp1) and
  13296. (tai(hp1).typ = ait_instruction) and
  13297. (taicpu(hp1).opcode = A_AND) and
  13298. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13299. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13300. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13301. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13302. begin
  13303. DebugMsg(SPeepholeOptimization + 'var8',p);
  13304. taicpu(p).opcode := A_MOV;
  13305. taicpu(p).changeopsize(S_W);
  13306. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13307. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13308. Result := True;
  13309. end;
  13310. end;
  13311. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13312. S_BL:
  13313. if not IsMOVZXAcceptable then
  13314. begin
  13315. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13316. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13317. begin
  13318. DebugMsg(SPeepholeOptimization + 'var9',p);
  13319. taicpu(p).opcode := A_AND;
  13320. taicpu(p).changeopsize(S_L);
  13321. taicpu(p).loadConst(0,$ff);
  13322. Result := True;
  13323. end
  13324. else if GetNextInstruction(p, hp1) and
  13325. (tai(hp1).typ = ait_instruction) and
  13326. (taicpu(hp1).opcode = A_AND) and
  13327. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13328. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13329. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13330. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13331. begin
  13332. DebugMsg(SPeepholeOptimization + 'var10',p);
  13333. taicpu(p).opcode := A_MOV;
  13334. taicpu(p).changeopsize(S_L);
  13335. { do not use R_SUBWHOLE
  13336. as movl %rdx,%eax
  13337. is invalid in assembler PM }
  13338. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13339. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13340. Result := True;
  13341. end;
  13342. end;
  13343. {$endif i8086}
  13344. S_WL:
  13345. if not IsMOVZXAcceptable then
  13346. begin
  13347. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13348. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13349. begin
  13350. DebugMsg(SPeepholeOptimization + 'var11',p);
  13351. taicpu(p).opcode := A_AND;
  13352. taicpu(p).changeopsize(S_L);
  13353. taicpu(p).loadConst(0,$ffff);
  13354. Result := True;
  13355. end
  13356. else if GetNextInstruction(p, hp1) and
  13357. (tai(hp1).typ = ait_instruction) and
  13358. (taicpu(hp1).opcode = A_AND) and
  13359. (taicpu(hp1).oper[0]^.typ = top_const) and
  13360. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13361. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13362. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13363. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13364. begin
  13365. DebugMsg(SPeepholeOptimization + 'var12',p);
  13366. taicpu(p).opcode := A_MOV;
  13367. taicpu(p).changeopsize(S_L);
  13368. { do not use R_SUBWHOLE
  13369. as movl %rdx,%eax
  13370. is invalid in assembler PM }
  13371. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13372. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13373. Result := True;
  13374. end;
  13375. end;
  13376. else
  13377. InternalError(2017050705);
  13378. end;
  13379. end
  13380. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13381. begin
  13382. if GetNextInstruction(p, hp1) and
  13383. (tai(hp1).typ = ait_instruction) and
  13384. (taicpu(hp1).opcode = A_AND) and
  13385. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13386. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13387. begin
  13388. //taicpu(p).opcode := A_MOV;
  13389. case taicpu(p).opsize Of
  13390. S_BL:
  13391. begin
  13392. DebugMsg(SPeepholeOptimization + 'var13',p);
  13393. taicpu(hp1).changeopsize(S_L);
  13394. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13395. end;
  13396. S_WL:
  13397. begin
  13398. DebugMsg(SPeepholeOptimization + 'var14',p);
  13399. taicpu(hp1).changeopsize(S_L);
  13400. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13401. end;
  13402. S_BW:
  13403. begin
  13404. DebugMsg(SPeepholeOptimization + 'var15',p);
  13405. taicpu(hp1).changeopsize(S_W);
  13406. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13407. end;
  13408. else
  13409. Internalerror(2017050704)
  13410. end;
  13411. Result := True;
  13412. end;
  13413. end;
  13414. end;
  13415. end;
  13416. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13417. var
  13418. hp1, hp2 : tai;
  13419. MaskLength : Cardinal;
  13420. MaskedBits : TCgInt;
  13421. ActiveReg : TRegister;
  13422. begin
  13423. Result:=false;
  13424. { There are no optimisations for reference targets }
  13425. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13426. Exit;
  13427. while GetNextInstruction(p, hp1) and
  13428. (hp1.typ = ait_instruction) do
  13429. begin
  13430. if (taicpu(p).oper[0]^.typ = top_const) then
  13431. begin
  13432. case taicpu(hp1).opcode of
  13433. A_AND:
  13434. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13435. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13436. { the second register must contain the first one, so compare their subreg types }
  13437. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13438. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13439. { change
  13440. and const1, reg
  13441. and const2, reg
  13442. to
  13443. and (const1 and const2), reg
  13444. }
  13445. begin
  13446. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13447. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13448. RemoveCurrentP(p, hp1);
  13449. Result:=true;
  13450. exit;
  13451. end;
  13452. A_CMP:
  13453. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13454. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13455. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13456. { Just check that the condition on the next instruction is compatible }
  13457. GetNextInstruction(hp1, hp2) and
  13458. (hp2.typ = ait_instruction) and
  13459. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13460. then
  13461. { change
  13462. and 2^n, reg
  13463. cmp 2^n, reg
  13464. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13465. to
  13466. and 2^n, reg
  13467. test reg, reg
  13468. j(~c) / set(~c) / cmov(~c)
  13469. }
  13470. begin
  13471. { Keep TEST instruction in, rather than remove it, because
  13472. it may trigger other optimisations such as MovAndTest2Test }
  13473. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13474. taicpu(hp1).opcode := A_TEST;
  13475. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13476. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13477. Result := True;
  13478. Exit;
  13479. end
  13480. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13481. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13482. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13483. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13484. { change
  13485. and $ff/$ff/$ffff, reg
  13486. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13487. dealloc reg
  13488. to
  13489. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13490. }
  13491. begin
  13492. TransferUsedRegs(TmpUsedRegs);
  13493. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13494. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13495. begin
  13496. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13497. case taicpu(p).oper[0]^.val of
  13498. $ff:
  13499. begin
  13500. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13501. taicpu(hp1).opsize:=S_B;
  13502. end;
  13503. $ffff:
  13504. begin
  13505. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13506. taicpu(hp1).opsize:=S_W;
  13507. end;
  13508. $ffffffff:
  13509. begin
  13510. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13511. taicpu(hp1).opsize:=S_L;
  13512. end;
  13513. else
  13514. Internalerror(2023030401);
  13515. end;
  13516. RemoveCurrentP(p);
  13517. Result := True;
  13518. Exit;
  13519. end;
  13520. end;
  13521. A_MOVZX:
  13522. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13523. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13524. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13525. (
  13526. (
  13527. (taicpu(p).opsize=S_W) and
  13528. (taicpu(hp1).opsize=S_BW)
  13529. ) or
  13530. (
  13531. (taicpu(p).opsize=S_L) and
  13532. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13533. )
  13534. {$ifdef x86_64}
  13535. or
  13536. (
  13537. (taicpu(p).opsize=S_Q) and
  13538. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13539. )
  13540. {$endif x86_64}
  13541. ) then
  13542. begin
  13543. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13544. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13545. ) or
  13546. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13547. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13548. then
  13549. begin
  13550. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13551. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13552. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13553. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13554. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13555. }
  13556. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13557. RemoveInstruction(hp1);
  13558. { See if there are other optimisations possible }
  13559. Continue;
  13560. end;
  13561. end;
  13562. A_SHL:
  13563. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13564. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13565. begin
  13566. {$ifopt R+}
  13567. {$define RANGE_WAS_ON}
  13568. {$R-}
  13569. {$endif}
  13570. { get length of potential and mask }
  13571. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13572. { really a mask? }
  13573. {$ifdef RANGE_WAS_ON}
  13574. {$R+}
  13575. {$endif}
  13576. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13577. { unmasked part shifted out? }
  13578. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13579. begin
  13580. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13581. RemoveCurrentP(p, hp1);
  13582. Result:=true;
  13583. exit;
  13584. end;
  13585. end;
  13586. A_SHR:
  13587. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13588. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13589. (taicpu(hp1).oper[0]^.val <= 63) then
  13590. begin
  13591. { Does SHR combined with the AND cover all the bits?
  13592. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13593. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13594. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13595. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13596. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13597. begin
  13598. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13599. RemoveCurrentP(p, hp1);
  13600. Result := True;
  13601. Exit;
  13602. end;
  13603. end;
  13604. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13605. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13606. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13607. begin
  13608. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13609. (
  13610. (
  13611. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13612. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  13613. ) or (
  13614. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13615. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  13616. {$ifdef x86_64}
  13617. ) or (
  13618. (taicpu(hp1).opsize = S_LQ) and
  13619. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  13620. {$endif x86_64}
  13621. )
  13622. ) then
  13623. begin
  13624. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  13625. begin
  13626. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  13627. RemoveInstruction(hp1);
  13628. { See if there are other optimisations possible }
  13629. Continue;
  13630. end;
  13631. { The super-registers are the same though.
  13632. Note that this change by itself doesn't improve
  13633. code speed, but it opens up other optimisations. }
  13634. {$ifdef x86_64}
  13635. { Convert 64-bit register to 32-bit }
  13636. case taicpu(hp1).opsize of
  13637. S_BQ:
  13638. begin
  13639. taicpu(hp1).opsize := S_BL;
  13640. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13641. end;
  13642. S_WQ:
  13643. begin
  13644. taicpu(hp1).opsize := S_WL;
  13645. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13646. end
  13647. else
  13648. ;
  13649. end;
  13650. {$endif x86_64}
  13651. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  13652. taicpu(hp1).opcode := A_MOVZX;
  13653. { See if there are other optimisations possible }
  13654. Continue;
  13655. end;
  13656. end;
  13657. else
  13658. ;
  13659. end;
  13660. end
  13661. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  13662. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13663. begin
  13664. {$ifdef x86_64}
  13665. if (taicpu(p).opsize = S_Q) then
  13666. begin
  13667. { Never necessary }
  13668. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  13669. RemoveCurrentP(p, hp1);
  13670. Result := True;
  13671. Exit;
  13672. end;
  13673. {$endif x86_64}
  13674. { Forward check to determine necessity of and %reg,%reg }
  13675. TransferUsedRegs(TmpUsedRegs);
  13676. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13677. { Saves on a bunch of dereferences }
  13678. ActiveReg := taicpu(p).oper[1]^.reg;
  13679. case taicpu(hp1).opcode of
  13680. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13681. if (
  13682. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13683. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13684. ) and
  13685. (
  13686. (taicpu(hp1).opcode <> A_MOV) or
  13687. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  13688. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  13689. ) and
  13690. not (
  13691. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  13692. (taicpu(hp1).opcode = A_MOV) and
  13693. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  13694. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  13695. ) and
  13696. (
  13697. (
  13698. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13699. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  13700. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  13701. ) or
  13702. (
  13703. {$ifdef x86_64}
  13704. (
  13705. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  13706. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  13707. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  13708. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  13709. ) and
  13710. {$endif x86_64}
  13711. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  13712. )
  13713. ) then
  13714. begin
  13715. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  13716. RemoveCurrentP(p, hp1);
  13717. Result := True;
  13718. Exit;
  13719. end;
  13720. A_ADD,
  13721. A_AND,
  13722. A_BSF,
  13723. A_BSR,
  13724. A_BTC,
  13725. A_BTR,
  13726. A_BTS,
  13727. A_OR,
  13728. A_SUB,
  13729. A_XOR:
  13730. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  13731. if (
  13732. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13733. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13734. ) and
  13735. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  13736. begin
  13737. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  13738. RemoveCurrentP(p, hp1);
  13739. Result := True;
  13740. Exit;
  13741. end;
  13742. A_CMP,
  13743. A_TEST:
  13744. if (
  13745. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13746. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13747. ) and
  13748. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  13749. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  13750. begin
  13751. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  13752. RemoveCurrentP(p, hp1);
  13753. Result := True;
  13754. Exit;
  13755. end;
  13756. A_BSWAP,
  13757. A_NEG,
  13758. A_NOT:
  13759. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  13760. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  13761. begin
  13762. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  13763. RemoveCurrentP(p, hp1);
  13764. Result := True;
  13765. Exit;
  13766. end;
  13767. else
  13768. ;
  13769. end;
  13770. end;
  13771. if (taicpu(hp1).is_jmp) and
  13772. (taicpu(hp1).opcode<>A_JMP) and
  13773. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  13774. begin
  13775. { change
  13776. and x, reg
  13777. jxx
  13778. to
  13779. test x, reg
  13780. jxx
  13781. if reg is deallocated before the
  13782. jump, but only if it's a conditional jump (PFV)
  13783. }
  13784. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  13785. taicpu(p).opcode := A_TEST;
  13786. Exit;
  13787. end;
  13788. Break;
  13789. end;
  13790. { Lone AND tests }
  13791. if (taicpu(p).oper[0]^.typ = top_const) then
  13792. begin
  13793. {
  13794. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  13795. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  13796. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  13797. }
  13798. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  13799. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  13800. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  13801. begin
  13802. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  13803. if taicpu(p).opsize = S_L then
  13804. begin
  13805. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  13806. Result := True;
  13807. end;
  13808. end;
  13809. end;
  13810. { Backward check to determine necessity of and %reg,%reg }
  13811. if (taicpu(p).oper[0]^.typ = top_reg) and
  13812. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13813. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13814. GetLastInstruction(p, hp2) and
  13815. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  13816. { Check size of adjacent instruction to determine if the AND is
  13817. effectively a null operation }
  13818. (
  13819. (taicpu(p).opsize = taicpu(hp2).opsize) or
  13820. { Note: Don't include S_Q }
  13821. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  13822. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  13823. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  13824. ) then
  13825. begin
  13826. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  13827. { If GetNextInstruction returned False, hp1 will be nil }
  13828. RemoveCurrentP(p, hp1);
  13829. Result := True;
  13830. Exit;
  13831. end;
  13832. end;
  13833. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  13834. var
  13835. hp1, hp2: tai;
  13836. NewRef: TReference;
  13837. Distance: Cardinal;
  13838. TempTracking: TAllUsedRegs;
  13839. { This entire nested function is used in an if-statement below, but we
  13840. want to avoid all the used reg transfers and GetNextInstruction calls
  13841. until we really have to check }
  13842. function MemRegisterNotUsedLater: Boolean; inline;
  13843. var
  13844. hp2: tai;
  13845. begin
  13846. TransferUsedRegs(TmpUsedRegs);
  13847. hp2 := p;
  13848. repeat
  13849. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13850. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13851. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  13852. end;
  13853. begin
  13854. Result := False;
  13855. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13856. (taicpu(p).oper[1]^.typ = top_reg) then
  13857. begin
  13858. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13859. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13860. (hp1.typ <> ait_instruction) or
  13861. not
  13862. (
  13863. (cs_opt_level3 in current_settings.optimizerswitches) or
  13864. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13865. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13866. ) then
  13867. Exit;
  13868. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13869. addq $x, %rax
  13870. movq %rax, %rdx
  13871. sarq $63, %rdx
  13872. (%rax still in use)
  13873. ...letting OptPass2ADD run its course (and without -Os) will produce:
  13874. leaq $x(%rax),%rdx
  13875. addq $x, %rax
  13876. sarq $63, %rdx
  13877. ...which is okay since it breaks the dependency chain between
  13878. addq and movq, but if OptPass2MOV is called first:
  13879. addq $x, %rax
  13880. cqto
  13881. ...which is better in all ways, taking only 2 cycles to execute
  13882. and much smaller in code size.
  13883. }
  13884. { The extra register tracking is quite strenuous }
  13885. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13886. MatchInstruction(hp1, A_MOV, []) then
  13887. begin
  13888. { Update the register tracking to the MOV instruction }
  13889. CopyUsedRegs(TempTracking);
  13890. hp2 := p;
  13891. repeat
  13892. UpdateUsedRegs(tai(hp2.Next));
  13893. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13894. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13895. OptPass2ADD get called again }
  13896. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13897. begin
  13898. { Reset the tracking to the current instruction }
  13899. RestoreUsedRegs(TempTracking);
  13900. ReleaseUsedRegs(TempTracking);
  13901. Result := True;
  13902. Exit;
  13903. end;
  13904. { Reset the tracking to the current instruction }
  13905. RestoreUsedRegs(TempTracking);
  13906. ReleaseUsedRegs(TempTracking);
  13907. { If OptPass2MOV returned True, we don't need to set Result to
  13908. True if hp1 didn't change because the ADD instruction didn't
  13909. get modified and we'll be evaluating hp1 again when the
  13910. peephole optimizer reaches it }
  13911. end;
  13912. { Change:
  13913. add %reg2,%reg1
  13914. (%reg2 not modified in between)
  13915. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  13916. To:
  13917. mov/s/z #(%reg1,%reg2),%reg1
  13918. }
  13919. if (taicpu(p).oper[0]^.typ = top_reg) and
  13920. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  13921. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  13922. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  13923. (
  13924. (
  13925. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  13926. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  13927. { r/esp cannot be an index }
  13928. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  13929. ) or (
  13930. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  13931. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  13932. )
  13933. ) and (
  13934. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  13935. (
  13936. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  13937. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13938. MemRegisterNotUsedLater
  13939. )
  13940. ) then
  13941. begin
  13942. if (
  13943. { Instructions are guaranteed to be adjacent on -O2 and under }
  13944. (cs_opt_level3 in current_settings.optimizerswitches) and
  13945. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  13946. ) then
  13947. begin
  13948. { If the other register is used in between, move the MOV
  13949. instruction to right after the ADD instruction so a
  13950. saving can still be made }
  13951. Asml.Remove(hp1);
  13952. Asml.InsertAfter(hp1, p);
  13953. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13954. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13955. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  13956. RemoveCurrentp(p, hp1);
  13957. end
  13958. else
  13959. begin
  13960. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  13961. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13962. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13963. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  13964. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13965. { hp1 may not be the immediate next instruction under -O3 }
  13966. RemoveCurrentp(p)
  13967. else
  13968. RemoveCurrentp(p, hp1);
  13969. end;
  13970. Result := True;
  13971. Exit;
  13972. end;
  13973. { Change:
  13974. addl/q $x,%reg1
  13975. movl/q %reg1,%reg2
  13976. To:
  13977. leal/q $x(%reg1),%reg2
  13978. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13979. Breaks the dependency chain.
  13980. }
  13981. if (taicpu(p).oper[0]^.typ = top_const) and
  13982. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13983. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13984. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13985. (
  13986. { Instructions are guaranteed to be adjacent on -O2 and under }
  13987. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13988. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13989. ) then
  13990. begin
  13991. TransferUsedRegs(TmpUsedRegs);
  13992. hp2 := p;
  13993. repeat
  13994. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13995. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13996. if (
  13997. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  13998. not (cs_opt_size in current_settings.optimizerswitches) or
  13999. (
  14000. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14001. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14002. )
  14003. ) then
  14004. begin
  14005. { Change the MOV instruction to a LEA instruction, and update the
  14006. first operand }
  14007. reference_reset(NewRef, 1, []);
  14008. NewRef.base := taicpu(p).oper[1]^.reg;
  14009. NewRef.scalefactor := 1;
  14010. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14011. taicpu(hp1).opcode := A_LEA;
  14012. taicpu(hp1).loadref(0, NewRef);
  14013. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14014. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14015. begin
  14016. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14017. { Move what is now the LEA instruction to before the ADD instruction }
  14018. Asml.Remove(hp1);
  14019. Asml.InsertBefore(hp1, p);
  14020. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14021. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14022. p := hp1;
  14023. end
  14024. else
  14025. begin
  14026. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14027. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14028. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14029. { hp1 may not be the immediate next instruction under -O3 }
  14030. RemoveCurrentp(p)
  14031. else
  14032. RemoveCurrentp(p, hp1);
  14033. end;
  14034. Result := True;
  14035. end;
  14036. end;
  14037. end;
  14038. end;
  14039. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14040. var
  14041. SubReg: TSubRegister;
  14042. hp1, hp2: tai;
  14043. CallJmp: Boolean;
  14044. begin
  14045. Result := False;
  14046. CallJmp := False;
  14047. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14048. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14049. with taicpu(p).oper[0]^.ref^ do
  14050. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14051. if (offset = 0) then
  14052. begin
  14053. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14054. begin
  14055. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14056. taicpu(p).opcode := A_ADD;
  14057. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14058. Result := True;
  14059. end
  14060. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14061. begin
  14062. if (base <> NR_NO) then
  14063. begin
  14064. if (scalefactor <= 1) then
  14065. begin
  14066. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14067. taicpu(p).opcode := A_ADD;
  14068. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14069. Result := True;
  14070. end;
  14071. end
  14072. else
  14073. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14074. if (scalefactor in [2, 4, 8]) then
  14075. begin
  14076. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14077. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14078. taicpu(p).opcode := A_SHL;
  14079. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14080. Result := True;
  14081. end;
  14082. end;
  14083. end
  14084. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14085. lot of latency, so break off the offset if %reg3 is used soon
  14086. afterwards }
  14087. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14088. { If 3-component addresses don't have additional latency, don't
  14089. perform this optimisation }
  14090. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14091. GetNextInstruction(p, hp1) and
  14092. (
  14093. (
  14094. { Permit jumps and calls since they have a larger degree of overhead }
  14095. (
  14096. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14097. (
  14098. { ... unless the register specifies the location }
  14099. (taicpu(hp1).ops > 0) and
  14100. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14101. )
  14102. ) and
  14103. (
  14104. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14105. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14106. )
  14107. )
  14108. or
  14109. (
  14110. { Check up to two instructions ahead }
  14111. GetNextInstruction(hp1, hp2) and
  14112. (
  14113. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14114. (
  14115. { Same as above }
  14116. (taicpu(hp2).ops > 0) and
  14117. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14118. )
  14119. ) and
  14120. (
  14121. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14122. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14123. )
  14124. )
  14125. ) then
  14126. begin
  14127. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14128. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14129. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14130. offset := 0;
  14131. if Assigned(symbol) or Assigned(relsymbol) then
  14132. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14133. else
  14134. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14135. { Inserting before the next instruction rather than after the
  14136. current instruction gives more accurate register tracking }
  14137. asml.InsertBefore(hp2, hp1);
  14138. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14139. Result := True;
  14140. end;
  14141. end;
  14142. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14143. var
  14144. hp1, hp2: tai;
  14145. NewRef: TReference;
  14146. Distance: Cardinal;
  14147. TempTracking: TAllUsedRegs;
  14148. begin
  14149. Result := False;
  14150. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14151. MatchOpType(taicpu(p),top_const,top_reg) then
  14152. begin
  14153. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14154. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14155. (hp1.typ <> ait_instruction) or
  14156. not
  14157. (
  14158. (cs_opt_level3 in current_settings.optimizerswitches) or
  14159. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14160. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14161. ) then
  14162. Exit;
  14163. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14164. subq $x, %rax
  14165. movq %rax, %rdx
  14166. sarq $63, %rdx
  14167. (%rax still in use)
  14168. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14169. leaq $-x(%rax),%rdx
  14170. movq $x, %rax
  14171. sarq $63, %rdx
  14172. ...which is okay since it breaks the dependency chain between
  14173. subq and movq, but if OptPass2MOV is called first:
  14174. subq $x, %rax
  14175. cqto
  14176. ...which is better in all ways, taking only 2 cycles to execute
  14177. and much smaller in code size.
  14178. }
  14179. { The extra register tracking is quite strenuous }
  14180. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14181. MatchInstruction(hp1, A_MOV, []) then
  14182. begin
  14183. { Update the register tracking to the MOV instruction }
  14184. CopyUsedRegs(TempTracking);
  14185. hp2 := p;
  14186. repeat
  14187. UpdateUsedRegs(tai(hp2.Next));
  14188. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14189. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14190. OptPass2SUB get called again }
  14191. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  14192. begin
  14193. { Reset the tracking to the current instruction }
  14194. RestoreUsedRegs(TempTracking);
  14195. ReleaseUsedRegs(TempTracking);
  14196. Result := True;
  14197. Exit;
  14198. end;
  14199. { Reset the tracking to the current instruction }
  14200. RestoreUsedRegs(TempTracking);
  14201. ReleaseUsedRegs(TempTracking);
  14202. { If OptPass2MOV returned True, we don't need to set Result to
  14203. True if hp1 didn't change because the SUB instruction didn't
  14204. get modified and we'll be evaluating hp1 again when the
  14205. peephole optimizer reaches it }
  14206. end;
  14207. { Change:
  14208. subl/q $x,%reg1
  14209. movl/q %reg1,%reg2
  14210. To:
  14211. leal/q $-x(%reg1),%reg2
  14212. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14213. Breaks the dependency chain and potentially permits the removal of
  14214. a CMP instruction if one follows.
  14215. }
  14216. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14217. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14218. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14219. (
  14220. { Instructions are guaranteed to be adjacent on -O2 and under }
  14221. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14222. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14223. ) then
  14224. begin
  14225. TransferUsedRegs(TmpUsedRegs);
  14226. hp2 := p;
  14227. repeat
  14228. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14229. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14230. if (
  14231. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14232. not (cs_opt_size in current_settings.optimizerswitches) or
  14233. (
  14234. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14235. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14236. )
  14237. ) then
  14238. begin
  14239. { Change the MOV instruction to a LEA instruction, and update the
  14240. first operand }
  14241. reference_reset(NewRef, 1, []);
  14242. NewRef.base := taicpu(p).oper[1]^.reg;
  14243. NewRef.scalefactor := 1;
  14244. NewRef.offset := -taicpu(p).oper[0]^.val;
  14245. taicpu(hp1).opcode := A_LEA;
  14246. taicpu(hp1).loadref(0, NewRef);
  14247. TransferUsedRegs(TmpUsedRegs);
  14248. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14249. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14250. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14251. begin
  14252. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14253. { Move what is now the LEA instruction to before the SUB instruction }
  14254. Asml.Remove(hp1);
  14255. Asml.InsertBefore(hp1, p);
  14256. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14257. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14258. p := hp1;
  14259. end
  14260. else
  14261. begin
  14262. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14263. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14264. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14265. { hp1 may not be the immediate next instruction under -O3 }
  14266. RemoveCurrentp(p)
  14267. else
  14268. RemoveCurrentp(p, hp1);
  14269. end;
  14270. Result := True;
  14271. end;
  14272. end;
  14273. end;
  14274. end;
  14275. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14276. begin
  14277. { we can skip all instructions not messing with the stack pointer }
  14278. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14279. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14280. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14281. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14282. ({(taicpu(hp1).ops=0) or }
  14283. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14284. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14285. ) and }
  14286. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14287. )
  14288. ) do
  14289. GetNextInstruction(hp1,hp1);
  14290. Result:=assigned(hp1);
  14291. end;
  14292. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14293. var
  14294. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14295. begin
  14296. Result:=false;
  14297. hp5:=nil;
  14298. hp6:=nil;
  14299. hp7:=nil;
  14300. hp8:=nil;
  14301. { replace
  14302. leal(q) x(<stackpointer>),<stackpointer>
  14303. <optional .seh_stackalloc ...>
  14304. <optional .seh_endprologue ...>
  14305. call procname
  14306. <optional NOP>
  14307. leal(q) -x(<stackpointer>),<stackpointer>
  14308. <optional VZEROUPPER>
  14309. ret
  14310. by
  14311. jmp procname
  14312. but do it only on level 4 because it destroys stack back traces
  14313. }
  14314. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14315. MatchOpType(taicpu(p),top_ref,top_reg) and
  14316. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14317. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14318. { the -8, -24, -40 are not required, but bail out early if possible,
  14319. higher values are unlikely }
  14320. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14321. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14322. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14323. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14324. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14325. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14326. GetNextInstruction(p, hp1) and
  14327. { Take a copy of hp1 }
  14328. SetAndTest(hp1, hp4) and
  14329. { trick to skip label }
  14330. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14331. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14332. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14333. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14334. SkipSimpleInstructions(hp1) and
  14335. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14336. GetNextInstruction(hp1, hp2) and
  14337. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14338. { skip nop instruction on win64 }
  14339. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14340. SetAndTest(hp2,hp6) and
  14341. GetNextInstruction(hp2,hp2) and
  14342. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14343. ) and
  14344. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14345. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14346. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14347. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14348. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14349. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14350. { Segment register will be NR_NO }
  14351. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14352. GetNextInstruction(hp2, hp3) and
  14353. { trick to skip label }
  14354. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14355. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14356. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14357. SetAndTest(hp3,hp5) and
  14358. GetNextInstruction(hp3,hp3) and
  14359. MatchInstruction(hp3,A_RET,[S_NO])
  14360. )
  14361. ) and
  14362. (taicpu(hp3).ops=0) then
  14363. begin
  14364. taicpu(hp1).opcode := A_JMP;
  14365. taicpu(hp1).is_jmp := true;
  14366. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14367. { search for the stackalloc directive and remove it }
  14368. hp7:=tai(p.next);
  14369. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14370. begin
  14371. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14372. begin
  14373. { sanity check }
  14374. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14375. Internalerror(2024012201);
  14376. hp8:=tai(hp7.next);
  14377. RemoveInstruction(tai(hp7));
  14378. hp7:=hp8;
  14379. break;
  14380. end
  14381. else
  14382. hp7:=tai(hp7.next);
  14383. end;
  14384. RemoveCurrentP(p, hp4);
  14385. RemoveInstruction(hp2);
  14386. RemoveInstruction(hp3);
  14387. { if there is a vzeroupper instruction then move it before the jmp }
  14388. if Assigned(hp5) then
  14389. begin
  14390. AsmL.Remove(hp5);
  14391. ASmL.InsertBefore(hp5,hp1)
  14392. end;
  14393. { remove nop on win64 }
  14394. if Assigned(hp6) then
  14395. RemoveInstruction(hp6);
  14396. Result:=true;
  14397. end;
  14398. end;
  14399. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14400. {$ifdef x86_64}
  14401. var
  14402. hp1, hp2, hp3, hp4, hp5: tai;
  14403. {$endif x86_64}
  14404. begin
  14405. Result:=false;
  14406. {$ifdef x86_64}
  14407. hp5:=nil;
  14408. { replace
  14409. push %rax
  14410. call procname
  14411. pop %rcx
  14412. ret
  14413. by
  14414. jmp procname
  14415. but do it only on level 4 because it destroys stack back traces
  14416. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14417. for all supported calling conventions
  14418. }
  14419. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14420. MatchOpType(taicpu(p),top_reg) and
  14421. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14422. GetNextInstruction(p, hp1) and
  14423. { Take a copy of hp1 }
  14424. SetAndTest(hp1, hp4) and
  14425. { trick to skip label }
  14426. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14427. SkipSimpleInstructions(hp1) and
  14428. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14429. GetNextInstruction(hp1, hp2) and
  14430. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14431. MatchOpType(taicpu(hp2),top_reg) and
  14432. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14433. GetNextInstruction(hp2, hp3) and
  14434. { trick to skip label }
  14435. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14436. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14437. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14438. SetAndTest(hp3,hp5) and
  14439. GetNextInstruction(hp3,hp3) and
  14440. MatchInstruction(hp3,A_RET,[S_NO])
  14441. )
  14442. ) and
  14443. (taicpu(hp3).ops=0) then
  14444. begin
  14445. taicpu(hp1).opcode := A_JMP;
  14446. taicpu(hp1).is_jmp := true;
  14447. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14448. RemoveCurrentP(p, hp4);
  14449. RemoveInstruction(hp2);
  14450. RemoveInstruction(hp3);
  14451. if Assigned(hp5) then
  14452. begin
  14453. AsmL.Remove(hp5);
  14454. ASmL.InsertBefore(hp5,hp1)
  14455. end;
  14456. Result:=true;
  14457. end;
  14458. {$endif x86_64}
  14459. end;
  14460. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14461. var
  14462. Value, RegName: string;
  14463. hp1: tai;
  14464. begin
  14465. Result:=false;
  14466. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14467. begin
  14468. case taicpu(p).oper[0]^.val of
  14469. 0:
  14470. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14471. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14472. (
  14473. { See if we can still convert the instruction }
  14474. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14475. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14476. ) then
  14477. begin
  14478. { change "mov $0,%reg" into "xor %reg,%reg" }
  14479. taicpu(p).opcode := A_XOR;
  14480. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14481. Result := True;
  14482. {$ifdef x86_64}
  14483. end
  14484. else if (taicpu(p).opsize = S_Q) then
  14485. begin
  14486. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14487. { The actual optimization }
  14488. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14489. taicpu(p).changeopsize(S_L);
  14490. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14491. Result := True;
  14492. end;
  14493. $1..$FFFFFFFF:
  14494. begin
  14495. { Code size reduction by J. Gareth "Kit" Moreton }
  14496. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14497. case taicpu(p).opsize of
  14498. S_Q:
  14499. begin
  14500. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14501. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14502. { The actual optimization }
  14503. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14504. taicpu(p).changeopsize(S_L);
  14505. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14506. Result := True;
  14507. end;
  14508. else
  14509. { Do nothing };
  14510. end;
  14511. {$endif x86_64}
  14512. end;
  14513. -1:
  14514. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14515. if (cs_opt_size in current_settings.optimizerswitches) and
  14516. (taicpu(p).opsize <> S_B) and
  14517. (
  14518. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14519. (
  14520. { See if we can still convert the instruction }
  14521. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14522. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14523. )
  14524. ) then
  14525. begin
  14526. { change "mov $-1,%reg" into "or $-1,%reg" }
  14527. { NOTES:
  14528. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14529. - This operation creates a false dependency on the register, so only do it when optimising for size
  14530. - 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
  14531. }
  14532. taicpu(p).opcode := A_OR;
  14533. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14534. Result := True;
  14535. end;
  14536. else
  14537. { Do nothing };
  14538. end;
  14539. end;
  14540. end;
  14541. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14542. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14543. begin
  14544. Result := False;
  14545. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14546. Exit;
  14547. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14548. so don't bother optimising }
  14549. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14550. Exit;
  14551. if (taicpu(p).oper[0]^.typ <> top_const) or
  14552. { If the value can fit into an 8-bit signed integer, a smaller
  14553. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14554. falls within this range }
  14555. (
  14556. (taicpu(p).oper[0]^.val > -128) and
  14557. (taicpu(p).oper[0]^.val <= 127)
  14558. ) then
  14559. Exit;
  14560. { If we're optimising for size, this is acceptable }
  14561. if (cs_opt_size in current_settings.optimizerswitches) then
  14562. Exit(True);
  14563. if (taicpu(p).oper[1]^.typ = top_reg) and
  14564. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14565. Exit(True);
  14566. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14567. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14568. Exit(True);
  14569. end;
  14570. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14571. var
  14572. hp1: tai;
  14573. Value: TCGInt;
  14574. begin
  14575. Result := False;
  14576. if MatchOpType(taicpu(p), top_const, top_reg) then
  14577. begin
  14578. { Detect:
  14579. andw x, %ax (0 <= x < $8000)
  14580. ...
  14581. movzwl %ax,%eax
  14582. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14583. }
  14584. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  14585. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  14586. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  14587. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  14588. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  14589. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  14590. begin
  14591. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  14592. taicpu(hp1).opcode := A_CWDE;
  14593. taicpu(hp1).clearop(0);
  14594. taicpu(hp1).clearop(1);
  14595. taicpu(hp1).ops := 0;
  14596. { A change was made, but not with p, so don't set Result, but
  14597. notify the compiler that a change was made }
  14598. Include(OptsToCheck, aoc_ForceNewIteration);
  14599. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  14600. end;
  14601. end;
  14602. { If "not x" is a power of 2 (popcnt = 1), change:
  14603. and $x, %reg/ref
  14604. To:
  14605. btr lb(x), %reg/ref
  14606. }
  14607. if IsBTXAcceptable(p) and
  14608. (
  14609. { Make sure a TEST doesn't follow that plays with the register }
  14610. not GetNextInstruction(p, hp1) or
  14611. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  14612. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  14613. ) then
  14614. begin
  14615. {$push}{$R-}{$Q-}
  14616. { Value is a sign-extended 32-bit integer - just correct it
  14617. if it's represented as an unsigned value. Also, IsBTXAcceptable
  14618. checks to see if this operand is an immediate. }
  14619. Value := not taicpu(p).oper[0]^.val;
  14620. {$pop}
  14621. {$ifdef x86_64}
  14622. if taicpu(p).opsize = S_L then
  14623. {$endif x86_64}
  14624. Value := Value and $FFFFFFFF;
  14625. if (PopCnt(QWord(Value)) = 1) then
  14626. begin
  14627. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  14628. taicpu(p).opcode := A_BTR;
  14629. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  14630. Result := True;
  14631. Exit;
  14632. end;
  14633. end;
  14634. end;
  14635. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  14636. begin
  14637. Result := False;
  14638. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  14639. Exit;
  14640. { Convert:
  14641. movswl %ax,%eax -> cwtl
  14642. movslq %eax,%rax -> cdqe
  14643. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  14644. refer to the same opcode and depends only on the assembler's
  14645. current operand-size attribute. [Kit]
  14646. }
  14647. with taicpu(p) do
  14648. case opsize of
  14649. S_WL:
  14650. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  14651. begin
  14652. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  14653. opcode := A_CWDE;
  14654. clearop(0);
  14655. clearop(1);
  14656. ops := 0;
  14657. Result := True;
  14658. end;
  14659. {$ifdef x86_64}
  14660. S_LQ:
  14661. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  14662. begin
  14663. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  14664. opcode := A_CDQE;
  14665. clearop(0);
  14666. clearop(1);
  14667. ops := 0;
  14668. Result := True;
  14669. end;
  14670. {$endif x86_64}
  14671. else
  14672. ;
  14673. end;
  14674. end;
  14675. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  14676. var
  14677. hp1, hp2: tai;
  14678. IdentityMask, Shift: TCGInt;
  14679. LimitSize: Topsize;
  14680. DoNotMerge: Boolean;
  14681. begin
  14682. Result := False;
  14683. { All these optimisations work on "shr const,%reg" }
  14684. if not MatchOpType(taicpu(p), top_const, top_reg) then
  14685. Exit;
  14686. DoNotMerge := False;
  14687. Shift := taicpu(p).oper[0]^.val;
  14688. LimitSize := taicpu(p).opsize;
  14689. hp1 := p;
  14690. repeat
  14691. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  14692. Break;
  14693. { Detect:
  14694. shr x, %reg
  14695. and y, %reg
  14696. If and y, %reg doesn't actually change the value of %reg (e.g. with
  14697. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  14698. }
  14699. case taicpu(hp1).opcode of
  14700. A_AND:
  14701. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  14702. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14703. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14704. begin
  14705. { Make sure the FLAGS register isn't in use }
  14706. TransferUsedRegs(TmpUsedRegs);
  14707. hp2 := p;
  14708. repeat
  14709. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14710. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14711. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14712. begin
  14713. { Generate the identity mask }
  14714. case taicpu(p).opsize of
  14715. S_B:
  14716. IdentityMask := $FF shr Shift;
  14717. S_W:
  14718. IdentityMask := $FFFF shr Shift;
  14719. S_L:
  14720. IdentityMask := $FFFFFFFF shr Shift;
  14721. {$ifdef x86_64}
  14722. S_Q:
  14723. { We need to force the operands to be unsigned 64-bit
  14724. integers otherwise the wrong value is generated }
  14725. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  14726. {$endif x86_64}
  14727. else
  14728. InternalError(2022081501);
  14729. end;
  14730. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  14731. begin
  14732. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  14733. { All the possible 1 bits are covered, so we can remove the AND }
  14734. hp2 := tai(hp1.Previous);
  14735. RemoveInstruction(hp1);
  14736. { p wasn't actually changed, so don't set Result to True,
  14737. but a change was nonetheless made elsewhere }
  14738. Include(OptsToCheck, aoc_ForceNewIteration);
  14739. { Do another pass in case other AND or MOVZX instructions
  14740. follow }
  14741. hp1 := hp2;
  14742. Continue;
  14743. end;
  14744. end;
  14745. end;
  14746. A_TEST, A_CMP, A_Jcc:
  14747. { Skip over conditional jumps and relevant comparisons }
  14748. Continue;
  14749. A_MOVZX:
  14750. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14751. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  14752. begin
  14753. { Since the original register is being read as is, subsequent
  14754. SHRs must not be merged at this point }
  14755. DoNotMerge := True;
  14756. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  14757. begin
  14758. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14759. begin
  14760. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  14761. { All the possible 1 bits are covered, so we can remove the AND }
  14762. hp2 := tai(hp1.Previous);
  14763. RemoveInstruction(hp1);
  14764. hp1 := hp2;
  14765. end
  14766. else { Different register target }
  14767. begin
  14768. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  14769. taicpu(hp1).opcode := A_MOV;
  14770. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  14771. case taicpu(hp1).opsize of
  14772. S_BW:
  14773. taicpu(hp1).opsize := S_W;
  14774. S_BL, S_WL:
  14775. taicpu(hp1).opsize := S_L;
  14776. else
  14777. InternalError(2022081503);
  14778. end;
  14779. end;
  14780. end
  14781. else if (Shift > 0) and
  14782. (taicpu(p).opsize = S_W) and
  14783. (taicpu(hp1).opsize = S_WL) and
  14784. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  14785. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  14786. begin
  14787. { Detect:
  14788. shr x, %ax (x > 0)
  14789. ...
  14790. movzwl %ax,%eax
  14791. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14792. }
  14793. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  14794. taicpu(hp1).opcode := A_CWDE;
  14795. taicpu(hp1).clearop(0);
  14796. taicpu(hp1).clearop(1);
  14797. taicpu(hp1).ops := 0;
  14798. end;
  14799. { Move onto the next instruction }
  14800. Continue;
  14801. end;
  14802. A_SHL, A_SAL, A_SHR:
  14803. if (taicpu(hp1).opsize <= LimitSize) and
  14804. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14805. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  14806. begin
  14807. { Make sure the sizes don't exceed the register size limit
  14808. (measured by the shift value falling below the limit) }
  14809. if taicpu(hp1).opsize < LimitSize then
  14810. LimitSize := taicpu(hp1).opsize;
  14811. if taicpu(hp1).opcode = A_SHR then
  14812. Inc(Shift, taicpu(hp1).oper[0]^.val)
  14813. else
  14814. begin
  14815. Dec(Shift, taicpu(hp1).oper[0]^.val);
  14816. DoNotMerge := True;
  14817. end;
  14818. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  14819. Break;
  14820. { Since we've established that the combined shift is within
  14821. limits, we can actually combine the adjacent SHR
  14822. instructions even if they're different sizes }
  14823. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  14824. begin
  14825. hp2 := tai(hp1.Previous);
  14826. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  14827. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  14828. RemoveInstruction(hp1);
  14829. hp1 := hp2;
  14830. end;
  14831. { Move onto the next instruction }
  14832. Continue;
  14833. end;
  14834. else
  14835. ;
  14836. end;
  14837. Break;
  14838. until False;
  14839. { Detect the following (looking backwards):
  14840. shr %cl,%reg
  14841. shr x, %reg
  14842. Swap the two SHR instructions to minimise a pipeline stall.
  14843. }
  14844. if GetLastInstruction(p, hp1) and
  14845. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  14846. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14847. { First operand will be %cl }
  14848. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  14849. { Just to be sure }
  14850. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  14851. begin
  14852. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  14853. { Moving the entries this way ensures the register tracking remains correct }
  14854. Asml.Remove(p);
  14855. Asml.InsertBefore(p, hp1);
  14856. p := hp1;
  14857. { Don't set Result to True because the current instruction is now
  14858. "shr %cl,%reg" and there's nothing more we can do with it }
  14859. end;
  14860. end;
  14861. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  14862. var
  14863. hp1, hp2: tai;
  14864. Opposite, SecondOpposite: TAsmOp;
  14865. NewCond: TAsmCond;
  14866. begin
  14867. Result := False;
  14868. { Change:
  14869. add/sub 128,(dest)
  14870. To:
  14871. sub/add -128,(dest)
  14872. This generaally takes fewer bytes to encode because -128 can be stored
  14873. in a signed byte, whereas +128 cannot.
  14874. }
  14875. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  14876. begin
  14877. if taicpu(p).opcode = A_ADD then
  14878. Opposite := A_SUB
  14879. else
  14880. Opposite := A_ADD;
  14881. { Be careful if the flags are in use, because the CF flag inverts
  14882. when changing from ADD to SUB and vice versa }
  14883. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  14884. GetNextInstruction(p, hp1) then
  14885. begin
  14886. TransferUsedRegs(TmpUsedRegs);
  14887. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  14888. hp2 := hp1;
  14889. { Scan ahead to check if everything's safe }
  14890. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  14891. begin
  14892. if (hp1.typ <> ait_instruction) then
  14893. { Probably unsafe since the flags are still in use }
  14894. Exit;
  14895. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  14896. { Stop searching at an unconditional jump }
  14897. Break;
  14898. if not
  14899. (
  14900. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  14901. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  14902. ) and
  14903. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  14904. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  14905. Exit;
  14906. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14907. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  14908. { Move to the next instruction }
  14909. GetNextInstruction(hp1, hp1);
  14910. end;
  14911. while Assigned(hp2) and (hp2 <> hp1) do
  14912. begin
  14913. NewCond := C_None;
  14914. case taicpu(hp2).condition of
  14915. C_A, C_NBE:
  14916. NewCond := C_BE;
  14917. C_B, C_C, C_NAE:
  14918. NewCond := C_AE;
  14919. C_AE, C_NB, C_NC:
  14920. NewCond := C_B;
  14921. C_BE, C_NA:
  14922. NewCond := C_A;
  14923. else
  14924. { No change needed };
  14925. end;
  14926. if NewCond <> C_None then
  14927. begin
  14928. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  14929. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  14930. taicpu(hp2).condition := NewCond;
  14931. end
  14932. else
  14933. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  14934. begin
  14935. { Because of the flipping of the carry bit, to ensure
  14936. the operation remains equivalent, ADC becomes SBB
  14937. and vice versa, and the constant is not-inverted.
  14938. If multiple ADCs or SBBs appear in a row, each one
  14939. changed causes the carry bit to invert, so they all
  14940. need to be flipped }
  14941. if taicpu(hp2).opcode = A_ADC then
  14942. SecondOpposite := A_SBB
  14943. else
  14944. SecondOpposite := A_ADC;
  14945. if taicpu(hp2).oper[0]^.typ <> top_const then
  14946. { Should have broken out of this optimisation already }
  14947. InternalError(2021112901);
  14948. 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]^) + ' -> ' +
  14949. 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);
  14950. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  14951. taicpu(hp2).opcode := SecondOpposite;
  14952. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  14953. end;
  14954. { Move to the next instruction }
  14955. GetNextInstruction(hp2, hp2);
  14956. end;
  14957. if (hp2 <> hp1) then
  14958. InternalError(2021111501);
  14959. end;
  14960. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  14961. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  14962. taicpu(p).opcode := Opposite;
  14963. taicpu(p).oper[0]^.val := -128;
  14964. { No further optimisations can be made on this instruction, so move
  14965. onto the next one to save time }
  14966. p := tai(p.Next);
  14967. UpdateUsedRegs(p);
  14968. Result := True;
  14969. Exit;
  14970. end;
  14971. { Detect:
  14972. add/sub %reg2,(dest)
  14973. add/sub x, (dest)
  14974. (dest can be a register or a reference)
  14975. Swap the instructions to minimise a pipeline stall. This reverses the
  14976. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  14977. optimisations could be made.
  14978. }
  14979. if (taicpu(p).oper[0]^.typ = top_reg) and
  14980. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  14981. (
  14982. (
  14983. (taicpu(p).oper[1]^.typ = top_reg) and
  14984. { We can try searching further ahead if we're writing to a register }
  14985. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  14986. ) or
  14987. (
  14988. (taicpu(p).oper[1]^.typ = top_ref) and
  14989. GetNextInstruction(p, hp1)
  14990. )
  14991. ) and
  14992. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  14993. (taicpu(hp1).oper[0]^.typ = top_const) and
  14994. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  14995. begin
  14996. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  14997. TransferUsedRegs(TmpUsedRegs);
  14998. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  14999. hp2 := p;
  15000. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15001. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15002. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15003. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15004. begin
  15005. asml.remove(hp1);
  15006. asml.InsertBefore(hp1, p);
  15007. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15008. Result := True;
  15009. end;
  15010. end;
  15011. end;
  15012. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15013. var
  15014. hp1: tai;
  15015. begin
  15016. Result:=false;
  15017. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15018. while GetNextInstruction(p, hp1) and
  15019. TrySwapMovCmp(p, hp1) do
  15020. begin
  15021. if MatchInstruction(hp1, A_MOV, []) then
  15022. begin
  15023. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15024. begin
  15025. { A little hacky, but since CMP doesn't read the flags, only
  15026. modify them, it's safe if they get scrambled by MOV -> XOR }
  15027. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15028. Result := PostPeepholeOptMov(hp1);
  15029. {$ifdef x86_64}
  15030. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15031. { Used to shrink instruction size }
  15032. PostPeepholeOptXor(hp1);
  15033. {$endif x86_64}
  15034. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15035. end
  15036. else
  15037. begin
  15038. Result := PostPeepholeOptMov(hp1);
  15039. {$ifdef x86_64}
  15040. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15041. { Used to shrink instruction size }
  15042. PostPeepholeOptXor(hp1);
  15043. {$endif x86_64}
  15044. end;
  15045. end;
  15046. { Enabling this flag is actually a null operation, but it marks
  15047. the code as 'modified' during this pass }
  15048. Include(OptsToCheck, aoc_ForceNewIteration);
  15049. end;
  15050. { change "cmp $0, %reg" to "test %reg, %reg" }
  15051. if MatchOpType(taicpu(p),top_const,top_reg) and
  15052. (taicpu(p).oper[0]^.val = 0) then
  15053. begin
  15054. taicpu(p).opcode := A_TEST;
  15055. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15056. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15057. Result:=true;
  15058. end;
  15059. end;
  15060. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15061. var
  15062. IsTestConstX, IsValid : Boolean;
  15063. hp1,hp2 : tai;
  15064. begin
  15065. Result:=false;
  15066. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15067. if (taicpu(p).opcode = A_TEST) then
  15068. while GetNextInstruction(p, hp1) and
  15069. TrySwapMovCmp(p, hp1) do
  15070. begin
  15071. if MatchInstruction(hp1, A_MOV, []) then
  15072. begin
  15073. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15074. begin
  15075. { A little hacky, but since TEST doesn't read the flags, only
  15076. modify them, it's safe if they get scrambled by MOV -> XOR }
  15077. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15078. Result := PostPeepholeOptMov(hp1);
  15079. {$ifdef x86_64}
  15080. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15081. { Used to shrink instruction size }
  15082. PostPeepholeOptXor(hp1);
  15083. {$endif x86_64}
  15084. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15085. end
  15086. else
  15087. begin
  15088. Result := PostPeepholeOptMov(hp1);
  15089. {$ifdef x86_64}
  15090. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15091. { Used to shrink instruction size }
  15092. PostPeepholeOptXor(hp1);
  15093. {$endif x86_64}
  15094. end;
  15095. end;
  15096. { Enabling this flag is actually a null operation, but it marks
  15097. the code as 'modified' during this pass }
  15098. Include(OptsToCheck, aoc_ForceNewIteration);
  15099. end;
  15100. { If x is a power of 2 (popcnt = 1), change:
  15101. or $x, %reg/ref
  15102. To:
  15103. bts lb(x), %reg/ref
  15104. }
  15105. if (taicpu(p).opcode = A_OR) and
  15106. IsBTXAcceptable(p) and
  15107. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15108. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15109. (
  15110. { Don't optimise if a test instruction follows }
  15111. not GetNextInstruction(p, hp1) or
  15112. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15113. ) then
  15114. begin
  15115. 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);
  15116. taicpu(p).opcode := A_BTS;
  15117. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15118. Result := True;
  15119. Exit;
  15120. end;
  15121. { If x is a power of 2 (popcnt = 1), change:
  15122. test $x, %reg/ref
  15123. je / sete / cmove (or jne / setne)
  15124. To:
  15125. bt lb(x), %reg/ref
  15126. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15127. }
  15128. if (taicpu(p).opcode = A_TEST) and
  15129. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15130. (taicpu(p).oper[0]^.typ = top_const) and
  15131. (
  15132. (cs_opt_size in current_settings.optimizerswitches) or
  15133. (
  15134. (taicpu(p).oper[1]^.typ = top_reg) and
  15135. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15136. ) or
  15137. (
  15138. (taicpu(p).oper[1]^.typ <> top_reg) and
  15139. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15140. )
  15141. ) and
  15142. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15143. { For sizes less than S_L, the byte size is equal or larger with BT,
  15144. so don't bother optimising }
  15145. (taicpu(p).opsize >= S_L) then
  15146. begin
  15147. IsValid := True;
  15148. { Check the next set of instructions, watching the FLAGS register
  15149. and the conditions used }
  15150. TransferUsedRegs(TmpUsedRegs);
  15151. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15152. hp1 := p;
  15153. hp2 := nil;
  15154. while GetNextInstruction(hp1, hp1) do
  15155. begin
  15156. if not Assigned(hp2) then
  15157. { The first instruction after TEST }
  15158. hp2 := hp1;
  15159. if (hp1.typ <> ait_instruction) then
  15160. begin
  15161. { If the flags are no longer in use, everything is fine }
  15162. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15163. IsValid := False;
  15164. Break;
  15165. end;
  15166. case taicpu(hp1).condition of
  15167. C_None:
  15168. begin
  15169. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15170. { Something is not quite normal, so play safe and don't change }
  15171. IsValid := False;
  15172. Break;
  15173. end;
  15174. C_E, C_Z, C_NE, C_NZ:
  15175. { This is fine };
  15176. else
  15177. begin
  15178. { Unsupported condition }
  15179. IsValid := False;
  15180. Break;
  15181. end;
  15182. end;
  15183. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15184. end;
  15185. if IsValid then
  15186. begin
  15187. while hp2 <> hp1 do
  15188. begin
  15189. case taicpu(hp2).condition of
  15190. C_Z, C_E:
  15191. taicpu(hp2).condition := C_NC;
  15192. C_NZ, C_NE:
  15193. taicpu(hp2).condition := C_C;
  15194. else
  15195. { Should not get this by this point }
  15196. InternalError(2022110701);
  15197. end;
  15198. GetNextInstruction(hp2, hp2);
  15199. end;
  15200. 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);
  15201. taicpu(p).opcode := A_BT;
  15202. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15203. Result := True;
  15204. Exit;
  15205. end;
  15206. end;
  15207. { removes the line marked with (x) from the sequence
  15208. and/or/xor/add/sub/... $x, %y
  15209. test/or %y, %y | test $-1, %y (x)
  15210. j(n)z _Label
  15211. as the first instruction already adjusts the ZF
  15212. %y operand may also be a reference }
  15213. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15214. MatchOperand(taicpu(p).oper[0]^,-1);
  15215. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15216. GetLastInstruction(p, hp1) and
  15217. (tai(hp1).typ = ait_instruction) and
  15218. GetNextInstruction(p,hp2) and
  15219. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15220. case taicpu(hp1).opcode Of
  15221. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15222. { These two instructions set the zero flag if the result is zero }
  15223. A_POPCNT, A_LZCNT:
  15224. begin
  15225. if (
  15226. { With POPCNT, an input of zero will set the zero flag
  15227. because the population count of zero is zero }
  15228. (taicpu(hp1).opcode = A_POPCNT) and
  15229. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15230. (
  15231. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15232. { Faster than going through the second half of the 'or'
  15233. condition below }
  15234. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15235. )
  15236. ) or (
  15237. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15238. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15239. { and in case of carry for A(E)/B(E)/C/NC }
  15240. (
  15241. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15242. (
  15243. (taicpu(hp1).opcode <> A_ADD) and
  15244. (taicpu(hp1).opcode <> A_SUB) and
  15245. (taicpu(hp1).opcode <> A_LZCNT)
  15246. )
  15247. )
  15248. ) then
  15249. begin
  15250. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15251. RemoveCurrentP(p, hp2);
  15252. Result:=true;
  15253. Exit;
  15254. end;
  15255. end;
  15256. A_SHL, A_SAL, A_SHR, A_SAR:
  15257. begin
  15258. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15259. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15260. { therefore, it's only safe to do this optimization for }
  15261. { shifts by a (nonzero) constant }
  15262. (taicpu(hp1).oper[0]^.typ = top_const) and
  15263. (taicpu(hp1).oper[0]^.val <> 0) and
  15264. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15265. { and in case of carry for A(E)/B(E)/C/NC }
  15266. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15267. begin
  15268. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15269. RemoveCurrentP(p, hp2);
  15270. Result:=true;
  15271. Exit;
  15272. end;
  15273. end;
  15274. A_DEC, A_INC, A_NEG:
  15275. begin
  15276. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15277. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15278. { and in case of carry for A(E)/B(E)/C/NC }
  15279. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15280. begin
  15281. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15282. RemoveCurrentP(p, hp2);
  15283. Result:=true;
  15284. Exit;
  15285. end;
  15286. end;
  15287. A_ANDN, A_BZHI:
  15288. begin
  15289. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15290. { Only the zero and sign flags are consistent with what the result is }
  15291. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15292. begin
  15293. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15294. RemoveCurrentP(p, hp2);
  15295. Result:=true;
  15296. Exit;
  15297. end;
  15298. end;
  15299. A_BEXTR:
  15300. begin
  15301. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15302. { Only the zero flag is set }
  15303. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15304. begin
  15305. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15306. RemoveCurrentP(p, hp2);
  15307. Result:=true;
  15308. Exit;
  15309. end;
  15310. end;
  15311. else
  15312. ;
  15313. end; { case }
  15314. { change "test $-1,%reg" into "test %reg,%reg" }
  15315. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15316. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15317. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15318. if MatchInstruction(p, A_OR, []) and
  15319. { Can only match if they're both registers }
  15320. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15321. begin
  15322. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15323. taicpu(p).opcode := A_TEST;
  15324. { No need to set Result to True, as we've done all the optimisations we can }
  15325. end;
  15326. end;
  15327. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15328. var
  15329. hp1,hp3 : tai;
  15330. {$ifndef x86_64}
  15331. hp2 : taicpu;
  15332. {$endif x86_64}
  15333. begin
  15334. Result:=false;
  15335. hp3:=nil;
  15336. {$ifndef x86_64}
  15337. { don't do this on modern CPUs, this really hurts them due to
  15338. broken call/ret pairing }
  15339. if (current_settings.optimizecputype < cpu_Pentium2) and
  15340. not(cs_create_pic in current_settings.moduleswitches) and
  15341. GetNextInstruction(p, hp1) and
  15342. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15343. MatchOpType(taicpu(hp1),top_ref) and
  15344. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15345. begin
  15346. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15347. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15348. InsertLLItem(p.previous, p, hp2);
  15349. taicpu(p).opcode := A_JMP;
  15350. taicpu(p).is_jmp := true;
  15351. RemoveInstruction(hp1);
  15352. Result:=true;
  15353. end
  15354. else
  15355. {$endif x86_64}
  15356. { replace
  15357. call procname
  15358. ret
  15359. by
  15360. jmp procname
  15361. but do it only on level 4 because it destroys stack back traces
  15362. else if the subroutine is marked as no return, remove the ret
  15363. }
  15364. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15365. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15366. GetNextInstruction(p, hp1) and
  15367. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15368. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15369. SetAndTest(hp1,hp3) and
  15370. GetNextInstruction(hp1,hp1) and
  15371. MatchInstruction(hp1,A_RET,[S_NO])
  15372. )
  15373. ) and
  15374. (taicpu(hp1).ops=0) then
  15375. begin
  15376. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15377. { we might destroy stack alignment here if we do not do a call }
  15378. (target_info.stackalign<=sizeof(SizeUInt)) then
  15379. begin
  15380. taicpu(p).opcode := A_JMP;
  15381. taicpu(p).is_jmp := true;
  15382. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15383. end
  15384. else
  15385. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15386. RemoveInstruction(hp1);
  15387. if Assigned(hp3) then
  15388. begin
  15389. AsmL.Remove(hp3);
  15390. AsmL.InsertBefore(hp3,p)
  15391. end;
  15392. Result:=true;
  15393. end;
  15394. end;
  15395. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15396. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15397. begin
  15398. case OpSize of
  15399. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15400. Result := (Val <= $FF) and (Val >= -128);
  15401. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15402. Result := (Val <= $FFFF) and (Val >= -32768);
  15403. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15404. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15405. else
  15406. Result := True;
  15407. end;
  15408. end;
  15409. var
  15410. hp1, hp2 : tai;
  15411. SizeChange: Boolean;
  15412. PreMessage: string;
  15413. begin
  15414. Result := False;
  15415. if (taicpu(p).oper[0]^.typ = top_reg) and
  15416. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15417. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15418. begin
  15419. { Change (using movzbl %al,%eax as an example):
  15420. movzbl %al, %eax movzbl %al, %eax
  15421. cmpl x, %eax testl %eax,%eax
  15422. To:
  15423. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15424. movzbl %al, %eax movzbl %al, %eax
  15425. Smaller instruction and minimises pipeline stall as the CPU
  15426. doesn't have to wait for the register to get zero-extended. [Kit]
  15427. Also allow if the smaller of the two registers is being checked,
  15428. as this still removes the false dependency.
  15429. }
  15430. if
  15431. (
  15432. (
  15433. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15434. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15435. ) or (
  15436. { If MatchOperand returns True, they must both be registers }
  15437. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15438. )
  15439. ) and
  15440. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15441. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15442. begin
  15443. 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);
  15444. asml.Remove(hp1);
  15445. asml.InsertBefore(hp1, p);
  15446. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15447. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15448. begin
  15449. taicpu(hp1).opcode := A_TEST;
  15450. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15451. end;
  15452. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15453. case taicpu(p).opsize of
  15454. S_BW, S_BL:
  15455. begin
  15456. SizeChange := taicpu(hp1).opsize <> S_B;
  15457. taicpu(hp1).changeopsize(S_B);
  15458. end;
  15459. S_WL:
  15460. begin
  15461. SizeChange := taicpu(hp1).opsize <> S_W;
  15462. taicpu(hp1).changeopsize(S_W);
  15463. end
  15464. else
  15465. InternalError(2020112701);
  15466. end;
  15467. UpdateUsedRegs(tai(p.Next));
  15468. { Check if the register is used aferwards - if not, we can
  15469. remove the movzx instruction completely }
  15470. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15471. begin
  15472. { Hp1 is a better position than p for debugging purposes }
  15473. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15474. RemoveCurrentp(p, hp1);
  15475. Result := True;
  15476. end;
  15477. if SizeChange then
  15478. DebugMsg(SPeepholeOptimization + PreMessage +
  15479. 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)
  15480. else
  15481. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15482. Exit;
  15483. end;
  15484. { Change (using movzwl %ax,%eax as an example):
  15485. movzwl %ax, %eax
  15486. movb %al, (dest) (Register is smaller than read register in movz)
  15487. To:
  15488. movb %al, (dest) (Move one back to avoid a false dependency)
  15489. movzwl %ax, %eax
  15490. }
  15491. if (taicpu(hp1).opcode = A_MOV) and
  15492. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15493. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15494. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15495. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15496. begin
  15497. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15498. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15499. asml.Remove(hp1);
  15500. asml.InsertBefore(hp1, p);
  15501. if taicpu(hp1).oper[1]^.typ = top_reg then
  15502. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15503. { Check if the register is used aferwards - if not, we can
  15504. remove the movzx instruction completely }
  15505. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15506. begin
  15507. { Hp1 is a better position than p for debugging purposes }
  15508. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15509. RemoveCurrentp(p, hp1);
  15510. Result := True;
  15511. end;
  15512. Exit;
  15513. end;
  15514. end;
  15515. end;
  15516. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15517. var
  15518. hp1: tai;
  15519. {$ifdef x86_64}
  15520. PreMessage, RegName: string;
  15521. {$endif x86_64}
  15522. begin
  15523. Result := False;
  15524. { If x is a power of 2 (popcnt = 1), change:
  15525. xor $x, %reg/ref
  15526. To:
  15527. btc lb(x), %reg/ref
  15528. }
  15529. if IsBTXAcceptable(p) and
  15530. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15531. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15532. (
  15533. { Don't optimise if a test instruction follows }
  15534. not GetNextInstruction(p, hp1) or
  15535. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15536. ) then
  15537. begin
  15538. 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);
  15539. taicpu(p).opcode := A_BTC;
  15540. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15541. Result := True;
  15542. Exit;
  15543. end;
  15544. {$ifdef x86_64}
  15545. { Code size reduction by J. Gareth "Kit" Moreton }
  15546. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15547. as this removes the REX prefix }
  15548. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15549. Exit;
  15550. if taicpu(p).oper[0]^.typ <> top_reg then
  15551. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15552. InternalError(2018011500);
  15553. case taicpu(p).opsize of
  15554. S_Q:
  15555. begin
  15556. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15557. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15558. { The actual optimization }
  15559. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15560. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15561. taicpu(p).changeopsize(S_L);
  15562. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15563. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15564. end;
  15565. else
  15566. ;
  15567. end;
  15568. {$endif x86_64}
  15569. end;
  15570. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15571. var
  15572. XReg: TRegister;
  15573. begin
  15574. Result := False;
  15575. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15576. Smaller encoding and slightly faster on some platforms (also works for
  15577. ZMM-sized registers) }
  15578. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15579. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15580. begin
  15581. XReg := taicpu(p).oper[0]^.reg;
  15582. if (taicpu(p).oper[1]^.reg = XReg) then
  15583. begin
  15584. taicpu(p).changeopsize(S_XMM);
  15585. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15586. if (cs_opt_size in current_settings.optimizerswitches) then
  15587. begin
  15588. { Change input registers to %xmm0 to reduce size. Note that
  15589. there's a risk of a false dependency doing this, so only
  15590. optimise for size here }
  15591. XReg := NR_XMM0;
  15592. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15593. end
  15594. else
  15595. begin
  15596. setsubreg(XReg, R_SUBMMX);
  15597. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15598. end;
  15599. taicpu(p).oper[0]^.reg := XReg;
  15600. taicpu(p).oper[1]^.reg := XReg;
  15601. Result := True;
  15602. end;
  15603. end;
  15604. end;
  15605. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15606. var
  15607. OperIdx: Integer;
  15608. begin
  15609. for OperIdx := 0 to p.ops - 1 do
  15610. if p.oper[OperIdx]^.typ = top_ref then
  15611. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15612. end;
  15613. end.