aoptx86.pas 721 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992
  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 OptPass1_V_MOVAP(var p : tai) : boolean;
  128. function OptPass1VOP(var p : tai) : boolean;
  129. function OptPass1MOV(var p : tai) : boolean;
  130. function OptPass1Movx(var p : tai) : boolean;
  131. function OptPass1MOVXX(var p : tai) : boolean;
  132. function OptPass1OP(var p : tai) : boolean;
  133. function OptPass1LEA(var p : tai) : boolean;
  134. function OptPass1Sub(var p : tai) : boolean;
  135. function OptPass1SHLSAL(var p : tai) : boolean;
  136. function OptPass1SHR(var p : tai) : boolean;
  137. function OptPass1FSTP(var p : tai) : boolean;
  138. function OptPass1FLD(var p : tai) : boolean;
  139. function OptPass1Cmp(var p : tai) : boolean;
  140. function OptPass1PXor(var p : tai) : boolean;
  141. function OptPass1VPXor(var p: tai): boolean;
  142. function OptPass1Imul(var p : tai) : boolean;
  143. function OptPass1Jcc(var p : tai) : boolean;
  144. function OptPass1SHXX(var p: tai): boolean;
  145. function OptPass1VMOVDQ(var p: tai): Boolean;
  146. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  147. function OptPass1STCCLC(var p: tai): Boolean;
  148. function OptPass2STCCLC(var p: tai): Boolean;
  149. function OptPass2Movx(var p : tai): Boolean;
  150. function OptPass2MOV(var p : tai) : boolean;
  151. function OptPass2Imul(var p : tai) : boolean;
  152. function OptPass2Jmp(var p : tai) : boolean;
  153. function OptPass2Jcc(var p : tai) : boolean;
  154. function OptPass2Lea(var p: tai): Boolean;
  155. function OptPass2SUB(var p: tai): Boolean;
  156. function OptPass2ADD(var p : tai): Boolean;
  157. function OptPass2SETcc(var p : tai) : boolean;
  158. function OptPass2Cmp(var p: tai): Boolean;
  159. function OptPass2Test(var p: tai): Boolean;
  160. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  161. function PostPeepholeOptMov(var p : tai) : Boolean;
  162. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  163. function PostPeepholeOptXor(var p : tai) : Boolean;
  164. function PostPeepholeOptAnd(var p : tai) : boolean;
  165. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  166. function PostPeepholeOptCmp(var p : tai) : Boolean;
  167. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  168. function PostPeepholeOptCall(var p : tai) : Boolean;
  169. function PostPeepholeOptLea(var p : tai) : Boolean;
  170. function PostPeepholeOptPush(var p: tai): Boolean;
  171. function PostPeepholeOptShr(var p : tai) : boolean;
  172. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  173. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  174. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  175. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  176. function TrySwapMovOp(var p, hp1: tai): Boolean;
  177. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  178. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  179. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  180. { Processor-dependent reference optimisation }
  181. class procedure OptimizeRefs(var p: taicpu); static;
  182. end;
  183. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  184. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  185. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  186. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  187. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  188. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  189. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  190. {$if max_operands>2}
  191. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  192. {$endif max_operands>2}
  193. function RefsEqual(const r1, r2: treference): boolean;
  194. { Note that Result is set to True if the references COULD overlap but the
  195. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  196. might still overlap because %reg2 could be equal to %reg1-4 }
  197. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  198. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  199. { returns true, if ref is a reference using only the registers passed as base and index
  200. and having an offset }
  201. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  202. implementation
  203. uses
  204. cutils,verbose,
  205. systems,
  206. globals,
  207. cpuinfo,
  208. procinfo,
  209. paramgr,
  210. aasmbase,
  211. aoptbase,aoptutils,
  212. symconst,symsym,
  213. cgx86,
  214. itcpugas;
  215. {$ifndef 8086}
  216. const
  217. MAX_CMOV_INSTRUCTIONS = 4;
  218. MAX_CMOV_REGISTERS = 8;
  219. type
  220. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  221. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  222. tsProcessed);
  223. { For OptPass2Jcc }
  224. TCMOVTracking = object
  225. private
  226. CMOVScore, ConstCount: LongInt;
  227. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  228. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  229. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  230. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  231. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  232. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  233. fOptimizer: TX86AsmOptimizer;
  234. fLabel: TAsmSymbol;
  235. fInsertionPoint,
  236. fCondition,
  237. fInitialJump,
  238. fFirstMovBlock,
  239. fFirstMovBlockStop,
  240. fSecondJump,
  241. fThirdJump,
  242. fSecondMovBlock,
  243. fSecondMovBlockStop,
  244. fMidLabel,
  245. fEndLabel,
  246. fAllocationRange: tai;
  247. fState: TCMovTrackingState;
  248. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  249. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  250. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  251. public
  252. RegisterTracking: TAllUsedRegs;
  253. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  254. destructor Done;
  255. procedure Process(out new_p: tai);
  256. property State: TCMovTrackingState read fState;
  257. end;
  258. PCMOVTracking = ^TCMOVTracking;
  259. {$endif 8086}
  260. {$ifdef DEBUG_AOPTCPU}
  261. const
  262. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  263. {$else DEBUG_AOPTCPU}
  264. { Empty strings help the optimizer to remove string concatenations that won't
  265. ever appear to the user on release builds. [Kit] }
  266. const
  267. SPeepholeOptimization = '';
  268. {$endif DEBUG_AOPTCPU}
  269. LIST_STEP_SIZE = 4;
  270. type
  271. TJumpTrackingItem = class(TLinkedListItem)
  272. private
  273. FSymbol: TAsmSymbol;
  274. FRefs: LongInt;
  275. public
  276. constructor Create(ASymbol: TAsmSymbol);
  277. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  278. property Symbol: TAsmSymbol read FSymbol;
  279. property Refs: LongInt read FRefs;
  280. end;
  281. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  282. begin
  283. inherited Create;
  284. FSymbol := ASymbol;
  285. FRefs := 0;
  286. end;
  287. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  288. begin
  289. Inc(FRefs);
  290. end;
  291. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  292. begin
  293. result :=
  294. (instr.typ = ait_instruction) and
  295. (taicpu(instr).opcode = op) and
  296. ((opsize = []) or (taicpu(instr).opsize in opsize));
  297. end;
  298. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  299. begin
  300. result :=
  301. (instr.typ = ait_instruction) and
  302. ((taicpu(instr).opcode = op1) or
  303. (taicpu(instr).opcode = op2)
  304. ) and
  305. ((opsize = []) or (taicpu(instr).opsize in opsize));
  306. end;
  307. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  308. begin
  309. result :=
  310. (instr.typ = ait_instruction) and
  311. ((taicpu(instr).opcode = op1) or
  312. (taicpu(instr).opcode = op2) or
  313. (taicpu(instr).opcode = op3)
  314. ) and
  315. ((opsize = []) or (taicpu(instr).opsize in opsize));
  316. end;
  317. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  318. const opsize : topsizes) : boolean;
  319. var
  320. op : TAsmOp;
  321. begin
  322. result:=false;
  323. if (instr.typ <> ait_instruction) or
  324. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  325. exit;
  326. for op in ops do
  327. begin
  328. if taicpu(instr).opcode = op then
  329. begin
  330. result:=true;
  331. exit;
  332. end;
  333. end;
  334. end;
  335. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  336. begin
  337. result := (oper.typ = top_reg) and (oper.reg = reg);
  338. end;
  339. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  340. begin
  341. result := (oper.typ = top_const) and (oper.val = a);
  342. end;
  343. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  344. begin
  345. result := oper1.typ = oper2.typ;
  346. if result then
  347. case oper1.typ of
  348. top_const:
  349. Result:=oper1.val = oper2.val;
  350. top_reg:
  351. Result:=oper1.reg = oper2.reg;
  352. top_ref:
  353. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  354. else
  355. internalerror(2013102801);
  356. end
  357. end;
  358. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  359. begin
  360. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  361. if result then
  362. case oper1.typ of
  363. top_const:
  364. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  365. top_reg:
  366. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  367. top_ref:
  368. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  369. else
  370. internalerror(2020052401);
  371. end
  372. end;
  373. function RefsEqual(const r1, r2: treference): boolean;
  374. begin
  375. RefsEqual :=
  376. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  377. (r1.relsymbol = r2.relsymbol) and
  378. (r1.segment = r2.segment) and (r1.base = r2.base) and
  379. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  380. (r1.offset = r2.offset) and
  381. (r1.volatility + r2.volatility = []);
  382. end;
  383. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  384. begin
  385. if (r1.symbol<>r2.symbol) then
  386. { If the index registers are different, there's a chance one could
  387. be set so it equals the other symbol }
  388. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  389. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  390. (r1.relsymbol = r2.relsymbol) and
  391. (r1.segment = r2.segment) and (r1.base = r2.base) and
  392. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  393. (r1.volatility + r2.volatility = []) then
  394. { In this case, it all depends on the offsets }
  395. Exit(abs(r1.offset - r2.offset) < Range);
  396. { There's a chance things MIGHT overlap, so take no chances }
  397. Result := True;
  398. end;
  399. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  400. begin
  401. Result:=(ref.offset=0) and
  402. (ref.scalefactor in [0,1]) and
  403. (ref.segment=NR_NO) and
  404. (ref.symbol=nil) and
  405. (ref.relsymbol=nil) and
  406. ((base=NR_INVALID) or
  407. (ref.base=base)) and
  408. ((index=NR_INVALID) or
  409. (ref.index=index)) and
  410. (ref.volatility=[]);
  411. end;
  412. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  413. begin
  414. Result:=(ref.scalefactor in [0,1]) and
  415. (ref.segment=NR_NO) and
  416. (ref.symbol=nil) and
  417. (ref.relsymbol=nil) and
  418. ((base=NR_INVALID) or
  419. (ref.base=base)) and
  420. ((index=NR_INVALID) or
  421. (ref.index=index)) and
  422. (ref.volatility=[]);
  423. end;
  424. function InstrReadsFlags(p: tai): boolean;
  425. begin
  426. InstrReadsFlags := true;
  427. case p.typ of
  428. ait_instruction:
  429. if InsProp[taicpu(p).opcode].Ch*
  430. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  431. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  432. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  433. exit;
  434. ait_label:
  435. exit;
  436. else
  437. ;
  438. end;
  439. InstrReadsFlags := false;
  440. end;
  441. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  442. begin
  443. Next:=Current;
  444. repeat
  445. Result:=GetNextInstruction(Next,Next);
  446. until not (Result) or
  447. not(cs_opt_level3 in current_settings.optimizerswitches) or
  448. (Next.typ<>ait_instruction) or
  449. RegInInstruction(reg,Next) or
  450. is_calljmp(taicpu(Next).opcode);
  451. end;
  452. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  453. var
  454. GetNextResult: Boolean;
  455. begin
  456. Result:=0;
  457. Next:=Current;
  458. repeat
  459. GetNextResult := GetNextInstruction(Next,Next);
  460. if GetNextResult then
  461. Inc(Result)
  462. else
  463. { Must return zero upon hitting the end of the linked list without a match }
  464. Result := 0;
  465. until not (GetNextResult) or
  466. not(cs_opt_level3 in current_settings.optimizerswitches) or
  467. (Next.typ<>ait_instruction) or
  468. RegInInstruction(reg,Next) or
  469. is_calljmp(taicpu(Next).opcode);
  470. end;
  471. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  472. procedure TrackJump(Symbol: TAsmSymbol);
  473. var
  474. Search: TJumpTrackingItem;
  475. begin
  476. { See if an entry already exists in our jump tracking list
  477. (faster to search backwards due to the higher chance of
  478. matching destinations) }
  479. Search := TJumpTrackingItem(JumpTracking.Last);
  480. while Assigned(Search) do
  481. begin
  482. if Search.Symbol = Symbol then
  483. begin
  484. { Found it - remove it so it can be pushed to the front }
  485. JumpTracking.Remove(Search);
  486. Break;
  487. end;
  488. Search := TJumpTrackingItem(Search.Previous);
  489. end;
  490. if not Assigned(Search) then
  491. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  492. JumpTracking.Concat(Search);
  493. Search.IncRefs;
  494. end;
  495. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  496. var
  497. Search: TJumpTrackingItem;
  498. begin
  499. Result := False;
  500. { See if this label appears in the tracking list }
  501. Search := TJumpTrackingItem(JumpTracking.Last);
  502. while Assigned(Search) do
  503. begin
  504. if Search.Symbol = Symbol then
  505. begin
  506. { Found it - let's see what we can discover }
  507. if Search.Symbol.getrefs = Search.Refs then
  508. begin
  509. { Success - all the references are accounted for }
  510. JumpTracking.Remove(Search);
  511. Search.Free;
  512. { It is logically impossible for CrossJump to be false here
  513. because we must have run into a conditional jump for
  514. this label at some point }
  515. if not CrossJump then
  516. InternalError(2022041710);
  517. if JumpTracking.First = nil then
  518. { Tracking list is now empty - no more cross jumps }
  519. CrossJump := False;
  520. Result := True;
  521. Exit;
  522. end;
  523. { If the references don't match, it's possible to enter
  524. this label through other means, so drop out }
  525. Exit;
  526. end;
  527. Search := TJumpTrackingItem(Search.Previous);
  528. end;
  529. end;
  530. var
  531. Next_Label: tai;
  532. begin
  533. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  534. Next := Current;
  535. repeat
  536. Result := GetNextInstruction(Next,Next);
  537. if not Result then
  538. Break;
  539. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  540. if is_calljmpuncondret(taicpu(Next).opcode) then
  541. begin
  542. if (taicpu(Next).opcode = A_JMP) and
  543. { Remove dead code now to save time }
  544. RemoveDeadCodeAfterJump(taicpu(Next)) then
  545. { A jump was removed, but not the current instruction, and
  546. Result doesn't necessarily translate into an optimisation
  547. routine's Result, so use the "Force New Iteration" flag so
  548. mark a new pass }
  549. Include(OptsToCheck, aoc_ForceNewIteration);
  550. if not Assigned(JumpTracking) then
  551. begin
  552. { Cross-label optimisations often causes other optimisations
  553. to perform worse because they're not given the chance to
  554. optimise locally. In this case, don't do the cross-label
  555. optimisations yet, but flag them as a potential possibility
  556. for the next iteration of Pass 1 }
  557. if not NotFirstIteration then
  558. Include(OptsToCheck, aoc_ForceNewIteration);
  559. end
  560. else if IsJumpToLabel(taicpu(Next)) and
  561. GetNextInstruction(Next, Next_Label) then
  562. begin
  563. { If we have JMP .lbl, and the label after it has all of its
  564. references tracked, then this is probably an if-else style of
  565. block and we can keep tracking. If the label for this jump
  566. then appears later and is fully tracked, then it's the end
  567. of the if-else blocks and the code paths converge (thus
  568. marking the end of the cross-jump) }
  569. if (Next_Label.typ = ait_label) then
  570. begin
  571. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  572. begin
  573. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  574. Next := Next_Label;
  575. { CrossJump gets set to false by LabelAccountedFor if the
  576. list is completely emptied (as it indicates that all
  577. code paths have converged). We could avoid this nuance
  578. by moving the TrackJump call to before the
  579. LabelAccountedFor call, but this is slower in situations
  580. where LabelAccountedFor would return False due to the
  581. creation of a new object that is not used and destroyed
  582. soon after. }
  583. CrossJump := True;
  584. Continue;
  585. end;
  586. end
  587. else if (Next_Label.typ <> ait_marker) then
  588. { We just did a RemoveDeadCodeAfterJump, so either we find
  589. a label, the end of the procedure or some kind of marker}
  590. InternalError(2022041720);
  591. end;
  592. Result := False;
  593. Exit;
  594. end
  595. else
  596. begin
  597. if not Assigned(JumpTracking) then
  598. begin
  599. { Cross-label optimisations often causes other optimisations
  600. to perform worse because they're not given the chance to
  601. optimise locally. In this case, don't do the cross-label
  602. optimisations yet, but flag them as a potential possibility
  603. for the next iteration of Pass 1 }
  604. if not NotFirstIteration then
  605. Include(OptsToCheck, aoc_ForceNewIteration);
  606. end
  607. else if IsJumpToLabel(taicpu(Next)) then
  608. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  609. else
  610. { Conditional jumps should always be a jump to label }
  611. InternalError(2022041701);
  612. CrossJump := True;
  613. Continue;
  614. end;
  615. if Next.typ = ait_label then
  616. begin
  617. if not Assigned(JumpTracking) then
  618. begin
  619. { Cross-label optimisations often causes other optimisations
  620. to perform worse because they're not given the chance to
  621. optimise locally. In this case, don't do the cross-label
  622. optimisations yet, but flag them as a potential possibility
  623. for the next iteration of Pass 1 }
  624. if not NotFirstIteration then
  625. Include(OptsToCheck, aoc_ForceNewIteration);
  626. end
  627. else if LabelAccountedFor(tai_label(Next).labsym) then
  628. Continue;
  629. { If we reach here, we're at a label that hasn't been seen before
  630. (or JumpTracking was nil) }
  631. Break;
  632. end;
  633. until not Result or
  634. not (cs_opt_level3 in current_settings.optimizerswitches) or
  635. not (Next.typ in [ait_label, ait_instruction]) or
  636. RegInInstruction(reg,Next);
  637. end;
  638. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  639. begin
  640. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  641. begin
  642. Result:=GetNextInstruction(Current,Next);
  643. exit;
  644. end;
  645. Next:=tai(Current.Next);
  646. Result:=false;
  647. while assigned(Next) do
  648. begin
  649. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  650. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  651. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  652. exit
  653. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  654. begin
  655. Result:=true;
  656. exit;
  657. end;
  658. Next:=tai(Next.Next);
  659. end;
  660. end;
  661. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  662. begin
  663. Result:=RegReadByInstruction(reg,hp);
  664. end;
  665. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  666. var
  667. p: taicpu;
  668. opcount: longint;
  669. begin
  670. RegReadByInstruction := false;
  671. if hp.typ <> ait_instruction then
  672. exit;
  673. p := taicpu(hp);
  674. case p.opcode of
  675. A_CALL:
  676. regreadbyinstruction := true;
  677. A_IMUL:
  678. case p.ops of
  679. 1:
  680. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  681. (
  682. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  683. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  684. );
  685. 2,3:
  686. regReadByInstruction :=
  687. reginop(reg,p.oper[0]^) or
  688. reginop(reg,p.oper[1]^);
  689. else
  690. InternalError(2019112801);
  691. end;
  692. A_MUL:
  693. begin
  694. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  695. (
  696. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  697. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  698. );
  699. end;
  700. A_IDIV,A_DIV:
  701. begin
  702. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  703. (
  704. (getregtype(reg)=R_INTREGISTER) and
  705. (
  706. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  707. )
  708. );
  709. end;
  710. else
  711. begin
  712. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  713. begin
  714. RegReadByInstruction := false;
  715. exit;
  716. end;
  717. for opcount := 0 to p.ops-1 do
  718. if (p.oper[opCount]^.typ = top_ref) and
  719. RegInRef(reg,p.oper[opcount]^.ref^) then
  720. begin
  721. RegReadByInstruction := true;
  722. exit
  723. end;
  724. { special handling for SSE MOVSD }
  725. if (p.opcode=A_MOVSD) and (p.ops>0) then
  726. begin
  727. if p.ops<>2 then
  728. internalerror(2017042702);
  729. regReadByInstruction := reginop(reg,p.oper[0]^) or
  730. (
  731. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  732. );
  733. exit;
  734. end;
  735. with insprop[p.opcode] do
  736. begin
  737. case getregtype(reg) of
  738. R_INTREGISTER:
  739. begin
  740. case getsupreg(reg) of
  741. RS_EAX:
  742. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  743. begin
  744. RegReadByInstruction := true;
  745. exit
  746. end;
  747. RS_ECX:
  748. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  749. begin
  750. RegReadByInstruction := true;
  751. exit
  752. end;
  753. RS_EDX:
  754. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  755. begin
  756. RegReadByInstruction := true;
  757. exit
  758. end;
  759. RS_EBX:
  760. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  761. begin
  762. RegReadByInstruction := true;
  763. exit
  764. end;
  765. RS_ESP:
  766. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  767. begin
  768. RegReadByInstruction := true;
  769. exit
  770. end;
  771. RS_EBP:
  772. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  773. begin
  774. RegReadByInstruction := true;
  775. exit
  776. end;
  777. RS_ESI:
  778. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  779. begin
  780. RegReadByInstruction := true;
  781. exit
  782. end;
  783. RS_EDI:
  784. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  785. begin
  786. RegReadByInstruction := true;
  787. exit
  788. end;
  789. end;
  790. end;
  791. R_MMREGISTER:
  792. begin
  793. case getsupreg(reg) of
  794. RS_XMM0:
  795. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  796. begin
  797. RegReadByInstruction := true;
  798. exit
  799. end;
  800. end;
  801. end;
  802. else
  803. ;
  804. end;
  805. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  806. begin
  807. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  808. begin
  809. case p.condition of
  810. C_A,C_NBE, { CF=0 and ZF=0 }
  811. C_BE,C_NA: { CF=1 or ZF=1 }
  812. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  813. C_AE,C_NB,C_NC, { CF=0 }
  814. C_B,C_NAE,C_C: { CF=1 }
  815. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  816. C_NE,C_NZ, { ZF=0 }
  817. C_E,C_Z: { ZF=1 }
  818. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  819. C_G,C_NLE, { ZF=0 and SF=OF }
  820. C_LE,C_NG: { ZF=1 or SF<>OF }
  821. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  822. C_GE,C_NL, { SF=OF }
  823. C_L,C_NGE: { SF<>OF }
  824. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  825. C_NO, { OF=0 }
  826. C_O: { OF=1 }
  827. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  828. C_NP,C_PO, { PF=0 }
  829. C_P,C_PE: { PF=1 }
  830. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  831. C_NS, { SF=0 }
  832. C_S: { SF=1 }
  833. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  834. else
  835. internalerror(2017042701);
  836. end;
  837. if RegReadByInstruction then
  838. exit;
  839. end;
  840. case getsubreg(reg) of
  841. R_SUBW,R_SUBD,R_SUBQ:
  842. RegReadByInstruction :=
  843. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  844. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  845. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  846. R_SUBFLAGCARRY:
  847. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  848. R_SUBFLAGPARITY:
  849. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  850. R_SUBFLAGAUXILIARY:
  851. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  852. R_SUBFLAGZERO:
  853. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  854. R_SUBFLAGSIGN:
  855. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  856. R_SUBFLAGOVERFLOW:
  857. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  858. R_SUBFLAGINTERRUPT:
  859. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  860. R_SUBFLAGDIRECTION:
  861. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  862. else
  863. internalerror(2017042601);
  864. end;
  865. exit;
  866. end;
  867. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  868. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  869. (p.oper[0]^.reg=p.oper[1]^.reg) then
  870. exit;
  871. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  872. begin
  873. RegReadByInstruction := true;
  874. exit
  875. end;
  876. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  877. begin
  878. RegReadByInstruction := true;
  879. exit
  880. end;
  881. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  882. begin
  883. RegReadByInstruction := true;
  884. exit
  885. end;
  886. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  887. begin
  888. RegReadByInstruction := true;
  889. exit
  890. end;
  891. end;
  892. end;
  893. end;
  894. end;
  895. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  896. begin
  897. result:=false;
  898. if p1.typ<>ait_instruction then
  899. exit;
  900. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  901. exit(true);
  902. if (getregtype(reg)=R_INTREGISTER) and
  903. { change information for xmm movsd are not correct }
  904. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  905. begin
  906. { Handle instructions that behave differently depending on the size and operand count }
  907. case taicpu(p1).opcode of
  908. A_MUL, A_DIV, A_IDIV:
  909. if taicpu(p1).opsize = S_B then
  910. Result := (getsupreg(Reg) = RS_EAX)
  911. else
  912. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  913. A_IMUL:
  914. if taicpu(p1).ops = 1 then
  915. begin
  916. if taicpu(p1).opsize = S_B then
  917. Result := (getsupreg(Reg) = RS_EAX)
  918. else
  919. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  920. end;
  921. { If ops are greater than 1, call inherited method }
  922. else
  923. case getsupreg(reg) of
  924. { RS_EAX = RS_RAX on x86-64 }
  925. RS_EAX:
  926. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  927. RS_ECX:
  928. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  929. RS_EDX:
  930. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  931. RS_EBX:
  932. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  933. RS_ESP:
  934. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  935. RS_EBP:
  936. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  937. RS_ESI:
  938. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  939. RS_EDI:
  940. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  941. else
  942. ;
  943. end;
  944. end;
  945. if result then
  946. exit;
  947. end
  948. else if getregtype(reg)=R_MMREGISTER then
  949. begin
  950. case getsupreg(reg) of
  951. RS_XMM0:
  952. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  953. else
  954. ;
  955. end;
  956. if result then
  957. exit;
  958. end
  959. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  960. begin
  961. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  962. exit(true);
  963. case getsubreg(reg) of
  964. R_SUBFLAGCARRY:
  965. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  966. R_SUBFLAGPARITY:
  967. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  968. R_SUBFLAGAUXILIARY:
  969. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  970. R_SUBFLAGZERO:
  971. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  972. R_SUBFLAGSIGN:
  973. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  974. R_SUBFLAGOVERFLOW:
  975. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  976. R_SUBFLAGINTERRUPT:
  977. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  978. R_SUBFLAGDIRECTION:
  979. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  980. R_SUBW,R_SUBD,R_SUBQ:
  981. { Everything except the direction bits }
  982. Result:=
  983. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  984. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  985. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  986. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  987. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  988. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  989. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  990. else
  991. ;
  992. end;
  993. if result then
  994. exit;
  995. end
  996. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  997. exit(true);
  998. Result:=inherited RegInInstruction(Reg, p1);
  999. end;
  1000. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1001. const
  1002. WriteOps: array[0..3] of set of TInsChange =
  1003. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1004. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1005. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1006. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1007. var
  1008. OperIdx: Integer;
  1009. begin
  1010. Result := False;
  1011. if p1.typ <> ait_instruction then
  1012. exit;
  1013. with insprop[taicpu(p1).opcode] do
  1014. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1015. begin
  1016. case getsubreg(reg) of
  1017. R_SUBW,R_SUBD,R_SUBQ:
  1018. Result :=
  1019. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1020. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1021. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1022. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1023. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1024. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1025. R_SUBFLAGCARRY:
  1026. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1027. R_SUBFLAGPARITY:
  1028. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1029. R_SUBFLAGAUXILIARY:
  1030. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1031. R_SUBFLAGZERO:
  1032. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1033. R_SUBFLAGSIGN:
  1034. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1035. R_SUBFLAGOVERFLOW:
  1036. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1037. R_SUBFLAGINTERRUPT:
  1038. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1039. R_SUBFLAGDIRECTION:
  1040. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1041. else
  1042. internalerror(2017042602);
  1043. end;
  1044. exit;
  1045. end;
  1046. case taicpu(p1).opcode of
  1047. A_CALL:
  1048. { We could potentially set Result to False if the register in
  1049. question is non-volatile for the subroutine's calling convention,
  1050. but this would require detecting the calling convention in use and
  1051. also assuming that the routine doesn't contain malformed assembly
  1052. language, for example... so it could only be done under -O4 as it
  1053. would be considered a side-effect. [Kit] }
  1054. Result := True;
  1055. A_MOVSD:
  1056. { special handling for SSE MOVSD }
  1057. if (taicpu(p1).ops>0) then
  1058. begin
  1059. if taicpu(p1).ops<>2 then
  1060. internalerror(2017042703);
  1061. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1062. end;
  1063. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1064. so fix it here (FK)
  1065. }
  1066. A_VMOVSS,
  1067. A_VMOVSD:
  1068. begin
  1069. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1070. exit;
  1071. end;
  1072. A_MUL, A_DIV, A_IDIV:
  1073. begin
  1074. if taicpu(p1).opsize = S_B then
  1075. Result := (getsupreg(Reg) = RS_EAX)
  1076. else
  1077. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1078. end;
  1079. A_IMUL:
  1080. begin
  1081. if taicpu(p1).ops = 1 then
  1082. begin
  1083. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1084. end
  1085. else
  1086. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1087. Exit;
  1088. end;
  1089. else
  1090. ;
  1091. end;
  1092. if Result then
  1093. exit;
  1094. with insprop[taicpu(p1).opcode] do
  1095. begin
  1096. if getregtype(reg)=R_INTREGISTER then
  1097. begin
  1098. case getsupreg(reg) of
  1099. RS_EAX:
  1100. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1101. begin
  1102. Result := True;
  1103. exit
  1104. end;
  1105. RS_ECX:
  1106. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1107. begin
  1108. Result := True;
  1109. exit
  1110. end;
  1111. RS_EDX:
  1112. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1113. begin
  1114. Result := True;
  1115. exit
  1116. end;
  1117. RS_EBX:
  1118. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1119. begin
  1120. Result := True;
  1121. exit
  1122. end;
  1123. RS_ESP:
  1124. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1125. begin
  1126. Result := True;
  1127. exit
  1128. end;
  1129. RS_EBP:
  1130. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1131. begin
  1132. Result := True;
  1133. exit
  1134. end;
  1135. RS_ESI:
  1136. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1137. begin
  1138. Result := True;
  1139. exit
  1140. end;
  1141. RS_EDI:
  1142. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1143. begin
  1144. Result := True;
  1145. exit
  1146. end;
  1147. end;
  1148. end;
  1149. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1150. if (WriteOps[OperIdx]*Ch<>[]) and
  1151. { The register doesn't get modified inside a reference }
  1152. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1153. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1154. begin
  1155. Result := true;
  1156. exit
  1157. end;
  1158. end;
  1159. end;
  1160. {$ifdef DEBUG_AOPTCPU}
  1161. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1162. begin
  1163. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1164. end;
  1165. function debug_tostr(i: tcgint): string; inline;
  1166. begin
  1167. Result := tostr(i);
  1168. end;
  1169. function debug_hexstr(i: tcgint): string;
  1170. begin
  1171. Result := '0x';
  1172. case i of
  1173. 0..$FF:
  1174. Result := Result + hexstr(i, 2);
  1175. $100..$FFFF:
  1176. Result := Result + hexstr(i, 4);
  1177. $10000..$FFFFFF:
  1178. Result := Result + hexstr(i, 6);
  1179. $1000000..$FFFFFFFF:
  1180. Result := Result + hexstr(i, 8);
  1181. else
  1182. Result := Result + hexstr(i, 16);
  1183. end;
  1184. end;
  1185. function debug_regname(r: TRegister): string; inline;
  1186. begin
  1187. Result := '%' + std_regname(r);
  1188. end;
  1189. { Debug output function - creates a string representation of an operator }
  1190. function debug_operstr(oper: TOper): string;
  1191. begin
  1192. case oper.typ of
  1193. top_const:
  1194. Result := '$' + debug_tostr(oper.val);
  1195. top_reg:
  1196. Result := debug_regname(oper.reg);
  1197. top_ref:
  1198. begin
  1199. if oper.ref^.offset <> 0 then
  1200. Result := debug_tostr(oper.ref^.offset) + '('
  1201. else
  1202. Result := '(';
  1203. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1204. begin
  1205. Result := Result + debug_regname(oper.ref^.base);
  1206. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1207. Result := Result + ',' + debug_regname(oper.ref^.index);
  1208. end
  1209. else
  1210. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1211. Result := Result + debug_regname(oper.ref^.index);
  1212. if (oper.ref^.scalefactor > 1) then
  1213. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1214. else
  1215. Result := Result + ')';
  1216. end;
  1217. else
  1218. Result := '[UNKNOWN]';
  1219. end;
  1220. end;
  1221. function debug_op2str(opcode: tasmop): string; inline;
  1222. begin
  1223. Result := std_op2str[opcode];
  1224. end;
  1225. function debug_opsize2str(opsize: topsize): string; inline;
  1226. begin
  1227. Result := gas_opsize2str[opsize];
  1228. end;
  1229. {$else DEBUG_AOPTCPU}
  1230. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1231. begin
  1232. end;
  1233. function debug_tostr(i: tcgint): string; inline;
  1234. begin
  1235. Result := '';
  1236. end;
  1237. function debug_hexstr(i: tcgint): string; inline;
  1238. begin
  1239. Result := '';
  1240. end;
  1241. function debug_regname(r: TRegister): string; inline;
  1242. begin
  1243. Result := '';
  1244. end;
  1245. function debug_operstr(oper: TOper): string; inline;
  1246. begin
  1247. Result := '';
  1248. end;
  1249. function debug_op2str(opcode: tasmop): string; inline;
  1250. begin
  1251. Result := '';
  1252. end;
  1253. function debug_opsize2str(opsize: topsize): string; inline;
  1254. begin
  1255. Result := '';
  1256. end;
  1257. {$endif DEBUG_AOPTCPU}
  1258. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1259. begin
  1260. {$ifdef x86_64}
  1261. { Always fine on x86-64 }
  1262. Result := True;
  1263. {$else x86_64}
  1264. Result :=
  1265. {$ifdef i8086}
  1266. (current_settings.cputype >= cpu_386) and
  1267. {$endif i8086}
  1268. (
  1269. { Always accept if optimising for size }
  1270. (cs_opt_size in current_settings.optimizerswitches) or
  1271. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1272. (current_settings.optimizecputype >= cpu_Pentium2)
  1273. );
  1274. {$endif x86_64}
  1275. end;
  1276. { Attempts to allocate a volatile integer register for use between p and hp,
  1277. using AUsedRegs for the current register usage information. Returns NR_NO
  1278. if no free register could be found }
  1279. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1280. var
  1281. RegSet: TCPURegisterSet;
  1282. CurrentSuperReg: Integer;
  1283. CurrentReg: TRegister;
  1284. Currentp: tai;
  1285. Breakout: Boolean;
  1286. begin
  1287. Result := NR_NO;
  1288. RegSet :=
  1289. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1290. current_procinfo.saved_regs_int;
  1291. (*
  1292. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1293. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1294. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1295. *)
  1296. for CurrentSuperReg in RegSet do
  1297. begin
  1298. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1299. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1300. {$if defined(i386) or defined(i8086)}
  1301. { If the target size is 8-bit, make sure we can actually encode it }
  1302. and (
  1303. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1304. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1305. )
  1306. {$endif i386 or i8086}
  1307. then
  1308. begin
  1309. Currentp := p;
  1310. Breakout := False;
  1311. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1312. begin
  1313. case Currentp.typ of
  1314. ait_instruction:
  1315. begin
  1316. if RegInInstruction(CurrentReg, Currentp) then
  1317. begin
  1318. Breakout := True;
  1319. Break;
  1320. end;
  1321. { Cannot allocate across an unconditional jump }
  1322. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1323. Exit;
  1324. end;
  1325. ait_marker:
  1326. { Don't try anything more if a marker is hit }
  1327. Exit;
  1328. ait_regalloc:
  1329. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1330. begin
  1331. Breakout := True;
  1332. Break;
  1333. end;
  1334. else
  1335. ;
  1336. end;
  1337. end;
  1338. if Breakout then
  1339. { Try the next register }
  1340. Continue;
  1341. { We have a free register available }
  1342. Result := CurrentReg;
  1343. if not DontAlloc then
  1344. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1345. Exit;
  1346. end;
  1347. end;
  1348. end;
  1349. { Attempts to allocate a volatile MM register for use between p and hp,
  1350. using AUsedRegs for the current register usage information. Returns NR_NO
  1351. if no free register could be found }
  1352. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1353. var
  1354. RegSet: TCPURegisterSet;
  1355. CurrentSuperReg: Integer;
  1356. CurrentReg: TRegister;
  1357. Currentp: tai;
  1358. Breakout: Boolean;
  1359. begin
  1360. Result := NR_NO;
  1361. RegSet :=
  1362. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1363. current_procinfo.saved_regs_mm;
  1364. for CurrentSuperReg in RegSet do
  1365. begin
  1366. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1367. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1368. begin
  1369. Currentp := p;
  1370. Breakout := False;
  1371. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1372. begin
  1373. case Currentp.typ of
  1374. ait_instruction:
  1375. begin
  1376. if RegInInstruction(CurrentReg, Currentp) then
  1377. begin
  1378. Breakout := True;
  1379. Break;
  1380. end;
  1381. { Cannot allocate across an unconditional jump }
  1382. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1383. Exit;
  1384. end;
  1385. ait_marker:
  1386. { Don't try anything more if a marker is hit }
  1387. Exit;
  1388. ait_regalloc:
  1389. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1390. begin
  1391. Breakout := True;
  1392. Break;
  1393. end;
  1394. else
  1395. ;
  1396. end;
  1397. end;
  1398. if Breakout then
  1399. { Try the next register }
  1400. Continue;
  1401. { We have a free register available }
  1402. Result := CurrentReg;
  1403. if not DontAlloc then
  1404. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1405. Exit;
  1406. end;
  1407. end;
  1408. end;
  1409. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1410. begin
  1411. if not SuperRegistersEqual(reg1,reg2) then
  1412. exit(false);
  1413. if getregtype(reg1)<>R_INTREGISTER then
  1414. exit(true); {because SuperRegisterEqual is true}
  1415. case getsubreg(reg1) of
  1416. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1417. higher, it preserves the high bits, so the new value depends on
  1418. reg2's previous value. In other words, it is equivalent to doing:
  1419. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1420. R_SUBL:
  1421. exit(getsubreg(reg2)=R_SUBL);
  1422. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1423. higher, it actually does a:
  1424. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1425. R_SUBH:
  1426. exit(getsubreg(reg2)=R_SUBH);
  1427. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1428. bits of reg2:
  1429. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1430. R_SUBW:
  1431. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1432. { a write to R_SUBD always overwrites every other subregister,
  1433. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1434. R_SUBD,
  1435. R_SUBQ:
  1436. exit(true);
  1437. else
  1438. internalerror(2017042801);
  1439. end;
  1440. end;
  1441. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1442. begin
  1443. if not SuperRegistersEqual(reg1,reg2) then
  1444. exit(false);
  1445. if getregtype(reg1)<>R_INTREGISTER then
  1446. exit(true); {because SuperRegisterEqual is true}
  1447. case getsubreg(reg1) of
  1448. R_SUBL:
  1449. exit(getsubreg(reg2)<>R_SUBH);
  1450. R_SUBH:
  1451. exit(getsubreg(reg2)<>R_SUBL);
  1452. R_SUBW,
  1453. R_SUBD,
  1454. R_SUBQ:
  1455. exit(true);
  1456. else
  1457. internalerror(2017042802);
  1458. end;
  1459. end;
  1460. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1461. var
  1462. hp1 : tai;
  1463. l : TCGInt;
  1464. begin
  1465. result:=false;
  1466. if not(GetNextInstruction(p, hp1)) then
  1467. exit;
  1468. { changes the code sequence
  1469. shr/sar const1, x
  1470. shl const2, x
  1471. to
  1472. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1473. if (taicpu(p).oper[0]^.typ = top_const) and
  1474. MatchInstruction(hp1,A_SHL,[]) and
  1475. (taicpu(hp1).oper[0]^.typ = top_const) and
  1476. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1477. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1478. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1479. begin
  1480. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1481. not(cs_opt_size in current_settings.optimizerswitches) then
  1482. begin
  1483. { shr/sar const1, %reg
  1484. shl const2, %reg
  1485. with const1 > const2 }
  1486. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1487. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1488. taicpu(hp1).opcode := A_AND;
  1489. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1490. case taicpu(p).opsize Of
  1491. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1492. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1493. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1494. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1495. else
  1496. Internalerror(2017050703)
  1497. end;
  1498. end
  1499. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1500. not(cs_opt_size in current_settings.optimizerswitches) then
  1501. begin
  1502. { shr/sar const1, %reg
  1503. shl const2, %reg
  1504. with const1 < const2 }
  1505. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1506. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1507. taicpu(p).opcode := A_AND;
  1508. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1509. case taicpu(p).opsize Of
  1510. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1511. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1512. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1513. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1514. else
  1515. Internalerror(2017050702)
  1516. end;
  1517. end
  1518. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1519. begin
  1520. { shr/sar const1, %reg
  1521. shl const2, %reg
  1522. with const1 = const2 }
  1523. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1524. taicpu(p).opcode := A_AND;
  1525. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1526. case taicpu(p).opsize Of
  1527. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1528. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1529. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1530. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1531. else
  1532. Internalerror(2017050701)
  1533. end;
  1534. RemoveInstruction(hp1);
  1535. end;
  1536. end;
  1537. end;
  1538. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1539. var
  1540. opsize : topsize;
  1541. hp1, hp2 : tai;
  1542. tmpref : treference;
  1543. ShiftValue : Cardinal;
  1544. BaseValue : TCGInt;
  1545. begin
  1546. result:=false;
  1547. opsize:=taicpu(p).opsize;
  1548. { changes certain "imul const, %reg"'s to lea sequences }
  1549. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1550. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1551. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1552. if (taicpu(p).oper[0]^.val = 1) then
  1553. if (taicpu(p).ops = 2) then
  1554. { remove "imul $1, reg" }
  1555. begin
  1556. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1557. Result := RemoveCurrentP(p);
  1558. end
  1559. else
  1560. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1561. begin
  1562. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1563. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1564. asml.InsertAfter(hp1, p);
  1565. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1566. RemoveCurrentP(p, hp1);
  1567. Result := True;
  1568. end
  1569. else if ((taicpu(p).ops <= 2) or
  1570. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1571. not(cs_opt_size in current_settings.optimizerswitches) and
  1572. (not(GetNextInstruction(p, hp1)) or
  1573. not((tai(hp1).typ = ait_instruction) and
  1574. ((taicpu(hp1).opcode=A_Jcc) and
  1575. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1576. begin
  1577. {
  1578. imul X, reg1, reg2 to
  1579. lea (reg1,reg1,Y), reg2
  1580. shl ZZ,reg2
  1581. imul XX, reg1 to
  1582. lea (reg1,reg1,YY), reg1
  1583. shl ZZ,reg2
  1584. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1585. it does not exist as a separate optimization target in FPC though.
  1586. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1587. at most two zeros
  1588. }
  1589. reference_reset(tmpref,1,[]);
  1590. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1591. begin
  1592. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1593. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1594. TmpRef.base := taicpu(p).oper[1]^.reg;
  1595. TmpRef.index := taicpu(p).oper[1]^.reg;
  1596. if not(BaseValue in [3,5,9]) then
  1597. Internalerror(2018110101);
  1598. TmpRef.ScaleFactor := BaseValue-1;
  1599. if (taicpu(p).ops = 2) then
  1600. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1601. else
  1602. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1603. AsmL.InsertAfter(hp1,p);
  1604. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1605. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1606. RemoveCurrentP(p, hp1);
  1607. if ShiftValue>0 then
  1608. begin
  1609. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1610. AsmL.InsertAfter(hp2,hp1);
  1611. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1612. end;
  1613. Result := True;
  1614. end;
  1615. end;
  1616. end;
  1617. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1618. begin
  1619. Result := False;
  1620. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1621. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1622. begin
  1623. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1624. taicpu(p).opcode := A_MOV;
  1625. Result := True;
  1626. end;
  1627. end;
  1628. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1629. var
  1630. p: taicpu absolute hp; { Implicit typecast }
  1631. i: Integer;
  1632. begin
  1633. Result := False;
  1634. if not assigned(hp) or
  1635. (hp.typ <> ait_instruction) then
  1636. Exit;
  1637. Prefetch(insprop[p.opcode]);
  1638. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1639. with insprop[p.opcode] do
  1640. begin
  1641. case getsubreg(reg) of
  1642. R_SUBW,R_SUBD,R_SUBQ:
  1643. Result:=
  1644. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1645. uncommon flags are checked first }
  1646. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1647. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1648. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1649. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1650. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1651. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1652. R_SUBFLAGCARRY:
  1653. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1654. R_SUBFLAGPARITY:
  1655. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1656. R_SUBFLAGAUXILIARY:
  1657. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1658. R_SUBFLAGZERO:
  1659. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1660. R_SUBFLAGSIGN:
  1661. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1662. R_SUBFLAGOVERFLOW:
  1663. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1664. R_SUBFLAGINTERRUPT:
  1665. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1666. R_SUBFLAGDIRECTION:
  1667. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1668. else
  1669. internalerror(2017050501);
  1670. end;
  1671. exit;
  1672. end;
  1673. { Handle special cases first }
  1674. case p.opcode of
  1675. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1676. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1677. begin
  1678. Result :=
  1679. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1680. (p.oper[1]^.typ = top_reg) and
  1681. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1682. (
  1683. (p.oper[0]^.typ = top_const) or
  1684. (
  1685. (p.oper[0]^.typ = top_reg) and
  1686. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1687. ) or (
  1688. (p.oper[0]^.typ = top_ref) and
  1689. not RegInRef(reg,p.oper[0]^.ref^)
  1690. )
  1691. );
  1692. end;
  1693. A_MUL, A_IMUL:
  1694. Result :=
  1695. (
  1696. (p.ops=3) and { IMUL only }
  1697. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1698. (
  1699. (
  1700. (p.oper[1]^.typ=top_reg) and
  1701. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1702. ) or (
  1703. (p.oper[1]^.typ=top_ref) and
  1704. not RegInRef(reg,p.oper[1]^.ref^)
  1705. )
  1706. )
  1707. ) or (
  1708. (
  1709. (p.ops=1) and
  1710. (
  1711. (
  1712. (
  1713. (p.oper[0]^.typ=top_reg) and
  1714. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1715. )
  1716. ) or (
  1717. (p.oper[0]^.typ=top_ref) and
  1718. not RegInRef(reg,p.oper[0]^.ref^)
  1719. )
  1720. ) and (
  1721. (
  1722. (p.opsize=S_B) and
  1723. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1724. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1725. ) or (
  1726. (p.opsize=S_W) and
  1727. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1728. ) or (
  1729. (p.opsize=S_L) and
  1730. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1731. {$ifdef x86_64}
  1732. ) or (
  1733. (p.opsize=S_Q) and
  1734. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1735. {$endif x86_64}
  1736. )
  1737. )
  1738. )
  1739. );
  1740. A_CBW:
  1741. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1742. {$ifndef x86_64}
  1743. A_LDS:
  1744. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1745. A_LES:
  1746. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1747. {$endif not x86_64}
  1748. A_LFS:
  1749. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1750. A_LGS:
  1751. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1752. A_LSS:
  1753. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1754. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1755. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1756. A_LODSB:
  1757. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1758. A_LODSW:
  1759. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1760. {$ifdef x86_64}
  1761. A_LODSQ:
  1762. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1763. {$endif x86_64}
  1764. A_LODSD:
  1765. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1766. A_FSTSW, A_FNSTSW:
  1767. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1768. else
  1769. begin
  1770. with insprop[p.opcode] do
  1771. begin
  1772. if (
  1773. { xor %reg,%reg etc. is classed as a new value }
  1774. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1775. MatchOpType(p, top_reg, top_reg) and
  1776. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1777. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1778. ) then
  1779. begin
  1780. Result := True;
  1781. Exit;
  1782. end;
  1783. { Make sure the entire register is overwritten }
  1784. if (getregtype(reg) = R_INTREGISTER) then
  1785. begin
  1786. if (p.ops > 0) then
  1787. begin
  1788. if RegInOp(reg, p.oper[0]^) then
  1789. begin
  1790. if (p.oper[0]^.typ = top_ref) then
  1791. begin
  1792. if RegInRef(reg, p.oper[0]^.ref^) then
  1793. begin
  1794. Result := False;
  1795. Exit;
  1796. end;
  1797. end
  1798. else if (p.oper[0]^.typ = top_reg) then
  1799. begin
  1800. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1801. begin
  1802. Result := False;
  1803. Exit;
  1804. end
  1805. else if ([Ch_WOp1]*Ch<>[]) then
  1806. begin
  1807. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1808. Result := True
  1809. else
  1810. begin
  1811. Result := False;
  1812. Exit;
  1813. end;
  1814. end;
  1815. end;
  1816. end;
  1817. if (p.ops > 1) then
  1818. begin
  1819. if RegInOp(reg, p.oper[1]^) then
  1820. begin
  1821. if (p.oper[1]^.typ = top_ref) then
  1822. begin
  1823. if RegInRef(reg, p.oper[1]^.ref^) then
  1824. begin
  1825. Result := False;
  1826. Exit;
  1827. end;
  1828. end
  1829. else if (p.oper[1]^.typ = top_reg) then
  1830. begin
  1831. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1832. begin
  1833. Result := False;
  1834. Exit;
  1835. end
  1836. else if ([Ch_WOp2]*Ch<>[]) then
  1837. begin
  1838. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1839. Result := True
  1840. else
  1841. begin
  1842. Result := False;
  1843. Exit;
  1844. end;
  1845. end;
  1846. end;
  1847. end;
  1848. if (p.ops > 2) then
  1849. begin
  1850. if RegInOp(reg, p.oper[2]^) then
  1851. begin
  1852. if (p.oper[2]^.typ = top_ref) then
  1853. begin
  1854. if RegInRef(reg, p.oper[2]^.ref^) then
  1855. begin
  1856. Result := False;
  1857. Exit;
  1858. end;
  1859. end
  1860. else if (p.oper[2]^.typ = top_reg) then
  1861. begin
  1862. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1863. begin
  1864. Result := False;
  1865. Exit;
  1866. end
  1867. else if ([Ch_WOp3]*Ch<>[]) then
  1868. begin
  1869. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1870. Result := True
  1871. else
  1872. begin
  1873. Result := False;
  1874. Exit;
  1875. end;
  1876. end;
  1877. end;
  1878. end;
  1879. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1880. begin
  1881. if (p.oper[3]^.typ = top_ref) then
  1882. begin
  1883. if RegInRef(reg, p.oper[3]^.ref^) then
  1884. begin
  1885. Result := False;
  1886. Exit;
  1887. end;
  1888. end
  1889. else if (p.oper[3]^.typ = top_reg) then
  1890. begin
  1891. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1892. begin
  1893. Result := False;
  1894. Exit;
  1895. end
  1896. else if ([Ch_WOp4]*Ch<>[]) then
  1897. begin
  1898. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1899. Result := True
  1900. else
  1901. begin
  1902. Result := False;
  1903. Exit;
  1904. end;
  1905. end;
  1906. end;
  1907. end;
  1908. end;
  1909. end;
  1910. end;
  1911. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1912. case getsupreg(reg) of
  1913. RS_EAX:
  1914. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1915. begin
  1916. Result := True;
  1917. Exit;
  1918. end;
  1919. RS_ECX:
  1920. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1921. begin
  1922. Result := True;
  1923. Exit;
  1924. end;
  1925. RS_EDX:
  1926. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1927. begin
  1928. Result := True;
  1929. Exit;
  1930. end;
  1931. RS_EBX:
  1932. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1933. begin
  1934. Result := True;
  1935. Exit;
  1936. end;
  1937. RS_ESP:
  1938. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1939. begin
  1940. Result := True;
  1941. Exit;
  1942. end;
  1943. RS_EBP:
  1944. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1945. begin
  1946. Result := True;
  1947. Exit;
  1948. end;
  1949. RS_ESI:
  1950. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1951. begin
  1952. Result := True;
  1953. Exit;
  1954. end;
  1955. RS_EDI:
  1956. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1957. begin
  1958. Result := True;
  1959. Exit;
  1960. end;
  1961. else
  1962. ;
  1963. end;
  1964. end;
  1965. end;
  1966. end;
  1967. end;
  1968. end;
  1969. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1970. var
  1971. hp2,hp3 : tai;
  1972. begin
  1973. { some x86-64 issue a NOP before the real exit code }
  1974. if MatchInstruction(p,A_NOP,[]) then
  1975. GetNextInstruction(p,p);
  1976. result:=assigned(p) and (p.typ=ait_instruction) and
  1977. ((taicpu(p).opcode = A_RET) or
  1978. ((taicpu(p).opcode=A_LEAVE) and
  1979. GetNextInstruction(p,hp2) and
  1980. MatchInstruction(hp2,A_RET,[S_NO])
  1981. ) or
  1982. (((taicpu(p).opcode=A_LEA) and
  1983. MatchOpType(taicpu(p),top_ref,top_reg) and
  1984. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1985. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1986. ) and
  1987. GetNextInstruction(p,hp2) and
  1988. MatchInstruction(hp2,A_RET,[S_NO])
  1989. ) or
  1990. ((((taicpu(p).opcode=A_MOV) and
  1991. MatchOpType(taicpu(p),top_reg,top_reg) and
  1992. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1993. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1994. ((taicpu(p).opcode=A_LEA) and
  1995. MatchOpType(taicpu(p),top_ref,top_reg) and
  1996. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1997. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1998. )
  1999. ) and
  2000. GetNextInstruction(p,hp2) and
  2001. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2002. MatchOpType(taicpu(hp2),top_reg) and
  2003. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2004. GetNextInstruction(hp2,hp3) and
  2005. MatchInstruction(hp3,A_RET,[S_NO])
  2006. )
  2007. );
  2008. end;
  2009. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2010. begin
  2011. isFoldableArithOp := False;
  2012. case hp1.opcode of
  2013. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2014. isFoldableArithOp :=
  2015. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2016. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2017. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2018. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2019. (taicpu(hp1).oper[1]^.reg = reg);
  2020. A_INC,A_DEC,A_NEG,A_NOT:
  2021. isFoldableArithOp :=
  2022. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2023. (taicpu(hp1).oper[0]^.reg = reg);
  2024. else
  2025. ;
  2026. end;
  2027. end;
  2028. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2029. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2030. var
  2031. hp2: tai;
  2032. begin
  2033. hp2 := p;
  2034. repeat
  2035. hp2 := tai(hp2.previous);
  2036. if assigned(hp2) and
  2037. (hp2.typ = ait_regalloc) and
  2038. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2039. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2040. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2041. begin
  2042. RemoveInstruction(hp2);
  2043. break;
  2044. end;
  2045. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2046. end;
  2047. begin
  2048. case current_procinfo.procdef.returndef.typ of
  2049. arraydef,recorddef,pointerdef,
  2050. stringdef,enumdef,procdef,objectdef,errordef,
  2051. filedef,setdef,procvardef,
  2052. classrefdef,forwarddef:
  2053. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2054. orddef:
  2055. if current_procinfo.procdef.returndef.size <> 0 then
  2056. begin
  2057. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2058. { for int64/qword }
  2059. if current_procinfo.procdef.returndef.size = 8 then
  2060. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2061. end;
  2062. else
  2063. ;
  2064. end;
  2065. end;
  2066. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2067. var
  2068. hp1,hp2 : tai;
  2069. begin
  2070. result:=false;
  2071. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2072. begin
  2073. { vmova* reg1,reg1
  2074. =>
  2075. <nop> }
  2076. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2077. begin
  2078. RemoveCurrentP(p);
  2079. result:=true;
  2080. exit;
  2081. end;
  2082. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2083. (hp1.typ = ait_instruction) and
  2084. (
  2085. { Under -O2 and below, the instructions are always adjacent }
  2086. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2087. (taicpu(hp1).ops <= 1) or
  2088. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2089. { If reg1 = reg3, reg1 must not be modified in between }
  2090. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2091. ) then
  2092. begin
  2093. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2094. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2095. begin
  2096. { vmova* reg1,reg2
  2097. ...
  2098. vmova* reg2,reg3
  2099. dealloc reg2
  2100. =>
  2101. vmova* reg1,reg3 }
  2102. TransferUsedRegs(TmpUsedRegs);
  2103. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2104. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2105. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2106. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2107. begin
  2108. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2109. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2110. TransferUsedRegs(TmpUsedRegs);
  2111. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2112. RemoveInstruction(hp1);
  2113. result:=true;
  2114. exit;
  2115. end;
  2116. { special case:
  2117. vmova* reg1,<op>
  2118. ...
  2119. vmova* <op>,reg1
  2120. =>
  2121. vmova* reg1,<op> }
  2122. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2123. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2124. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2125. ) then
  2126. begin
  2127. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2128. RemoveInstruction(hp1);
  2129. result:=true;
  2130. exit;
  2131. end
  2132. end
  2133. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2134. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2135. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2136. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2137. ) and
  2138. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2139. begin
  2140. { vmova* reg1,reg2
  2141. ...
  2142. vmovs* reg2,<op>
  2143. dealloc reg2
  2144. =>
  2145. vmovs* reg1,<op> }
  2146. TransferUsedRegs(TmpUsedRegs);
  2147. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2148. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2149. begin
  2150. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2151. taicpu(p).opcode:=taicpu(hp1).opcode;
  2152. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2153. TransferUsedRegs(TmpUsedRegs);
  2154. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2155. RemoveInstruction(hp1);
  2156. result:=true;
  2157. exit;
  2158. end
  2159. end;
  2160. if MatchInstruction(hp1,[A_VFMADDPD,
  2161. A_VFMADD132PD,
  2162. A_VFMADD132PS,
  2163. A_VFMADD132SD,
  2164. A_VFMADD132SS,
  2165. A_VFMADD213PD,
  2166. A_VFMADD213PS,
  2167. A_VFMADD213SD,
  2168. A_VFMADD213SS,
  2169. A_VFMADD231PD,
  2170. A_VFMADD231PS,
  2171. A_VFMADD231SD,
  2172. A_VFMADD231SS,
  2173. A_VFMADDSUB132PD,
  2174. A_VFMADDSUB132PS,
  2175. A_VFMADDSUB213PD,
  2176. A_VFMADDSUB213PS,
  2177. A_VFMADDSUB231PD,
  2178. A_VFMADDSUB231PS,
  2179. A_VFMSUB132PD,
  2180. A_VFMSUB132PS,
  2181. A_VFMSUB132SD,
  2182. A_VFMSUB132SS,
  2183. A_VFMSUB213PD,
  2184. A_VFMSUB213PS,
  2185. A_VFMSUB213SD,
  2186. A_VFMSUB213SS,
  2187. A_VFMSUB231PD,
  2188. A_VFMSUB231PS,
  2189. A_VFMSUB231SD,
  2190. A_VFMSUB231SS,
  2191. A_VFMSUBADD132PD,
  2192. A_VFMSUBADD132PS,
  2193. A_VFMSUBADD213PD,
  2194. A_VFMSUBADD213PS,
  2195. A_VFMSUBADD231PD,
  2196. A_VFMSUBADD231PS,
  2197. A_VFNMADD132PD,
  2198. A_VFNMADD132PS,
  2199. A_VFNMADD132SD,
  2200. A_VFNMADD132SS,
  2201. A_VFNMADD213PD,
  2202. A_VFNMADD213PS,
  2203. A_VFNMADD213SD,
  2204. A_VFNMADD213SS,
  2205. A_VFNMADD231PD,
  2206. A_VFNMADD231PS,
  2207. A_VFNMADD231SD,
  2208. A_VFNMADD231SS,
  2209. A_VFNMSUB132PD,
  2210. A_VFNMSUB132PS,
  2211. A_VFNMSUB132SD,
  2212. A_VFNMSUB132SS,
  2213. A_VFNMSUB213PD,
  2214. A_VFNMSUB213PS,
  2215. A_VFNMSUB213SD,
  2216. A_VFNMSUB213SS,
  2217. A_VFNMSUB231PD,
  2218. A_VFNMSUB231PS,
  2219. A_VFNMSUB231SD,
  2220. A_VFNMSUB231SS],[S_NO]) and
  2221. { we mix single and double opperations here because we assume that the compiler
  2222. generates vmovapd only after double operations and vmovaps only after single operations }
  2223. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2224. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2225. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2226. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2227. begin
  2228. TransferUsedRegs(TmpUsedRegs);
  2229. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2230. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2231. begin
  2232. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2233. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2234. RemoveCurrentP(p)
  2235. else
  2236. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2237. RemoveInstruction(hp2);
  2238. end;
  2239. end
  2240. else if (hp1.typ = ait_instruction) and
  2241. (((taicpu(p).opcode=A_MOVAPS) and
  2242. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2243. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2244. ((taicpu(p).opcode=A_MOVAPD) and
  2245. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2246. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2247. ) and
  2248. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2249. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2250. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2251. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2252. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2253. { change
  2254. movapX reg,reg2
  2255. addsX/subsX/... reg3, reg2
  2256. movapX reg2,reg
  2257. to
  2258. addsX/subsX/... reg3,reg
  2259. }
  2260. begin
  2261. TransferUsedRegs(TmpUsedRegs);
  2262. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2263. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2264. begin
  2265. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2266. debug_op2str(taicpu(p).opcode)+' '+
  2267. debug_op2str(taicpu(hp1).opcode)+' '+
  2268. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2269. { we cannot eliminate the first move if
  2270. the operations uses the same register for source and dest }
  2271. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2272. { Remember that hp1 is not necessarily the immediate
  2273. next instruction }
  2274. RemoveCurrentP(p);
  2275. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2276. RemoveInstruction(hp2);
  2277. result:=true;
  2278. end;
  2279. end
  2280. else if (hp1.typ = ait_instruction) and
  2281. (((taicpu(p).opcode=A_VMOVAPD) and
  2282. (taicpu(hp1).opcode=A_VCOMISD)) or
  2283. ((taicpu(p).opcode=A_VMOVAPS) and
  2284. ((taicpu(hp1).opcode=A_VCOMISS))
  2285. )
  2286. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2287. { change
  2288. movapX reg,reg1
  2289. vcomisX reg1,reg1
  2290. to
  2291. vcomisX reg,reg
  2292. }
  2293. begin
  2294. TransferUsedRegs(TmpUsedRegs);
  2295. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2296. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2297. begin
  2298. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2299. debug_op2str(taicpu(p).opcode)+' '+
  2300. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2301. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2302. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2303. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2304. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2305. RemoveCurrentP(p);
  2306. result:=true;
  2307. exit;
  2308. end;
  2309. end
  2310. end;
  2311. end;
  2312. end;
  2313. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2314. var
  2315. hp1 : tai;
  2316. begin
  2317. result:=false;
  2318. { replace
  2319. V<Op>X %mreg1,%mreg2,%mreg3
  2320. VMovX %mreg3,%mreg4
  2321. dealloc %mreg3
  2322. by
  2323. V<Op>X %mreg1,%mreg2,%mreg4
  2324. ?
  2325. }
  2326. if GetNextInstruction(p,hp1) and
  2327. { we mix single and double operations here because we assume that the compiler
  2328. generates vmovapd only after double operations and vmovaps only after single operations }
  2329. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2330. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2331. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2332. begin
  2333. TransferUsedRegs(TmpUsedRegs);
  2334. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2335. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2336. begin
  2337. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2338. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2339. RemoveInstruction(hp1);
  2340. result:=true;
  2341. end;
  2342. end;
  2343. end;
  2344. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2345. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2346. begin
  2347. Result := False;
  2348. { For safety reasons, only check for exact register matches }
  2349. { Check base register }
  2350. if (ref.base = AOldReg) then
  2351. begin
  2352. ref.base := ANewReg;
  2353. Result := True;
  2354. end;
  2355. { Check index register }
  2356. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2357. begin
  2358. ref.index := ANewReg;
  2359. Result := True;
  2360. end;
  2361. end;
  2362. { Replaces all references to AOldReg in an operand to ANewReg }
  2363. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2364. var
  2365. OldSupReg, NewSupReg: TSuperRegister;
  2366. OldSubReg, NewSubReg: TSubRegister;
  2367. OldRegType: TRegisterType;
  2368. ThisOper: POper;
  2369. begin
  2370. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2371. Result := False;
  2372. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2373. InternalError(2020011801);
  2374. OldSupReg := getsupreg(AOldReg);
  2375. OldSubReg := getsubreg(AOldReg);
  2376. OldRegType := getregtype(AOldReg);
  2377. NewSupReg := getsupreg(ANewReg);
  2378. NewSubReg := getsubreg(ANewReg);
  2379. if OldRegType <> getregtype(ANewReg) then
  2380. InternalError(2020011802);
  2381. if OldSubReg <> NewSubReg then
  2382. InternalError(2020011803);
  2383. case ThisOper^.typ of
  2384. top_reg:
  2385. if (
  2386. (ThisOper^.reg = AOldReg) or
  2387. (
  2388. (OldRegType = R_INTREGISTER) and
  2389. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2390. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2391. (
  2392. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2393. {$ifndef x86_64}
  2394. and (
  2395. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2396. don't have an 8-bit representation }
  2397. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2398. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2399. )
  2400. {$endif x86_64}
  2401. )
  2402. )
  2403. ) then
  2404. begin
  2405. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2406. Result := True;
  2407. end;
  2408. top_ref:
  2409. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2410. Result := True;
  2411. else
  2412. ;
  2413. end;
  2414. end;
  2415. { Replaces all references to AOldReg in an instruction to ANewReg }
  2416. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2417. const
  2418. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2419. var
  2420. OperIdx: Integer;
  2421. begin
  2422. Result := False;
  2423. for OperIdx := 0 to p.ops - 1 do
  2424. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2425. begin
  2426. { The shift and rotate instructions can only use CL }
  2427. if not (
  2428. (OperIdx = 0) and
  2429. { This second condition just helps to avoid unnecessarily
  2430. calling MatchInstruction for 10 different opcodes }
  2431. (p.oper[0]^.reg = NR_CL) and
  2432. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2433. ) then
  2434. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2435. end
  2436. else if p.oper[OperIdx]^.typ = top_ref then
  2437. { It's okay to replace registers in references that get written to }
  2438. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2439. end;
  2440. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2441. begin
  2442. Result :=
  2443. (ref^.index = NR_NO) and
  2444. (
  2445. {$ifdef x86_64}
  2446. (
  2447. (ref^.base = NR_RIP) and
  2448. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2449. ) or
  2450. {$endif x86_64}
  2451. (ref^.refaddr = addr_full) or
  2452. (ref^.base = NR_STACK_POINTER_REG) or
  2453. (ref^.base = current_procinfo.framepointer)
  2454. );
  2455. end;
  2456. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2457. var
  2458. l: asizeint;
  2459. begin
  2460. Result := False;
  2461. { Should have been checked previously }
  2462. if p.opcode <> A_LEA then
  2463. InternalError(2020072501);
  2464. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2465. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2466. not(cs_opt_size in current_settings.optimizerswitches) then
  2467. exit;
  2468. with p.oper[0]^.ref^ do
  2469. begin
  2470. if (base <> p.oper[1]^.reg) or
  2471. (index <> NR_NO) or
  2472. assigned(symbol) then
  2473. exit;
  2474. l:=offset;
  2475. if (l=1) and UseIncDec then
  2476. begin
  2477. p.opcode:=A_INC;
  2478. p.loadreg(0,p.oper[1]^.reg);
  2479. p.ops:=1;
  2480. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2481. end
  2482. else if (l=-1) and UseIncDec then
  2483. begin
  2484. p.opcode:=A_DEC;
  2485. p.loadreg(0,p.oper[1]^.reg);
  2486. p.ops:=1;
  2487. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2488. end
  2489. else
  2490. begin
  2491. if (l<0) and (l<>-2147483648) then
  2492. begin
  2493. p.opcode:=A_SUB;
  2494. p.loadConst(0,-l);
  2495. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2496. end
  2497. else
  2498. begin
  2499. p.opcode:=A_ADD;
  2500. p.loadConst(0,l);
  2501. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2502. end;
  2503. end;
  2504. end;
  2505. Result := True;
  2506. end;
  2507. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2508. var
  2509. CurrentReg, ReplaceReg: TRegister;
  2510. begin
  2511. Result := False;
  2512. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2513. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2514. case hp.opcode of
  2515. A_FSTSW, A_FNSTSW,
  2516. A_IN, A_INS, A_OUT, A_OUTS,
  2517. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2518. { These routines have explicit operands, but they are restricted in
  2519. what they can be (e.g. IN and OUT can only read from AL, AX or
  2520. EAX. }
  2521. Exit;
  2522. A_IMUL:
  2523. begin
  2524. { The 1-operand version writes to implicit registers
  2525. The 2-operand version reads from the first operator, and reads
  2526. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2527. the 3-operand version reads from a register that it doesn't write to
  2528. }
  2529. case hp.ops of
  2530. 1:
  2531. if (
  2532. (
  2533. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2534. ) or
  2535. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2536. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2537. begin
  2538. Result := True;
  2539. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2540. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2541. end;
  2542. 2:
  2543. { Only modify the first parameter }
  2544. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2545. begin
  2546. Result := True;
  2547. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2548. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2549. end;
  2550. 3:
  2551. { Only modify the second parameter }
  2552. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2553. begin
  2554. Result := True;
  2555. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2556. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2557. end;
  2558. else
  2559. InternalError(2020012901);
  2560. end;
  2561. end;
  2562. else
  2563. if (hp.ops > 0) and
  2564. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2565. begin
  2566. Result := True;
  2567. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2568. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2569. end;
  2570. end;
  2571. end;
  2572. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2573. var
  2574. hp2: tai;
  2575. p_SourceReg, p_TargetReg: TRegister;
  2576. begin
  2577. Result := False;
  2578. { Backward optimisation. If we have:
  2579. func. %reg1,%reg2
  2580. mov %reg2,%reg3
  2581. (dealloc %reg2)
  2582. Change to:
  2583. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2584. Perform similar optimisations with 1, 3 and 4-operand instructions
  2585. that only have one output.
  2586. }
  2587. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2588. begin
  2589. p_SourceReg := taicpu(p).oper[0]^.reg;
  2590. p_TargetReg := taicpu(p).oper[1]^.reg;
  2591. TransferUsedRegs(TmpUsedRegs);
  2592. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2593. GetLastInstruction(p, hp2) and
  2594. (hp2.typ = ait_instruction) and
  2595. { Have to make sure it's an instruction that only reads from
  2596. the first operands and only writes (not reads or modifies) to
  2597. the last one; in essence, a pure function such as BSR, POPCNT
  2598. or ANDN }
  2599. (
  2600. (
  2601. (taicpu(hp2).ops = 1) and
  2602. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2603. ) or
  2604. (
  2605. (taicpu(hp2).ops = 2) and
  2606. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2607. ) or
  2608. (
  2609. (taicpu(hp2).ops = 3) and
  2610. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2611. ) or
  2612. (
  2613. (taicpu(hp2).ops = 4) and
  2614. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2615. )
  2616. ) and
  2617. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2618. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2619. begin
  2620. case taicpu(hp2).opcode of
  2621. A_FSTSW, A_FNSTSW,
  2622. A_IN, A_INS, A_OUT, A_OUTS,
  2623. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2624. { These routines have explicit operands, but they are restricted in
  2625. what they can be (e.g. IN and OUT can only read from AL, AX or
  2626. EAX. }
  2627. ;
  2628. else
  2629. begin
  2630. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2631. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2632. if not RegInInstruction(p_TargetReg, hp2) then
  2633. begin
  2634. { Since we're allocating from an earlier point, we
  2635. need to remove the register from the tracking }
  2636. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2637. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2638. end;
  2639. RemoveCurrentp(p, hp1);
  2640. { If the Func was another MOV instruction, we might get
  2641. "mov %reg,%reg" that doesn't get removed in Pass 2
  2642. otherwise, so deal with it here (also do something
  2643. similar with lea (%reg),%reg}
  2644. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2645. begin
  2646. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2647. if p = hp2 then
  2648. RemoveCurrentp(p)
  2649. else
  2650. RemoveInstruction(hp2);
  2651. end;
  2652. Result := True;
  2653. Exit;
  2654. end;
  2655. end;
  2656. end;
  2657. end;
  2658. end;
  2659. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2660. begin
  2661. Result := False;
  2662. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2663. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2664. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2665. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2666. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2667. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2668. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2669. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2670. begin
  2671. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2672. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2673. Result := True;
  2674. end;
  2675. end;
  2676. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2677. var
  2678. hp1, hp2, hp3, hp4: tai;
  2679. DoOptimisation, TempBool: Boolean;
  2680. {$ifdef x86_64}
  2681. NewConst: TCGInt;
  2682. {$endif x86_64}
  2683. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2684. begin
  2685. if taicpu(hp1).opcode = signed_movop then
  2686. begin
  2687. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2688. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2689. end
  2690. else
  2691. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2692. end;
  2693. function TryConstMerge(var p1, p2: tai): Boolean;
  2694. var
  2695. ThisRef: TReference;
  2696. begin
  2697. Result := False;
  2698. ThisRef := taicpu(p2).oper[1]^.ref^;
  2699. { Only permit writes to the stack, since we can guarantee alignment with that }
  2700. if (ThisRef.index = NR_NO) and
  2701. (
  2702. (ThisRef.base = NR_STACK_POINTER_REG) or
  2703. (ThisRef.base = current_procinfo.framepointer)
  2704. ) then
  2705. begin
  2706. case taicpu(p).opsize of
  2707. S_B:
  2708. begin
  2709. { Word writes must be on a 2-byte boundary }
  2710. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2711. begin
  2712. { Reduce offset of second reference to see if it is sequential with the first }
  2713. Dec(ThisRef.offset, 1);
  2714. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2715. begin
  2716. { Make sure the constants aren't represented as a
  2717. negative number, as these won't merge properly }
  2718. taicpu(p1).opsize := S_W;
  2719. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2720. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2721. RemoveInstruction(p2);
  2722. Result := True;
  2723. end;
  2724. end;
  2725. end;
  2726. S_W:
  2727. begin
  2728. { Longword writes must be on a 4-byte boundary }
  2729. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2730. begin
  2731. { Reduce offset of second reference to see if it is sequential with the first }
  2732. Dec(ThisRef.offset, 2);
  2733. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2734. begin
  2735. { Make sure the constants aren't represented as a
  2736. negative number, as these won't merge properly }
  2737. taicpu(p1).opsize := S_L;
  2738. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2739. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2740. RemoveInstruction(p2);
  2741. Result := True;
  2742. end;
  2743. end;
  2744. end;
  2745. {$ifdef x86_64}
  2746. S_L:
  2747. begin
  2748. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2749. see if the constants can be encoded this way. }
  2750. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2751. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2752. { Quadword writes must be on an 8-byte boundary }
  2753. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2754. begin
  2755. { Reduce offset of second reference to see if it is sequential with the first }
  2756. Dec(ThisRef.offset, 4);
  2757. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2758. begin
  2759. { Make sure the constants aren't represented as a
  2760. negative number, as these won't merge properly }
  2761. taicpu(p1).opsize := S_Q;
  2762. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2763. taicpu(p1).oper[0]^.val := NewConst;
  2764. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2765. RemoveInstruction(p2);
  2766. Result := True;
  2767. end;
  2768. end;
  2769. end;
  2770. {$endif x86_64}
  2771. else
  2772. ;
  2773. end;
  2774. end;
  2775. end;
  2776. var
  2777. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2778. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2779. NewSize: topsize; NewOffset: asizeint;
  2780. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2781. SourceRef, TargetRef: TReference;
  2782. MovAligned, MovUnaligned: TAsmOp;
  2783. ThisRef: TReference;
  2784. JumpTracking: TLinkedList;
  2785. begin
  2786. Result:=false;
  2787. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2788. { remove mov reg1,reg1? }
  2789. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2790. then
  2791. begin
  2792. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2793. { take care of the register (de)allocs following p }
  2794. RemoveCurrentP(p, hp1);
  2795. Result:=true;
  2796. exit;
  2797. end;
  2798. { All the next optimisations require a next instruction }
  2799. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2800. Exit;
  2801. { Prevent compiler warnings }
  2802. p_TargetReg := NR_NO;
  2803. if taicpu(p).oper[1]^.typ = top_reg then
  2804. begin
  2805. { Saves on a large number of dereferences }
  2806. p_TargetReg := taicpu(p).oper[1]^.reg;
  2807. { Look for:
  2808. mov %reg1,%reg2
  2809. ??? %reg2,r/m
  2810. Change to:
  2811. mov %reg1,%reg2
  2812. ??? %reg1,r/m
  2813. }
  2814. if taicpu(p).oper[0]^.typ = top_reg then
  2815. begin
  2816. if RegReadByInstruction(p_TargetReg, hp1) and
  2817. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2818. begin
  2819. { A change has occurred, just not in p }
  2820. Result := True;
  2821. TransferUsedRegs(TmpUsedRegs);
  2822. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2823. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2824. { Just in case something didn't get modified (e.g. an
  2825. implicit register) }
  2826. not RegReadByInstruction(p_TargetReg, hp1) then
  2827. begin
  2828. { We can remove the original MOV }
  2829. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2830. RemoveCurrentp(p, hp1);
  2831. { UsedRegs got updated by RemoveCurrentp }
  2832. Result := True;
  2833. Exit;
  2834. end;
  2835. { If we know a MOV instruction has become a null operation, we might as well
  2836. get rid of it now to save time. }
  2837. if (taicpu(hp1).opcode = A_MOV) and
  2838. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2839. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2840. { Just being a register is enough to confirm it's a null operation }
  2841. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2842. begin
  2843. Result := True;
  2844. { Speed-up to reduce a pipeline stall... if we had something like...
  2845. movl %eax,%edx
  2846. movw %dx,%ax
  2847. ... the second instruction would change to movw %ax,%ax, but
  2848. given that it is now %ax that's active rather than %eax,
  2849. penalties might occur due to a partial register write, so instead,
  2850. change it to a MOVZX instruction when optimising for speed.
  2851. }
  2852. if not (cs_opt_size in current_settings.optimizerswitches) and
  2853. IsMOVZXAcceptable and
  2854. (taicpu(hp1).opsize < taicpu(p).opsize)
  2855. {$ifdef x86_64}
  2856. { operations already implicitly set the upper 64 bits to zero }
  2857. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2858. {$endif x86_64}
  2859. then
  2860. begin
  2861. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2862. case taicpu(p).opsize of
  2863. S_W:
  2864. if taicpu(hp1).opsize = S_B then
  2865. taicpu(hp1).opsize := S_BL
  2866. else
  2867. InternalError(2020012911);
  2868. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2869. case taicpu(hp1).opsize of
  2870. S_B:
  2871. taicpu(hp1).opsize := S_BL;
  2872. S_W:
  2873. taicpu(hp1).opsize := S_WL;
  2874. else
  2875. InternalError(2020012912);
  2876. end;
  2877. else
  2878. InternalError(2020012910);
  2879. end;
  2880. taicpu(hp1).opcode := A_MOVZX;
  2881. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2882. end
  2883. else
  2884. begin
  2885. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2886. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2887. RemoveInstruction(hp1);
  2888. { The instruction after what was hp1 is now the immediate next instruction,
  2889. so we can continue to make optimisations if it's present }
  2890. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2891. Exit;
  2892. hp1 := hp2;
  2893. end;
  2894. end;
  2895. end;
  2896. end;
  2897. end;
  2898. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2899. overwrites the original destination register. e.g.
  2900. movl ###,%reg2d
  2901. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2902. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2903. }
  2904. if (taicpu(p).oper[1]^.typ = top_reg) and
  2905. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2906. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2907. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2908. begin
  2909. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2910. begin
  2911. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2912. case taicpu(p).oper[0]^.typ of
  2913. top_const:
  2914. { We have something like:
  2915. movb $x, %regb
  2916. movzbl %regb,%regd
  2917. Change to:
  2918. movl $x, %regd
  2919. }
  2920. begin
  2921. case taicpu(hp1).opsize of
  2922. S_BW:
  2923. begin
  2924. convert_mov_value(A_MOVSX, $FF);
  2925. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2926. taicpu(p).opsize := S_W;
  2927. end;
  2928. S_BL:
  2929. begin
  2930. convert_mov_value(A_MOVSX, $FF);
  2931. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2932. taicpu(p).opsize := S_L;
  2933. end;
  2934. S_WL:
  2935. begin
  2936. convert_mov_value(A_MOVSX, $FFFF);
  2937. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2938. taicpu(p).opsize := S_L;
  2939. end;
  2940. {$ifdef x86_64}
  2941. S_BQ:
  2942. begin
  2943. convert_mov_value(A_MOVSX, $FF);
  2944. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2945. taicpu(p).opsize := S_Q;
  2946. end;
  2947. S_WQ:
  2948. begin
  2949. convert_mov_value(A_MOVSX, $FFFF);
  2950. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2951. taicpu(p).opsize := S_Q;
  2952. end;
  2953. S_LQ:
  2954. begin
  2955. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2956. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2957. taicpu(p).opsize := S_Q;
  2958. end;
  2959. {$endif x86_64}
  2960. else
  2961. { If hp1 was a MOV instruction, it should have been
  2962. optimised already }
  2963. InternalError(2020021001);
  2964. end;
  2965. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2966. RemoveInstruction(hp1);
  2967. Result := True;
  2968. Exit;
  2969. end;
  2970. top_ref:
  2971. begin
  2972. { We have something like:
  2973. movb mem, %regb
  2974. movzbl %regb,%regd
  2975. Change to:
  2976. movzbl mem, %regd
  2977. }
  2978. ThisRef := taicpu(p).oper[0]^.ref^;
  2979. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2980. begin
  2981. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2982. taicpu(hp1).loadref(0, ThisRef);
  2983. { Make sure any registers in the references are properly tracked }
  2984. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2985. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2986. if (ThisRef.index <> NR_NO) then
  2987. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2988. RemoveCurrentP(p, hp1);
  2989. Result := True;
  2990. Exit;
  2991. end;
  2992. end;
  2993. else
  2994. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2995. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2996. Exit;
  2997. end;
  2998. end
  2999. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3000. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3001. optimised }
  3002. else
  3003. begin
  3004. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3005. RemoveCurrentP(p, hp1);
  3006. Result := True;
  3007. Exit;
  3008. end;
  3009. end;
  3010. if (taicpu(hp1).opcode = A_AND) and
  3011. (taicpu(p).oper[1]^.typ = top_reg) and
  3012. MatchOpType(taicpu(hp1),top_const,top_reg) then
  3013. begin
  3014. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  3015. begin
  3016. case taicpu(p).opsize of
  3017. S_L:
  3018. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  3019. begin
  3020. { Optimize out:
  3021. mov x, %reg
  3022. and ffffffffh, %reg
  3023. }
  3024. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  3025. RemoveInstruction(hp1);
  3026. Result:=true;
  3027. exit;
  3028. end;
  3029. S_Q: { TODO: Confirm if this is even possible }
  3030. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  3031. begin
  3032. { Optimize out:
  3033. mov x, %reg
  3034. and ffffffffffffffffh, %reg
  3035. }
  3036. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  3037. RemoveInstruction(hp1);
  3038. Result:=true;
  3039. exit;
  3040. end;
  3041. else
  3042. ;
  3043. end;
  3044. if (
  3045. (taicpu(p).oper[0]^.typ=top_reg) or
  3046. (
  3047. (taicpu(p).oper[0]^.typ=top_ref) and
  3048. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  3049. )
  3050. ) and
  3051. GetNextInstruction(hp1,hp2) and
  3052. MatchInstruction(hp2,A_TEST,[]) and
  3053. (
  3054. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3055. (
  3056. { If the register being tested is smaller than the one
  3057. that received a bitwise AND, permit it if the constant
  3058. fits into the smaller size }
  3059. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3060. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3061. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3062. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3063. (
  3064. (
  3065. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3066. (taicpu(hp1).oper[0]^.val <= $FF)
  3067. ) or
  3068. (
  3069. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3070. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3071. {$ifdef x86_64}
  3072. ) or
  3073. (
  3074. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3075. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3076. {$endif x86_64}
  3077. )
  3078. )
  3079. )
  3080. ) and
  3081. (
  3082. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3083. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3084. ) and
  3085. GetNextInstruction(hp2,hp3) and
  3086. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3087. (taicpu(hp3).condition in [C_E,C_NE]) then
  3088. begin
  3089. TransferUsedRegs(TmpUsedRegs);
  3090. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3091. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3092. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3093. begin
  3094. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3095. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3096. taicpu(hp1).opcode:=A_TEST;
  3097. { Shrink the TEST instruction down to the smallest possible size }
  3098. case taicpu(hp1).oper[0]^.val of
  3099. 0..255:
  3100. if (taicpu(hp1).opsize <> S_B)
  3101. {$ifndef x86_64}
  3102. and (
  3103. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3104. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3105. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3106. )
  3107. {$endif x86_64}
  3108. then
  3109. begin
  3110. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3111. { Only print debug message if the TEST instruction
  3112. is a different size before and after }
  3113. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3114. taicpu(hp1).opsize := S_B;
  3115. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3116. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3117. end;
  3118. 256..65535:
  3119. if (taicpu(hp1).opsize <> S_W) then
  3120. begin
  3121. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3122. { Only print debug message if the TEST instruction
  3123. is a different size before and after }
  3124. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3125. taicpu(hp1).opsize := S_W;
  3126. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3127. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3128. end;
  3129. {$ifdef x86_64}
  3130. 65536..$7FFFFFFF:
  3131. if (taicpu(hp1).opsize <> S_L) then
  3132. begin
  3133. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3134. { Only print debug message if the TEST instruction
  3135. is a different size before and after }
  3136. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3137. taicpu(hp1).opsize := S_L;
  3138. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3139. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3140. end;
  3141. {$endif x86_64}
  3142. else
  3143. ;
  3144. end;
  3145. RemoveInstruction(hp2);
  3146. RemoveCurrentP(p, hp1);
  3147. Result:=true;
  3148. exit;
  3149. end;
  3150. end;
  3151. end
  3152. else if IsMOVZXAcceptable and
  3153. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3154. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3155. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3156. then
  3157. begin
  3158. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3159. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3160. case taicpu(p).opsize of
  3161. S_B:
  3162. if (taicpu(hp1).oper[0]^.val = $ff) then
  3163. begin
  3164. { Convert:
  3165. movb x, %regl movb x, %regl
  3166. andw ffh, %regw andl ffh, %regd
  3167. To:
  3168. movzbw x, %regd movzbl x, %regd
  3169. (Identical registers, just different sizes)
  3170. }
  3171. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3172. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3173. case taicpu(hp1).opsize of
  3174. S_W: NewSize := S_BW;
  3175. S_L: NewSize := S_BL;
  3176. {$ifdef x86_64}
  3177. S_Q: NewSize := S_BQ;
  3178. {$endif x86_64}
  3179. else
  3180. InternalError(2018011510);
  3181. end;
  3182. end
  3183. else
  3184. NewSize := S_NO;
  3185. S_W:
  3186. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3187. begin
  3188. { Convert:
  3189. movw x, %regw
  3190. andl ffffh, %regd
  3191. To:
  3192. movzwl x, %regd
  3193. (Identical registers, just different sizes)
  3194. }
  3195. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3196. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3197. case taicpu(hp1).opsize of
  3198. S_L: NewSize := S_WL;
  3199. {$ifdef x86_64}
  3200. S_Q: NewSize := S_WQ;
  3201. {$endif x86_64}
  3202. else
  3203. InternalError(2018011511);
  3204. end;
  3205. end
  3206. else
  3207. NewSize := S_NO;
  3208. else
  3209. NewSize := S_NO;
  3210. end;
  3211. if NewSize <> S_NO then
  3212. begin
  3213. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3214. { The actual optimization }
  3215. taicpu(p).opcode := A_MOVZX;
  3216. taicpu(p).changeopsize(NewSize);
  3217. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3218. { Safeguard if "and" is followed by a conditional command }
  3219. TransferUsedRegs(TmpUsedRegs);
  3220. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3221. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3222. begin
  3223. { At this point, the "and" command is effectively equivalent to
  3224. "test %reg,%reg". This will be handled separately by the
  3225. Peephole Optimizer. [Kit] }
  3226. DebugMsg(SPeepholeOptimization + PreMessage +
  3227. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3228. end
  3229. else
  3230. begin
  3231. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3232. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3233. RemoveInstruction(hp1);
  3234. end;
  3235. Result := True;
  3236. Exit;
  3237. end;
  3238. end;
  3239. end;
  3240. if (taicpu(hp1).opcode = A_OR) and
  3241. (taicpu(p).oper[1]^.typ = top_reg) and
  3242. MatchOperand(taicpu(p).oper[0]^, 0) and
  3243. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3244. begin
  3245. { mov 0, %reg
  3246. or ###,%reg
  3247. Change to (only if the flags are not used):
  3248. mov ###,%reg
  3249. }
  3250. TransferUsedRegs(TmpUsedRegs);
  3251. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3252. DoOptimisation := True;
  3253. { Even if the flags are used, we might be able to do the optimisation
  3254. if the conditions are predictable }
  3255. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3256. begin
  3257. { Only perform if ### = %reg (the same register) or equal to 0,
  3258. so %reg is guaranteed to still have a value of zero }
  3259. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3260. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3261. begin
  3262. hp2 := hp1;
  3263. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3264. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3265. GetNextInstruction(hp2, hp3) do
  3266. begin
  3267. { Don't continue modifying if the flags state is getting changed }
  3268. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3269. Break;
  3270. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3271. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3272. begin
  3273. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3274. begin
  3275. { Condition is always true }
  3276. case taicpu(hp3).opcode of
  3277. A_Jcc:
  3278. begin
  3279. { Check for jump shortcuts before we destroy the condition }
  3280. hp4 := hp3;
  3281. DoJumpOptimizations(hp3, TempBool);
  3282. { Make sure hp3 hasn't changed }
  3283. if (hp4 = hp3) then
  3284. begin
  3285. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3286. MakeUnconditional(taicpu(hp3));
  3287. end;
  3288. Result := True;
  3289. end;
  3290. A_CMOVcc:
  3291. begin
  3292. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3293. taicpu(hp3).opcode := A_MOV;
  3294. taicpu(hp3).condition := C_None;
  3295. Result := True;
  3296. end;
  3297. A_SETcc:
  3298. begin
  3299. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3300. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3301. taicpu(hp3).opcode := A_MOV;
  3302. taicpu(hp3).ops := 2;
  3303. taicpu(hp3).condition := C_None;
  3304. taicpu(hp3).opsize := S_B;
  3305. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3306. taicpu(hp3).loadconst(0, 1);
  3307. Result := True;
  3308. end;
  3309. else
  3310. InternalError(2021090701);
  3311. end;
  3312. end
  3313. 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
  3314. begin
  3315. { Condition is always false }
  3316. case taicpu(hp3).opcode of
  3317. A_Jcc:
  3318. begin
  3319. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3320. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3321. RemoveInstruction(hp3);
  3322. Result := True;
  3323. { Since hp3 was deleted, hp2 must not be updated }
  3324. Continue;
  3325. end;
  3326. A_CMOVcc:
  3327. begin
  3328. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3329. RemoveInstruction(hp3);
  3330. Result := True;
  3331. { Since hp3 was deleted, hp2 must not be updated }
  3332. Continue;
  3333. end;
  3334. A_SETcc:
  3335. begin
  3336. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3337. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3338. taicpu(hp3).opcode := A_MOV;
  3339. taicpu(hp3).ops := 2;
  3340. taicpu(hp3).condition := C_None;
  3341. taicpu(hp3).opsize := S_B;
  3342. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3343. taicpu(hp3).loadconst(0, 0);
  3344. Result := True;
  3345. end;
  3346. else
  3347. InternalError(2021090702);
  3348. end;
  3349. end
  3350. else
  3351. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3352. DoOptimisation := False;
  3353. end;
  3354. hp2 := hp3;
  3355. end;
  3356. { Flags are still in use - don't optimise }
  3357. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3358. DoOptimisation := False;
  3359. end
  3360. else
  3361. DoOptimisation := False;
  3362. end;
  3363. if DoOptimisation then
  3364. begin
  3365. {$ifdef x86_64}
  3366. { OR only supports 32-bit sign-extended constants for 64-bit
  3367. instructions, so compensate for this if the constant is
  3368. encoded as a value greater than or equal to 2^31 }
  3369. if (taicpu(hp1).opsize = S_Q) and
  3370. (taicpu(hp1).oper[0]^.typ = top_const) and
  3371. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3372. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3373. {$endif x86_64}
  3374. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3375. taicpu(hp1).opcode := A_MOV;
  3376. RemoveCurrentP(p, hp1);
  3377. Result := True;
  3378. Exit;
  3379. end;
  3380. end;
  3381. { Next instruction is also a MOV ? }
  3382. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3383. begin
  3384. if MatchOpType(taicpu(p), top_const, top_ref) and
  3385. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3386. TryConstMerge(p, hp1) then
  3387. begin
  3388. Result := True;
  3389. { In case we have four byte writes in a row, check for 2 more
  3390. right now so we don't have to wait for another iteration of
  3391. pass 1
  3392. }
  3393. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3394. case taicpu(p).opsize of
  3395. S_W:
  3396. begin
  3397. if GetNextInstruction(p, hp1) and
  3398. MatchInstruction(hp1, A_MOV, [S_B]) and
  3399. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3400. GetNextInstruction(hp1, hp2) and
  3401. MatchInstruction(hp2, A_MOV, [S_B]) and
  3402. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3403. { Try to merge the two bytes }
  3404. TryConstMerge(hp1, hp2) then
  3405. { Now try to merge the two words (hp2 will get deleted) }
  3406. TryConstMerge(p, hp1);
  3407. end;
  3408. S_L:
  3409. begin
  3410. { Though this only really benefits x86_64 and not i386, it
  3411. gets a potential optimisation done faster and hence
  3412. reduces the number of times OptPass1MOV is entered }
  3413. if GetNextInstruction(p, hp1) and
  3414. MatchInstruction(hp1, A_MOV, [S_W]) and
  3415. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3416. GetNextInstruction(hp1, hp2) and
  3417. MatchInstruction(hp2, A_MOV, [S_W]) and
  3418. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3419. { Try to merge the two words }
  3420. TryConstMerge(hp1, hp2) then
  3421. { This will always fail on i386, so don't bother
  3422. calling it unless we're doing x86_64 }
  3423. {$ifdef x86_64}
  3424. { Now try to merge the two longwords (hp2 will get deleted) }
  3425. TryConstMerge(p, hp1)
  3426. {$endif x86_64}
  3427. ;
  3428. end;
  3429. else
  3430. ;
  3431. end;
  3432. Exit;
  3433. end;
  3434. if (taicpu(p).oper[1]^.typ = top_reg) and
  3435. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3436. begin
  3437. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3438. TransferUsedRegs(TmpUsedRegs);
  3439. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3440. { we have
  3441. mov x, %treg
  3442. mov %treg, y
  3443. }
  3444. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3445. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3446. { we've got
  3447. mov x, %treg
  3448. mov %treg, y
  3449. with %treg is not used after }
  3450. case taicpu(p).oper[0]^.typ Of
  3451. { top_reg is covered by DeepMOVOpt }
  3452. top_const:
  3453. begin
  3454. { change
  3455. mov const, %treg
  3456. mov %treg, y
  3457. to
  3458. mov const, y
  3459. }
  3460. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3461. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3462. begin
  3463. if taicpu(hp1).oper[1]^.typ=top_reg then
  3464. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3465. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3466. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3467. RemoveInstruction(hp1);
  3468. Result:=true;
  3469. Exit;
  3470. end;
  3471. end;
  3472. top_ref:
  3473. case taicpu(hp1).oper[1]^.typ of
  3474. top_reg:
  3475. begin
  3476. { change
  3477. mov mem, %treg
  3478. mov %treg, %reg
  3479. to
  3480. mov mem, %reg"
  3481. }
  3482. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3483. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3484. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3485. RemoveInstruction(hp1);
  3486. Result:=true;
  3487. Exit;
  3488. end;
  3489. top_ref:
  3490. begin
  3491. {$ifdef x86_64}
  3492. { Look for the following to simplify:
  3493. mov x(mem1), %reg
  3494. mov %reg, y(mem2)
  3495. mov x+8(mem1), %reg
  3496. mov %reg, y+8(mem2)
  3497. Change to:
  3498. movdqu x(mem1), %xmmreg
  3499. movdqu %xmmreg, y(mem2)
  3500. ...but only as long as the memory blocks don't overlap
  3501. }
  3502. SourceRef := taicpu(p).oper[0]^.ref^;
  3503. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3504. if (taicpu(p).opsize = S_Q) and
  3505. GetNextInstruction(hp1, hp2) and
  3506. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3507. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3508. begin
  3509. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3510. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3511. Inc(SourceRef.offset, 8);
  3512. if UseAVX then
  3513. begin
  3514. MovAligned := A_VMOVDQA;
  3515. MovUnaligned := A_VMOVDQU;
  3516. end
  3517. else
  3518. begin
  3519. MovAligned := A_MOVDQA;
  3520. MovUnaligned := A_MOVDQU;
  3521. end;
  3522. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3523. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3524. begin
  3525. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3526. Inc(TargetRef.offset, 8);
  3527. if GetNextInstruction(hp2, hp3) and
  3528. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3529. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3530. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3531. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3532. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3533. begin
  3534. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3535. if NewMMReg <> NR_NO then
  3536. begin
  3537. { Remember that the offsets are 8 ahead }
  3538. if ((SourceRef.offset mod 16) = 8) and
  3539. (
  3540. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3541. (SourceRef.base = current_procinfo.framepointer) or
  3542. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3543. ) then
  3544. taicpu(p).opcode := MovAligned
  3545. else
  3546. taicpu(p).opcode := MovUnaligned;
  3547. taicpu(p).opsize := S_XMM;
  3548. taicpu(p).oper[1]^.reg := NewMMReg;
  3549. if ((TargetRef.offset mod 16) = 8) and
  3550. (
  3551. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3552. (TargetRef.base = current_procinfo.framepointer) or
  3553. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3554. ) then
  3555. taicpu(hp1).opcode := MovAligned
  3556. else
  3557. taicpu(hp1).opcode := MovUnaligned;
  3558. taicpu(hp1).opsize := S_XMM;
  3559. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3560. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3561. RemoveInstruction(hp2);
  3562. RemoveInstruction(hp3);
  3563. Result := True;
  3564. Exit;
  3565. end;
  3566. end;
  3567. end
  3568. else
  3569. begin
  3570. { See if the next references are 8 less rather than 8 greater }
  3571. Dec(SourceRef.offset, 16); { -8 the other way }
  3572. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3573. begin
  3574. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3575. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3576. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3577. GetNextInstruction(hp2, hp3) and
  3578. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3579. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3580. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3581. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3582. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3583. begin
  3584. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3585. if NewMMReg <> NR_NO then
  3586. begin
  3587. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3588. if ((SourceRef.offset mod 16) = 0) and
  3589. (
  3590. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3591. (SourceRef.base = current_procinfo.framepointer) or
  3592. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3593. ) then
  3594. taicpu(hp2).opcode := MovAligned
  3595. else
  3596. taicpu(hp2).opcode := MovUnaligned;
  3597. taicpu(hp2).opsize := S_XMM;
  3598. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3599. if ((TargetRef.offset mod 16) = 0) and
  3600. (
  3601. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3602. (TargetRef.base = current_procinfo.framepointer) or
  3603. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3604. ) then
  3605. taicpu(hp3).opcode := MovAligned
  3606. else
  3607. taicpu(hp3).opcode := MovUnaligned;
  3608. taicpu(hp3).opsize := S_XMM;
  3609. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3610. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3611. RemoveInstruction(hp1);
  3612. RemoveCurrentP(p, hp2);
  3613. Result := True;
  3614. Exit;
  3615. end;
  3616. end;
  3617. end;
  3618. end;
  3619. end;
  3620. {$endif x86_64}
  3621. end;
  3622. else
  3623. { The write target should be a reg or a ref }
  3624. InternalError(2021091601);
  3625. end;
  3626. else
  3627. ;
  3628. end
  3629. else
  3630. { %treg is used afterwards, but all eventualities
  3631. other than the first MOV instruction being a constant
  3632. are covered by DeepMOVOpt, so only check for that }
  3633. if (taicpu(p).oper[0]^.typ = top_const) and
  3634. (
  3635. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3636. not (cs_opt_size in current_settings.optimizerswitches) or
  3637. (taicpu(hp1).opsize = S_B)
  3638. ) and
  3639. (
  3640. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3641. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3642. ) then
  3643. begin
  3644. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3645. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3646. end;
  3647. end;
  3648. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3649. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3650. { mov reg1, mem1 or mov mem1, reg1
  3651. mov mem2, reg2 mov reg2, mem2}
  3652. begin
  3653. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3654. { mov reg1, mem1 or mov mem1, reg1
  3655. mov mem2, reg1 mov reg2, mem1}
  3656. begin
  3657. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3658. { Removes the second statement from
  3659. mov reg1, mem1/reg2
  3660. mov mem1/reg2, reg1 }
  3661. begin
  3662. if taicpu(p).oper[0]^.typ=top_reg then
  3663. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3664. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3665. RemoveInstruction(hp1);
  3666. Result:=true;
  3667. exit;
  3668. end
  3669. else
  3670. begin
  3671. TransferUsedRegs(TmpUsedRegs);
  3672. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3673. if (taicpu(p).oper[1]^.typ = top_ref) and
  3674. { mov reg1, mem1
  3675. mov mem2, reg1 }
  3676. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3677. GetNextInstruction(hp1, hp2) and
  3678. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3679. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3680. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3681. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3682. { change to
  3683. mov reg1, mem1 mov reg1, mem1
  3684. mov mem2, reg1 cmp reg1, mem2
  3685. cmp mem1, reg1
  3686. }
  3687. begin
  3688. RemoveInstruction(hp2);
  3689. taicpu(hp1).opcode := A_CMP;
  3690. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3691. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3692. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3693. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3694. end;
  3695. end;
  3696. end
  3697. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3698. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3699. begin
  3700. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3701. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3702. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3703. end
  3704. else
  3705. begin
  3706. TransferUsedRegs(TmpUsedRegs);
  3707. if GetNextInstruction(hp1, hp2) and
  3708. MatchOpType(taicpu(p),top_ref,top_reg) and
  3709. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3710. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3711. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3712. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3713. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3714. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3715. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3716. { mov mem1, %reg1
  3717. mov %reg1, mem2
  3718. mov mem2, reg2
  3719. to:
  3720. mov mem1, reg2
  3721. mov reg2, mem2}
  3722. begin
  3723. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3724. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3725. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3726. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3727. RemoveInstruction(hp2);
  3728. Result := True;
  3729. end
  3730. {$ifdef i386}
  3731. { this is enabled for i386 only, as the rules to create the reg sets below
  3732. are too complicated for x86-64, so this makes this code too error prone
  3733. on x86-64
  3734. }
  3735. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3736. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3737. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3738. { mov mem1, reg1 mov mem1, reg1
  3739. mov reg1, mem2 mov reg1, mem2
  3740. mov mem2, reg2 mov mem2, reg1
  3741. to: to:
  3742. mov mem1, reg1 mov mem1, reg1
  3743. mov mem1, reg2 mov reg1, mem2
  3744. mov reg1, mem2
  3745. or (if mem1 depends on reg1
  3746. and/or if mem2 depends on reg2)
  3747. to:
  3748. mov mem1, reg1
  3749. mov reg1, mem2
  3750. mov reg1, reg2
  3751. }
  3752. begin
  3753. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3754. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3755. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3756. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3757. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3758. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3759. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3760. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3761. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3762. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3763. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3764. end
  3765. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3766. begin
  3767. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3768. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3769. end
  3770. else
  3771. begin
  3772. RemoveInstruction(hp2);
  3773. end
  3774. {$endif i386}
  3775. ;
  3776. end;
  3777. end
  3778. { movl [mem1],reg1
  3779. movl [mem1],reg2
  3780. to
  3781. movl [mem1],reg1
  3782. movl reg1,reg2
  3783. }
  3784. else if not CheckMovMov2MovMov2(p, hp1) and
  3785. { movl const1,[mem1]
  3786. movl [mem1],reg1
  3787. to
  3788. movl const1,reg1
  3789. movl reg1,[mem1]
  3790. }
  3791. MatchOpType(Taicpu(p),top_const,top_ref) and
  3792. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3793. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3794. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3795. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3796. begin
  3797. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3798. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3799. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3800. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3801. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3802. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3803. Result:=true;
  3804. exit;
  3805. end;
  3806. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3807. { Change:
  3808. movl %reg1,%reg2
  3809. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3810. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3811. To:
  3812. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3813. movl x(%reg1),%reg1
  3814. movl %reg1,%regX
  3815. }
  3816. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3817. begin
  3818. p_SourceReg := taicpu(p).oper[0]^.reg;
  3819. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3820. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3821. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3822. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3823. GetNextInstruction(hp1, hp2) and
  3824. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3825. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3826. begin
  3827. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3828. if RegInRef(p_TargetReg, SourceRef) and
  3829. { If %reg1 also appears in the second reference, then it will
  3830. not refer to the same memory block as the first reference }
  3831. not RegInRef(p_SourceReg, SourceRef) then
  3832. begin
  3833. { Check to see if the references match if %reg2 is changed to %reg1 }
  3834. if SourceRef.base = p_TargetReg then
  3835. SourceRef.base := p_SourceReg;
  3836. if SourceRef.index = p_TargetReg then
  3837. SourceRef.index := p_SourceReg;
  3838. { RefsEqual also checks to ensure both references are non-volatile }
  3839. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3840. begin
  3841. taicpu(hp2).loadreg(0, p_SourceReg);
  3842. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3843. Result := True;
  3844. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3845. begin
  3846. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3847. RemoveCurrentP(p, hp1);
  3848. Exit;
  3849. end
  3850. else
  3851. begin
  3852. { Check to see if %reg2 is no longer in use }
  3853. TransferUsedRegs(TmpUsedRegs);
  3854. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3855. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3856. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3857. begin
  3858. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3859. RemoveCurrentP(p, hp1);
  3860. Exit;
  3861. end;
  3862. end;
  3863. { If we reach this point, p and hp1 weren't actually modified,
  3864. so we can do a bit more work on this pass }
  3865. end;
  3866. end;
  3867. end;
  3868. end;
  3869. end;
  3870. {$ifdef x86_64}
  3871. { Change:
  3872. movl %reg1l,%reg2l
  3873. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3874. To:
  3875. movl %reg1l,%reg2l
  3876. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3877. If %reg1 = %reg3, convert to:
  3878. movl %reg1l,%reg2l
  3879. andl %reg1l,%reg1l
  3880. }
  3881. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3882. MatchOpType(taicpu(p), top_reg, top_reg) and
  3883. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3884. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3885. begin
  3886. TransferUsedRegs(TmpUsedRegs);
  3887. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3888. taicpu(hp1).opsize := S_L;
  3889. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3890. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3891. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3892. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3893. begin
  3894. { %reg1 = %reg3 }
  3895. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3896. taicpu(hp1).opcode := A_AND;
  3897. end
  3898. else
  3899. begin
  3900. { %reg1 <> %reg3 }
  3901. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3902. end;
  3903. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3904. begin
  3905. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3906. RemoveCurrentP(p, hp1);
  3907. Result := True;
  3908. Exit;
  3909. end
  3910. else
  3911. begin
  3912. { Initial instruction wasn't actually changed }
  3913. Include(OptsToCheck, aoc_ForceNewIteration);
  3914. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3915. appears below since %reg1 has technically changed }
  3916. if taicpu(hp1).opcode = A_AND then
  3917. Exit;
  3918. end;
  3919. end;
  3920. {$endif x86_64}
  3921. { search further than the next instruction for a mov (as long as it's not a jump) }
  3922. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3923. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3924. (taicpu(p).oper[1]^.typ = top_reg) and
  3925. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3926. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3927. begin
  3928. { we work with hp2 here, so hp1 can be still used later on when
  3929. checking for GetNextInstruction_p }
  3930. hp3 := hp1;
  3931. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3932. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3933. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3934. TransferUsedRegs(TmpUsedRegs);
  3935. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3936. if NotFirstIteration then
  3937. JumpTracking := TLinkedList.Create
  3938. else
  3939. JumpTracking := nil;
  3940. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3941. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3942. (hp2.typ=ait_instruction) do
  3943. begin
  3944. case taicpu(hp2).opcode of
  3945. A_POP:
  3946. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3947. begin
  3948. if not CrossJump and
  3949. not RegUsedBetween(p_TargetReg, p, hp2) then
  3950. begin
  3951. { We can remove the original MOV since the register
  3952. wasn't used between it and its popping from the stack }
  3953. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3954. RemoveCurrentp(p, hp1);
  3955. Result := True;
  3956. JumpTracking.Free;
  3957. Exit;
  3958. end;
  3959. { Can't go any further }
  3960. Break;
  3961. end;
  3962. A_MOV:
  3963. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3964. ((taicpu(p).oper[0]^.typ=top_const) or
  3965. ((taicpu(p).oper[0]^.typ=top_reg) and
  3966. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3967. )
  3968. ) then
  3969. begin
  3970. { we have
  3971. mov x, %treg
  3972. mov %treg, y
  3973. }
  3974. { We don't need to call UpdateUsedRegs for every instruction between
  3975. p and hp2 because the register we're concerned about will not
  3976. become deallocated (otherwise GetNextInstructionUsingReg would
  3977. have stopped at an earlier instruction). [Kit] }
  3978. TempRegUsed :=
  3979. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3980. RegReadByInstruction(p_TargetReg, hp3) or
  3981. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3982. case taicpu(p).oper[0]^.typ Of
  3983. top_reg:
  3984. begin
  3985. { change
  3986. mov %reg, %treg
  3987. mov %treg, y
  3988. to
  3989. mov %reg, y
  3990. }
  3991. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3992. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3993. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3994. begin
  3995. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3996. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3997. if TempRegUsed then
  3998. begin
  3999. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4000. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4001. { Set the start of the next GetNextInstructionUsingRegCond search
  4002. to start at the entry right before hp2 (which is about to be removed) }
  4003. hp3 := tai(hp2.Previous);
  4004. RemoveInstruction(hp2);
  4005. Include(OptsToCheck, aoc_ForceNewIteration);
  4006. { See if there's more we can optimise }
  4007. Continue;
  4008. end
  4009. else
  4010. begin
  4011. RemoveInstruction(hp2);
  4012. { We can remove the original MOV too }
  4013. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4014. RemoveCurrentP(p, hp1);
  4015. Result:=true;
  4016. JumpTracking.Free;
  4017. Exit;
  4018. end;
  4019. end
  4020. else
  4021. begin
  4022. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4023. taicpu(hp2).loadReg(0, p_SourceReg);
  4024. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4025. { Check to see if the register also appears in the reference }
  4026. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4027. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4028. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4029. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4030. begin
  4031. { Don't remove the first instruction if the temporary register is in use }
  4032. if not TempRegUsed then
  4033. begin
  4034. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4035. RemoveCurrentP(p, hp1);
  4036. Result:=true;
  4037. JumpTracking.Free;
  4038. Exit;
  4039. end;
  4040. { No need to set Result to True here. If there's another instruction later
  4041. on that can be optimised, it will be detected when the main Pass 1 loop
  4042. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4043. hp3 := hp2;
  4044. Continue;
  4045. end;
  4046. end;
  4047. end;
  4048. top_const:
  4049. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4050. begin
  4051. { change
  4052. mov const, %treg
  4053. mov %treg, y
  4054. to
  4055. mov const, y
  4056. }
  4057. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4058. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4059. begin
  4060. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4061. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4062. if TempRegUsed then
  4063. begin
  4064. { Don't remove the first instruction if the temporary register is in use }
  4065. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4066. { No need to set Result to True. If there's another instruction later on
  4067. that can be optimised, it will be detected when the main Pass 1 loop
  4068. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4069. end
  4070. else
  4071. begin
  4072. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4073. RemoveCurrentP(p, hp1);
  4074. Result:=true;
  4075. Exit;
  4076. end;
  4077. end;
  4078. end;
  4079. else
  4080. Internalerror(2019103001);
  4081. end;
  4082. end
  4083. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4084. begin
  4085. if not CrossJump and
  4086. not RegUsedBetween(p_TargetReg, p, hp2) and
  4087. not RegReadByInstruction(p_TargetReg, hp2) then
  4088. begin
  4089. { Register is not used before it is overwritten }
  4090. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4091. RemoveCurrentp(p, hp1);
  4092. Result := True;
  4093. Exit;
  4094. end;
  4095. if (taicpu(p).oper[0]^.typ = top_const) and
  4096. (taicpu(hp2).oper[0]^.typ = top_const) then
  4097. begin
  4098. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4099. begin
  4100. { Same value - register hasn't changed }
  4101. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4102. RemoveInstruction(hp2);
  4103. Include(OptsToCheck, aoc_ForceNewIteration);
  4104. { See if there's more we can optimise }
  4105. Continue;
  4106. end;
  4107. end;
  4108. {$ifdef x86_64}
  4109. end
  4110. { Change:
  4111. movl %reg1l,%reg2l
  4112. ...
  4113. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4114. To:
  4115. movl %reg1l,%reg2l
  4116. ...
  4117. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4118. If %reg1 = %reg3, convert to:
  4119. movl %reg1l,%reg2l
  4120. ...
  4121. andl %reg1l,%reg1l
  4122. }
  4123. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4124. (taicpu(p).oper[0]^.typ = top_reg) and
  4125. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4126. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4127. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4128. begin
  4129. TempRegUsed :=
  4130. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4131. RegReadByInstruction(p_TargetReg, hp3) or
  4132. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4133. taicpu(hp2).opsize := S_L;
  4134. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4135. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4136. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4137. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4138. begin
  4139. { %reg1 = %reg3 }
  4140. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4141. taicpu(hp2).opcode := A_AND;
  4142. end
  4143. else
  4144. begin
  4145. { %reg1 <> %reg3 }
  4146. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4147. end;
  4148. if not TempRegUsed then
  4149. begin
  4150. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4151. RemoveCurrentP(p, hp1);
  4152. Result := True;
  4153. Exit;
  4154. end
  4155. else
  4156. begin
  4157. { Initial instruction wasn't actually changed }
  4158. Include(OptsToCheck, aoc_ForceNewIteration);
  4159. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4160. appears below since %reg1 has technically changed }
  4161. if taicpu(hp2).opcode = A_AND then
  4162. Break;
  4163. end;
  4164. {$endif x86_64}
  4165. end
  4166. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4167. GetNextInstruction(hp2, hp4) and
  4168. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4169. { Optimise the following first:
  4170. movl [mem1],reg1
  4171. movl [mem1],reg2
  4172. to
  4173. movl [mem1],reg1
  4174. movl reg1,reg2
  4175. If [mem1] contains the target register and reg1 is the
  4176. the source register, this optimisation will get missed
  4177. and produce less efficient code later on.
  4178. }
  4179. if CheckMovMov2MovMov2(hp2, hp4) then
  4180. { Initial instruction wasn't actually changed }
  4181. Include(OptsToCheck, aoc_ForceNewIteration);
  4182. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4183. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4184. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4185. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4186. begin
  4187. {
  4188. Change from:
  4189. mov ###, %reg
  4190. ...
  4191. movs/z %reg,%reg (Same register, just different sizes)
  4192. To:
  4193. movs/z ###, %reg (Longer version)
  4194. ...
  4195. (remove)
  4196. }
  4197. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4198. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4199. { Keep the first instruction as mov if ### is a constant }
  4200. if taicpu(p).oper[0]^.typ = top_const then
  4201. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4202. else
  4203. begin
  4204. taicpu(p).opcode := taicpu(hp2).opcode;
  4205. taicpu(p).opsize := taicpu(hp2).opsize;
  4206. end;
  4207. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4208. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4209. RemoveInstruction(hp2);
  4210. Result := True;
  4211. JumpTracking.Free;
  4212. Exit;
  4213. end;
  4214. else
  4215. { Move down to the if-block below };
  4216. end;
  4217. { Also catches MOV/S/Z instructions that aren't modified }
  4218. if taicpu(p).oper[0]^.typ = top_reg then
  4219. begin
  4220. p_SourceReg := taicpu(p).oper[0]^.reg;
  4221. if
  4222. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4223. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4224. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4225. begin
  4226. Result := True;
  4227. { Just in case something didn't get modified (e.g. an
  4228. implicit register). Also, if it does read from this
  4229. register, then there's no longer an advantage to
  4230. changing the register on subsequent instructions.}
  4231. if not RegReadByInstruction(p_TargetReg, hp2) then
  4232. begin
  4233. { If a conditional jump was crossed, do not delete
  4234. the original MOV no matter what }
  4235. if not CrossJump and
  4236. { RegEndOfLife returns True if the register is
  4237. deallocated before the next instruction or has
  4238. been loaded with a new value }
  4239. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4240. begin
  4241. { We can remove the original MOV }
  4242. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4243. RemoveCurrentp(p, hp1);
  4244. JumpTracking.Free;
  4245. Result := True;
  4246. Exit;
  4247. end;
  4248. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4249. begin
  4250. { See if there's more we can optimise }
  4251. hp3 := hp2;
  4252. Continue;
  4253. end;
  4254. end;
  4255. end;
  4256. end;
  4257. { Break out of the while loop under normal circumstances }
  4258. Break;
  4259. end;
  4260. JumpTracking.Free;
  4261. end;
  4262. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4263. (taicpu(p).oper[1]^.typ = top_reg) and
  4264. (taicpu(p).opsize = S_L) and
  4265. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4266. (hp2.typ = ait_instruction) and
  4267. (taicpu(hp2).opcode = A_AND) and
  4268. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4269. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4270. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4271. ) then
  4272. begin
  4273. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4274. begin
  4275. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4276. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4277. begin
  4278. { Optimize out:
  4279. mov x, %reg
  4280. and ffffffffh, %reg
  4281. }
  4282. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4283. RemoveInstruction(hp2);
  4284. Result:=true;
  4285. exit;
  4286. end;
  4287. end;
  4288. end;
  4289. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4290. x >= RetOffset) as it doesn't do anything (it writes either to a
  4291. parameter or to the temporary storage room for the function
  4292. result)
  4293. }
  4294. if IsExitCode(hp1) and
  4295. (taicpu(p).oper[1]^.typ = top_ref) and
  4296. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4297. (
  4298. (
  4299. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4300. not (
  4301. assigned(current_procinfo.procdef.funcretsym) and
  4302. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4303. )
  4304. ) or
  4305. { Also discard writes to the stack that are below the base pointer,
  4306. as this is temporary storage rather than a function result on the
  4307. stack, say. }
  4308. (
  4309. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4310. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4311. )
  4312. ) then
  4313. begin
  4314. RemoveCurrentp(p, hp1);
  4315. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4316. RemoveLastDeallocForFuncRes(p);
  4317. Result:=true;
  4318. exit;
  4319. end;
  4320. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4321. begin
  4322. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4323. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4324. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4325. begin
  4326. { change
  4327. mov reg1, mem1
  4328. test/cmp x, mem1
  4329. to
  4330. mov reg1, mem1
  4331. test/cmp x, reg1
  4332. }
  4333. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4334. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4335. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4336. Result := True;
  4337. Exit;
  4338. end;
  4339. if DoMovCmpMemOpt(p, hp1) then
  4340. begin
  4341. Result := True;
  4342. Exit;
  4343. end;
  4344. end;
  4345. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4346. { If the flags register is in use, don't change the instruction to an
  4347. ADD otherwise this will scramble the flags. [Kit] }
  4348. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4349. begin
  4350. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4351. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4352. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4353. ) or
  4354. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4355. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4356. )
  4357. ) then
  4358. { mov reg1,ref
  4359. lea reg2,[reg1,reg2]
  4360. to
  4361. add reg2,ref}
  4362. begin
  4363. TransferUsedRegs(TmpUsedRegs);
  4364. { reg1 may not be used afterwards }
  4365. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4366. begin
  4367. Taicpu(hp1).opcode:=A_ADD;
  4368. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4369. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4370. RemoveCurrentp(p, hp1);
  4371. result:=true;
  4372. exit;
  4373. end;
  4374. end;
  4375. { If the LEA instruction can be converted into an arithmetic instruction,
  4376. it may be possible to then fold it in the next optimisation, otherwise
  4377. there's nothing more that can be optimised here. }
  4378. if not ConvertLEA(taicpu(hp1)) then
  4379. Exit;
  4380. end;
  4381. if (taicpu(p).oper[1]^.typ = top_reg) and
  4382. (hp1.typ = ait_instruction) and
  4383. GetNextInstruction(hp1, hp2) and
  4384. MatchInstruction(hp2,A_MOV,[]) and
  4385. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4386. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4387. (
  4388. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4389. {$ifdef x86_64}
  4390. or
  4391. (
  4392. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4393. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4394. )
  4395. {$endif x86_64}
  4396. ) then
  4397. begin
  4398. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4399. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4400. { change movsX/movzX reg/ref, reg2
  4401. add/sub/or/... reg3/$const, reg2
  4402. mov reg2 reg/ref
  4403. dealloc reg2
  4404. to
  4405. add/sub/or/... reg3/$const, reg/ref }
  4406. begin
  4407. TransferUsedRegs(TmpUsedRegs);
  4408. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4409. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4410. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4411. begin
  4412. { by example:
  4413. movswl %si,%eax movswl %si,%eax p
  4414. decl %eax addl %edx,%eax hp1
  4415. movw %ax,%si movw %ax,%si hp2
  4416. ->
  4417. movswl %si,%eax movswl %si,%eax p
  4418. decw %eax addw %edx,%eax hp1
  4419. movw %ax,%si movw %ax,%si hp2
  4420. }
  4421. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4422. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4423. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4424. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4425. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4426. {
  4427. ->
  4428. movswl %si,%eax movswl %si,%eax p
  4429. decw %si addw %dx,%si hp1
  4430. movw %ax,%si movw %ax,%si hp2
  4431. }
  4432. case taicpu(hp1).ops of
  4433. 1:
  4434. begin
  4435. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4436. if taicpu(hp1).oper[0]^.typ=top_reg then
  4437. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4438. end;
  4439. 2:
  4440. begin
  4441. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4442. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4443. (taicpu(hp1).opcode<>A_SHL) and
  4444. (taicpu(hp1).opcode<>A_SHR) and
  4445. (taicpu(hp1).opcode<>A_SAR) then
  4446. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4447. end;
  4448. else
  4449. internalerror(2008042701);
  4450. end;
  4451. {
  4452. ->
  4453. decw %si addw %dx,%si p
  4454. }
  4455. RemoveInstruction(hp2);
  4456. RemoveCurrentP(p, hp1);
  4457. Result:=True;
  4458. Exit;
  4459. end;
  4460. end;
  4461. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4462. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4463. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4464. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4465. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4466. )
  4467. {$ifdef i386}
  4468. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4469. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4470. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4471. {$endif i386}
  4472. then
  4473. { change movsX/movzX reg/ref, reg2
  4474. add/sub/or/... regX/$const, reg2
  4475. mov reg2, reg3
  4476. dealloc reg2
  4477. to
  4478. movsX/movzX reg/ref, reg3
  4479. add/sub/or/... reg3/$const, reg3
  4480. }
  4481. begin
  4482. TransferUsedRegs(TmpUsedRegs);
  4483. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4484. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4485. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4486. begin
  4487. { by example:
  4488. movswl %si,%eax movswl %si,%eax p
  4489. decl %eax addl %edx,%eax hp1
  4490. movw %ax,%si movw %ax,%si hp2
  4491. ->
  4492. movswl %si,%eax movswl %si,%eax p
  4493. decw %eax addw %edx,%eax hp1
  4494. movw %ax,%si movw %ax,%si hp2
  4495. }
  4496. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4497. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4498. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4499. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4500. { limit size of constants as well to avoid assembler errors, but
  4501. check opsize to avoid overflow when left shifting the 1 }
  4502. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4503. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4504. {$ifdef x86_64}
  4505. { Be careful of, for example:
  4506. movl %reg1,%reg2
  4507. addl %reg3,%reg2
  4508. movq %reg2,%reg4
  4509. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4510. }
  4511. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4512. begin
  4513. taicpu(hp2).changeopsize(S_L);
  4514. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4515. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4516. end;
  4517. {$endif x86_64}
  4518. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4519. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4520. if taicpu(p).oper[0]^.typ=top_reg then
  4521. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4522. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4523. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4524. {
  4525. ->
  4526. movswl %si,%eax movswl %si,%eax p
  4527. decw %si addw %dx,%si hp1
  4528. movw %ax,%si movw %ax,%si hp2
  4529. }
  4530. case taicpu(hp1).ops of
  4531. 1:
  4532. begin
  4533. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4534. if taicpu(hp1).oper[0]^.typ=top_reg then
  4535. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4536. end;
  4537. 2:
  4538. begin
  4539. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4540. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4541. (taicpu(hp1).opcode<>A_SHL) and
  4542. (taicpu(hp1).opcode<>A_SHR) and
  4543. (taicpu(hp1).opcode<>A_SAR) then
  4544. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4545. end;
  4546. else
  4547. internalerror(2018111801);
  4548. end;
  4549. {
  4550. ->
  4551. decw %si addw %dx,%si p
  4552. }
  4553. RemoveInstruction(hp2);
  4554. end;
  4555. end;
  4556. end;
  4557. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4558. GetNextInstruction(hp1, hp2) and
  4559. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4560. MatchOperand(Taicpu(p).oper[0]^,0) and
  4561. (Taicpu(p).oper[1]^.typ = top_reg) and
  4562. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4563. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4564. { mov reg1,0
  4565. bts reg1,operand1 --> mov reg1,operand2
  4566. or reg1,operand2 bts reg1,operand1}
  4567. begin
  4568. Taicpu(hp2).opcode:=A_MOV;
  4569. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4570. asml.remove(hp1);
  4571. insertllitem(hp2,hp2.next,hp1);
  4572. RemoveCurrentp(p, hp1);
  4573. Result:=true;
  4574. exit;
  4575. end;
  4576. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4577. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4578. GetNextInstruction(hp1, hp2) and
  4579. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4580. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4581. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4582. { change
  4583. mov reg1,reg2
  4584. sub reg3,reg2
  4585. cmp reg3,reg1
  4586. into
  4587. mov reg1,reg2
  4588. sub reg3,reg2
  4589. }
  4590. begin
  4591. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4592. RemoveInstruction(hp2);
  4593. Result:=true;
  4594. exit;
  4595. end;
  4596. {
  4597. mov ref,reg0
  4598. <op> reg0,reg1
  4599. dealloc reg0
  4600. to
  4601. <op> ref,reg1
  4602. }
  4603. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4604. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4605. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4606. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4607. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4608. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4609. begin
  4610. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4611. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4612. RemoveCurrentp(p, hp1);
  4613. Result:=true;
  4614. exit;
  4615. end;
  4616. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4617. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4618. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4619. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4620. begin
  4621. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4622. {$ifdef x86_64}
  4623. { Convert:
  4624. movq x(ref),%reg64
  4625. shrq y,%reg64
  4626. To:
  4627. movl x+4(ref),%reg32
  4628. shrl y-32,%reg32 (Remove if y = 32)
  4629. }
  4630. if (taicpu(p).opsize = S_Q) and
  4631. (taicpu(hp1).opcode = A_SHR) and
  4632. (taicpu(hp1).oper[0]^.val >= 32) then
  4633. begin
  4634. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4635. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4636. { Convert to 32-bit }
  4637. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4638. taicpu(p).opsize := S_L;
  4639. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4640. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4641. if (taicpu(hp1).oper[0]^.val = 32) then
  4642. begin
  4643. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4644. RemoveInstruction(hp1);
  4645. end
  4646. else
  4647. begin
  4648. { This will potentially open up more arithmetic operations since
  4649. the peephole optimizer now has a big hint that only the lower
  4650. 32 bits are currently in use (and opcodes are smaller in size) }
  4651. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4652. taicpu(hp1).opsize := S_L;
  4653. Dec(taicpu(hp1).oper[0]^.val, 32);
  4654. DebugMsg(SPeepholeOptimization + PreMessage +
  4655. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4656. end;
  4657. Result := True;
  4658. Exit;
  4659. end;
  4660. {$endif x86_64}
  4661. { Convert:
  4662. movl x(ref),%reg
  4663. shrl $24,%reg
  4664. To:
  4665. movzbl x+3(ref),%reg
  4666. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4667. Also accept sar instead of shr, but convert to movsx instead of movzx
  4668. }
  4669. if taicpu(hp1).opcode = A_SHR then
  4670. MovUnaligned := A_MOVZX
  4671. else
  4672. MovUnaligned := A_MOVSX;
  4673. NewSize := S_NO;
  4674. NewOffset := 0;
  4675. case taicpu(p).opsize of
  4676. S_B:
  4677. { No valid combinations };
  4678. S_W:
  4679. if (taicpu(hp1).oper[0]^.val = 8) then
  4680. begin
  4681. NewSize := S_BW;
  4682. NewOffset := 1;
  4683. end;
  4684. S_L:
  4685. case taicpu(hp1).oper[0]^.val of
  4686. 16:
  4687. begin
  4688. NewSize := S_WL;
  4689. NewOffset := 2;
  4690. end;
  4691. 24:
  4692. begin
  4693. NewSize := S_BL;
  4694. NewOffset := 3;
  4695. end;
  4696. else
  4697. ;
  4698. end;
  4699. {$ifdef x86_64}
  4700. S_Q:
  4701. case taicpu(hp1).oper[0]^.val of
  4702. 32:
  4703. begin
  4704. if taicpu(hp1).opcode = A_SAR then
  4705. begin
  4706. { 32-bit to 64-bit is a distinct instruction }
  4707. MovUnaligned := A_MOVSXD;
  4708. NewSize := S_LQ;
  4709. NewOffset := 4;
  4710. end
  4711. else
  4712. { Should have been handled by MovShr2Mov above }
  4713. InternalError(2022081811);
  4714. end;
  4715. 48:
  4716. begin
  4717. NewSize := S_WQ;
  4718. NewOffset := 6;
  4719. end;
  4720. 56:
  4721. begin
  4722. NewSize := S_BQ;
  4723. NewOffset := 7;
  4724. end;
  4725. else
  4726. ;
  4727. end;
  4728. {$endif x86_64}
  4729. else
  4730. InternalError(2022081810);
  4731. end;
  4732. if (NewSize <> S_NO) and
  4733. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4734. begin
  4735. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4736. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4737. debug_op2str(MovUnaligned);
  4738. {$ifdef x86_64}
  4739. if MovUnaligned <> A_MOVSXD then
  4740. { Don't add size suffix for MOVSXD }
  4741. {$endif x86_64}
  4742. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4743. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4744. taicpu(p).opcode := MovUnaligned;
  4745. taicpu(p).opsize := NewSize;
  4746. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4747. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4748. RemoveInstruction(hp1);
  4749. Result := True;
  4750. Exit;
  4751. end;
  4752. end;
  4753. { Backward optimisation shared with OptPass2MOV }
  4754. if FuncMov2Func(p, hp1) then
  4755. begin
  4756. Result := True;
  4757. Exit;
  4758. end;
  4759. end;
  4760. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4761. var
  4762. hp1 : tai;
  4763. begin
  4764. Result:=false;
  4765. if taicpu(p).ops <> 2 then
  4766. exit;
  4767. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4768. GetNextInstruction(p,hp1) then
  4769. begin
  4770. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4771. (taicpu(hp1).ops = 2) then
  4772. begin
  4773. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4774. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4775. { movXX reg1, mem1 or movXX mem1, reg1
  4776. movXX mem2, reg2 movXX reg2, mem2}
  4777. begin
  4778. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4779. { movXX reg1, mem1 or movXX mem1, reg1
  4780. movXX mem2, reg1 movXX reg2, mem1}
  4781. begin
  4782. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4783. begin
  4784. { Removes the second statement from
  4785. movXX reg1, mem1/reg2
  4786. movXX mem1/reg2, reg1
  4787. }
  4788. if taicpu(p).oper[0]^.typ=top_reg then
  4789. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4790. { Removes the second statement from
  4791. movXX mem1/reg1, reg2
  4792. movXX reg2, mem1/reg1
  4793. }
  4794. if (taicpu(p).oper[1]^.typ=top_reg) and
  4795. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4796. begin
  4797. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4798. RemoveInstruction(hp1);
  4799. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4800. Result:=true;
  4801. exit;
  4802. end
  4803. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4804. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4805. begin
  4806. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4807. RemoveInstruction(hp1);
  4808. Result:=true;
  4809. exit;
  4810. end;
  4811. end
  4812. end;
  4813. end;
  4814. end;
  4815. end;
  4816. end;
  4817. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4818. var
  4819. hp1 : tai;
  4820. begin
  4821. result:=false;
  4822. { replace
  4823. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4824. MovX %mreg2,%mreg1
  4825. dealloc %mreg2
  4826. by
  4827. <Op>X %mreg2,%mreg1
  4828. ?
  4829. }
  4830. if GetNextInstruction(p,hp1) and
  4831. { we mix single and double opperations here because we assume that the compiler
  4832. generates vmovapd only after double operations and vmovaps only after single operations }
  4833. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4834. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4835. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4836. (taicpu(p).oper[0]^.typ=top_reg) then
  4837. begin
  4838. TransferUsedRegs(TmpUsedRegs);
  4839. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4840. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4841. begin
  4842. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4843. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4844. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4845. RemoveInstruction(hp1);
  4846. result:=true;
  4847. end;
  4848. end;
  4849. end;
  4850. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4851. var
  4852. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4853. JumpLabel, JumpLabel_dist: TAsmLabel;
  4854. FirstValue, SecondValue: TCGInt;
  4855. function OptimizeJump(var InputP: tai): Boolean;
  4856. var
  4857. TempBool: Boolean;
  4858. begin
  4859. Result := False;
  4860. TempBool := True;
  4861. if DoJumpOptimizations(InputP, TempBool) or
  4862. not TempBool then
  4863. begin
  4864. Result := True;
  4865. if Assigned(InputP) then
  4866. begin
  4867. { CollapseZeroDistJump will be set to the label or an align
  4868. before it after the jump if it optimises, whether or not
  4869. the label is live or dead }
  4870. if (InputP.typ = ait_align) or
  4871. (
  4872. (InputP.typ = ait_label) and
  4873. not (tai_label(InputP).labsym.is_used)
  4874. ) then
  4875. GetNextInstruction(InputP, InputP);
  4876. end;
  4877. Exit;
  4878. end;
  4879. end;
  4880. begin
  4881. Result := False;
  4882. if (taicpu(p).oper[0]^.typ = top_const) and
  4883. (taicpu(p).oper[0]^.val <> -1) then
  4884. begin
  4885. { Convert unsigned maximum constants to -1 to aid optimisation }
  4886. case taicpu(p).opsize of
  4887. S_B:
  4888. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4889. begin
  4890. taicpu(p).oper[0]^.val := -1;
  4891. Result := True;
  4892. Exit;
  4893. end;
  4894. S_W:
  4895. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4896. begin
  4897. taicpu(p).oper[0]^.val := -1;
  4898. Result := True;
  4899. Exit;
  4900. end;
  4901. S_L:
  4902. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4903. begin
  4904. taicpu(p).oper[0]^.val := -1;
  4905. Result := True;
  4906. Exit;
  4907. end;
  4908. {$ifdef x86_64}
  4909. S_Q:
  4910. { Storing anything greater than $7FFFFFFF is not possible so do
  4911. nothing };
  4912. {$endif x86_64}
  4913. else
  4914. InternalError(2021121001);
  4915. end;
  4916. end;
  4917. if GetNextInstruction(p, hp1) and
  4918. TrySwapMovCmp(p, hp1) then
  4919. begin
  4920. Result := True;
  4921. Exit;
  4922. end;
  4923. p_label := nil;
  4924. JumpLabel := nil;
  4925. if MatchInstruction(hp1, A_Jcc, []) then
  4926. begin
  4927. if OptimizeJump(hp1) then
  4928. begin
  4929. Result := True;
  4930. if Assigned(hp1) then
  4931. begin
  4932. { CollapseZeroDistJump will be set to the label or an align
  4933. before it after the jump if it optimises, whether or not
  4934. the label is live or dead }
  4935. if (hp1.typ = ait_align) or
  4936. (
  4937. (hp1.typ = ait_label) and
  4938. not (tai_label(hp1).labsym.is_used)
  4939. ) then
  4940. GetNextInstruction(hp1, hp1);
  4941. end;
  4942. TransferUsedRegs(TmpUsedRegs);
  4943. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4944. if not Assigned(hp1) or
  4945. (
  4946. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4947. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4948. ) then
  4949. begin
  4950. { No more conditional jumps; conditional statement is no longer required }
  4951. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4952. RemoveCurrentP(p);
  4953. end;
  4954. Exit;
  4955. end;
  4956. if IsJumpToLabel(taicpu(hp1)) then
  4957. begin
  4958. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4959. if Assigned(JumpLabel) then
  4960. p_label := getlabelwithsym(JumpLabel);
  4961. end;
  4962. end;
  4963. { Search for:
  4964. test $x,(reg/ref)
  4965. jne @lbl1
  4966. test $y,(reg/ref) (same register or reference)
  4967. jne @lbl1
  4968. Change to:
  4969. test $(x or y),(reg/ref)
  4970. jne @lbl1
  4971. (Note, this doesn't work with je instead of jne)
  4972. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4973. Also search for:
  4974. test $x,(reg/ref)
  4975. je @lbl1
  4976. ...
  4977. test $y,(reg/ref)
  4978. je/jne @lbl2
  4979. If (x or y) = x, then the second jump is deterministic
  4980. }
  4981. if (
  4982. (
  4983. (taicpu(p).oper[0]^.typ = top_const) or
  4984. (
  4985. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4986. (taicpu(p).oper[0]^.typ = top_reg) and
  4987. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4988. )
  4989. ) and
  4990. MatchInstruction(hp1, A_JCC, [])
  4991. ) then
  4992. begin
  4993. if (taicpu(p).oper[0]^.typ = top_reg) and
  4994. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4995. FirstValue := -1
  4996. else
  4997. FirstValue := taicpu(p).oper[0]^.val;
  4998. { If we have several test/jne's in a row, it might be the case that
  4999. the second label doesn't go to the same location, but the one
  5000. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5001. so accommodate for this with a while loop.
  5002. }
  5003. hp1_last := hp1;
  5004. while (
  5005. (
  5006. (taicpu(p).oper[1]^.typ = top_reg) and
  5007. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5008. ) or GetNextInstruction(hp1_last, p_dist)
  5009. ) and (p_dist.typ = ait_instruction) do
  5010. begin
  5011. if (
  5012. (
  5013. (taicpu(p_dist).opcode = A_TEST) and
  5014. (
  5015. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5016. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5017. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5018. )
  5019. ) or
  5020. (
  5021. { cmp 0,%reg = test %reg,%reg }
  5022. (taicpu(p_dist).opcode = A_CMP) and
  5023. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5024. )
  5025. ) and
  5026. { Make sure the destination operands are actually the same }
  5027. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5028. GetNextInstruction(p_dist, hp1_dist) and
  5029. MatchInstruction(hp1_dist, A_JCC, []) then
  5030. begin
  5031. if OptimizeJump(hp1_dist) then
  5032. begin
  5033. Result := True;
  5034. Exit;
  5035. end;
  5036. if
  5037. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5038. (
  5039. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5040. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5041. ) then
  5042. SecondValue := -1
  5043. else
  5044. SecondValue := taicpu(p_dist).oper[0]^.val;
  5045. { If both of the TEST constants are identical, delete the
  5046. second TEST that is unnecessary (be careful though, just
  5047. in case the flags are modified in between) }
  5048. if (FirstValue = SecondValue) then
  5049. begin
  5050. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5051. begin
  5052. { Since the second jump's condition is a subset of the first, we
  5053. know it will never branch because the first jump dominates it.
  5054. Get it out of the way now rather than wait for the jump
  5055. optimisations for a speed boost. }
  5056. if IsJumpToLabel(taicpu(hp1_dist)) then
  5057. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5058. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5059. RemoveInstruction(hp1_dist);
  5060. Result := True;
  5061. end
  5062. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5063. begin
  5064. { If the inverse of the first condition is a subset of the second,
  5065. the second one will definitely branch if the first one doesn't }
  5066. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5067. { We can remove the TEST instruction too }
  5068. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5069. RemoveInstruction(p_dist);
  5070. MakeUnconditional(taicpu(hp1_dist));
  5071. RemoveDeadCodeAfterJump(hp1_dist);
  5072. { Since the jump is now unconditional, we can't
  5073. continue any further with this particular
  5074. optimisation. The original TEST is still intact
  5075. though, so there might be something else we can
  5076. do }
  5077. Include(OptsToCheck, aoc_ForceNewIteration);
  5078. Break;
  5079. end;
  5080. if Result or
  5081. { If a jump wasn't removed or made unconditional, only
  5082. remove the identical TEST instruction if the flags
  5083. weren't modified }
  5084. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5085. begin
  5086. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5087. RemoveInstruction(p_dist);
  5088. { If the jump was removed or made unconditional, we
  5089. don't need to allocate NR_DEFAULTFLAGS over the
  5090. entire range }
  5091. if not Result then
  5092. begin
  5093. { Mark the flags as 'in use' over the entire range }
  5094. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5095. { Speed gain - continue search from the Jcc instruction }
  5096. hp1_last := hp1_dist;
  5097. { Only the TEST instruction was removed, and the
  5098. original was unchanged, so we can safely do
  5099. another iteration of the while loop }
  5100. Include(OptsToCheck, aoc_ForceNewIteration);
  5101. Continue;
  5102. end;
  5103. Exit;
  5104. end;
  5105. end;
  5106. hp1_last := nil;
  5107. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5108. (
  5109. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5110. { Always adjacent under -O2 and under }
  5111. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5112. (
  5113. GetNextInstruction(hp1, hp1_last) and
  5114. (hp1_last = p_dist)
  5115. )
  5116. ) and
  5117. (
  5118. (
  5119. { Test the following variant:
  5120. test $x,(reg/ref)
  5121. jne @lbl1
  5122. test $y,(reg/ref)
  5123. je @lbl2
  5124. @lbl1:
  5125. Becomes:
  5126. test $(x or y),(reg/ref)
  5127. je @lbl2
  5128. @lbl1: (may become a dead label)
  5129. }
  5130. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5131. GetNextInstruction(hp1_dist, hp1_last) and
  5132. (hp1_last = p_label)
  5133. ) or
  5134. (
  5135. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5136. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5137. then the second jump will never branch, so it can also be
  5138. removed regardless of where it goes }
  5139. (
  5140. (FirstValue = -1) or
  5141. (SecondValue = -1) or
  5142. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5143. )
  5144. )
  5145. ) then
  5146. begin
  5147. { Same jump location... can be a register since nothing's changed }
  5148. { If any of the entries are equivalent to test %reg,%reg, then the
  5149. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5150. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5151. if (hp1_last = p_label) then
  5152. begin
  5153. { Variant }
  5154. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5155. RemoveInstruction(p_dist);
  5156. if Assigned(JumpLabel) then
  5157. JumpLabel.decrefs;
  5158. RemoveInstruction(hp1);
  5159. end
  5160. else
  5161. begin
  5162. { Only remove the second test if no jumps or other conditional instructions follow }
  5163. TransferUsedRegs(TmpUsedRegs);
  5164. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5165. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5166. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5167. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5168. begin
  5169. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5170. RemoveInstruction(p_dist);
  5171. { Remove the first jump, not the second, to keep
  5172. any register deallocations between the second
  5173. TEST/JNE pair in the same place. Aids future
  5174. optimisation. }
  5175. if Assigned(JumpLabel) then
  5176. JumpLabel.decrefs;
  5177. RemoveInstruction(hp1);
  5178. end
  5179. else
  5180. begin
  5181. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5182. if IsJumpToLabel(taicpu(hp1_dist)) then
  5183. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5184. { Remove second jump in this instance }
  5185. RemoveInstruction(hp1_dist);
  5186. end;
  5187. end;
  5188. Result := True;
  5189. Exit;
  5190. end;
  5191. end;
  5192. if { If -O2 and under, it may stop on any old instruction }
  5193. (cs_opt_level3 in current_settings.optimizerswitches) and
  5194. (taicpu(p).oper[1]^.typ = top_reg) and
  5195. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5196. begin
  5197. hp1_last := p_dist;
  5198. Continue;
  5199. end;
  5200. Break;
  5201. end;
  5202. end;
  5203. { Search for:
  5204. test %reg,%reg
  5205. j(c1) @lbl1
  5206. ...
  5207. @lbl:
  5208. test %reg,%reg (same register)
  5209. j(c2) @lbl2
  5210. If c2 is a subset of c1, change to:
  5211. test %reg,%reg
  5212. j(c1) @lbl2
  5213. (@lbl1 may become a dead label as a result)
  5214. }
  5215. if (taicpu(p).oper[1]^.typ = top_reg) and
  5216. (taicpu(p).oper[0]^.typ = top_reg) and
  5217. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5218. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5219. Assigned(p_label) and
  5220. GetNextInstruction(p_label, p_dist) and
  5221. MatchInstruction(p_dist, A_TEST, []) and
  5222. { It's fine if the second test uses smaller sub-registers }
  5223. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5224. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5225. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5226. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5227. GetNextInstruction(p_dist, hp1_dist) and
  5228. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5229. begin
  5230. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5231. if JumpLabel = JumpLabel_dist then
  5232. { This is an infinite loop }
  5233. Exit;
  5234. { Best optimisation when the first condition is a subset (or equal) of the second }
  5235. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5236. begin
  5237. { Any registers used here will already be allocated }
  5238. if Assigned(JumpLabel) then
  5239. JumpLabel.DecRefs;
  5240. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5241. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5242. Result := True;
  5243. Exit;
  5244. end;
  5245. end;
  5246. end;
  5247. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5248. var
  5249. hp1, hp2: tai;
  5250. ActiveReg: TRegister;
  5251. OldOffset: asizeint;
  5252. ThisConst: TCGInt;
  5253. function RegDeallocated: Boolean;
  5254. begin
  5255. TransferUsedRegs(TmpUsedRegs);
  5256. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5257. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5258. end;
  5259. begin
  5260. result:=false;
  5261. hp1 := nil;
  5262. { replace
  5263. addX const,%reg1
  5264. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5265. dealloc %reg1
  5266. by
  5267. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5268. }
  5269. if MatchOpType(taicpu(p),top_const,top_reg) then
  5270. begin
  5271. ActiveReg := taicpu(p).oper[1]^.reg;
  5272. { Ensures the entire register was updated }
  5273. if (taicpu(p).opsize >= S_L) and
  5274. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5275. MatchInstruction(hp1,A_LEA,[]) and
  5276. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5277. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5278. (
  5279. { Cover the case where the register in the reference is also the destination register }
  5280. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5281. (
  5282. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5283. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5284. RegDeallocated
  5285. )
  5286. ) then
  5287. begin
  5288. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5289. {$push}
  5290. {$R-}{$Q-}
  5291. { Explicitly disable overflow checking for these offset calculation
  5292. as those do not matter for the final result }
  5293. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5294. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5295. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5296. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5297. {$pop}
  5298. {$ifdef x86_64}
  5299. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5300. begin
  5301. { Overflow; abort }
  5302. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5303. end
  5304. else
  5305. {$endif x86_64}
  5306. begin
  5307. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5308. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5309. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5310. RemoveCurrentP(p, hp1)
  5311. else
  5312. RemoveCurrentP(p);
  5313. result:=true;
  5314. Exit;
  5315. end;
  5316. end;
  5317. if (
  5318. { Save calling GetNextInstructionUsingReg again }
  5319. Assigned(hp1) or
  5320. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5321. ) and
  5322. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5323. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5324. begin
  5325. if taicpu(hp1).oper[0]^.typ = top_const then
  5326. begin
  5327. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5328. if taicpu(hp1).opcode = A_ADD then
  5329. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5330. else
  5331. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5332. Result := True;
  5333. { Handle any overflows }
  5334. case taicpu(p).opsize of
  5335. S_B:
  5336. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5337. S_W:
  5338. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5339. S_L:
  5340. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5341. {$ifdef x86_64}
  5342. S_Q:
  5343. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5344. { Overflow; abort }
  5345. Result := False
  5346. else
  5347. taicpu(p).oper[0]^.val := ThisConst;
  5348. {$endif x86_64}
  5349. else
  5350. InternalError(2021102610);
  5351. end;
  5352. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5353. if Result then
  5354. begin
  5355. if (taicpu(p).oper[0]^.val < 0) and
  5356. (
  5357. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5358. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5359. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5360. ) then
  5361. begin
  5362. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5363. taicpu(p).opcode := A_SUB;
  5364. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5365. end
  5366. else
  5367. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5368. RemoveInstruction(hp1);
  5369. end;
  5370. end
  5371. else
  5372. begin
  5373. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5374. TransferUsedRegs(TmpUsedRegs);
  5375. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5376. hp2 := p;
  5377. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5378. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5379. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5380. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5381. begin
  5382. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5383. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5384. Asml.Remove(p);
  5385. Asml.InsertAfter(p, hp1);
  5386. p := hp1;
  5387. Result := True;
  5388. Exit;
  5389. end;
  5390. end;
  5391. end;
  5392. if DoArithCombineOpt(p) then
  5393. Result:=true;
  5394. end;
  5395. end;
  5396. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5397. var
  5398. hp1, hp2: tai;
  5399. ref: Integer;
  5400. saveref: treference;
  5401. offsetcalc: Int64;
  5402. TempReg: TRegister;
  5403. Multiple: TCGInt;
  5404. Adjacent, IntermediateRegDiscarded: Boolean;
  5405. begin
  5406. Result:=false;
  5407. { play save and throw an error if LEA uses a seg register prefix,
  5408. this is most likely an error somewhere else }
  5409. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5410. internalerror(2022022001);
  5411. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5412. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5413. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5414. (
  5415. { do not mess with leas accessing the stack pointer
  5416. unless it's a null operation }
  5417. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5418. (
  5419. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5420. (taicpu(p).oper[0]^.ref^.offset = 0)
  5421. )
  5422. ) and
  5423. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5424. begin
  5425. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5426. begin
  5427. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5428. begin
  5429. taicpu(p).opcode := A_MOV;
  5430. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5431. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5432. end
  5433. else
  5434. begin
  5435. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5436. RemoveCurrentP(p);
  5437. end;
  5438. Result:=true;
  5439. exit;
  5440. end
  5441. else if (
  5442. { continue to use lea to adjust the stack pointer,
  5443. it is the recommended way, but only if not optimizing for size }
  5444. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5445. (cs_opt_size in current_settings.optimizerswitches)
  5446. ) and
  5447. { If the flags register is in use, don't change the instruction
  5448. to an ADD otherwise this will scramble the flags. [Kit] }
  5449. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5450. ConvertLEA(taicpu(p)) then
  5451. begin
  5452. Result:=true;
  5453. exit;
  5454. end;
  5455. end;
  5456. { Don't optimise if the stack or frame pointer is the destination register }
  5457. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5458. Exit;
  5459. if GetNextInstruction(p,hp1) and
  5460. (hp1.typ=ait_instruction) then
  5461. begin
  5462. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5463. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5464. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5465. begin
  5466. TransferUsedRegs(TmpUsedRegs);
  5467. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5468. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5469. begin
  5470. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5471. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5472. RemoveInstruction(hp1);
  5473. result:=true;
  5474. exit;
  5475. end;
  5476. end;
  5477. { changes
  5478. lea <ref1>, reg1
  5479. <op> ...,<ref. with reg1>,...
  5480. to
  5481. <op> ...,<ref1>,... }
  5482. { find a reference which uses reg1 }
  5483. 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
  5484. ref:=0
  5485. 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
  5486. ref:=1
  5487. else
  5488. ref:=-1;
  5489. if (ref<>-1) and
  5490. { reg1 must be either the base or the index }
  5491. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5492. begin
  5493. { reg1 can be removed from the reference }
  5494. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5495. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5496. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5497. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5498. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5499. else
  5500. Internalerror(2019111201);
  5501. { check if the can insert all data of the lea into the second instruction }
  5502. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5503. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5504. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5505. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5506. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5507. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5508. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5509. {$ifdef x86_64}
  5510. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5511. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5512. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5513. )
  5514. {$endif x86_64}
  5515. then
  5516. begin
  5517. { reg1 might not used by the second instruction after it is remove from the reference }
  5518. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5519. begin
  5520. TransferUsedRegs(TmpUsedRegs);
  5521. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5522. { reg1 is not updated so it might not be used afterwards }
  5523. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5524. begin
  5525. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5526. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5527. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5528. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5529. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5530. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5531. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5532. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5533. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5534. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5535. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5536. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5537. RemoveCurrentP(p, hp1);
  5538. result:=true;
  5539. exit;
  5540. end
  5541. end;
  5542. end;
  5543. { recover }
  5544. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5545. end;
  5546. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5547. if Adjacent or
  5548. { Check further ahead (up to 2 instructions ahead for -O2) }
  5549. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5550. begin
  5551. { Check common LEA/LEA conditions }
  5552. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5553. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5554. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5555. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5556. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5557. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5558. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5559. (
  5560. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5561. calling it (since it calls GetNextInstruction) }
  5562. Adjacent or
  5563. (
  5564. (
  5565. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5566. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5567. ) and (
  5568. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5569. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5570. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5571. )
  5572. )
  5573. ) then
  5574. begin
  5575. TransferUsedRegs(TmpUsedRegs);
  5576. hp2 := p;
  5577. repeat
  5578. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5579. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5580. IntermediateRegDiscarded :=
  5581. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5582. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5583. { changes
  5584. lea offset1(regX,scale), reg1
  5585. lea offset2(reg1,reg1), reg2
  5586. to
  5587. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5588. and
  5589. lea offset1(regX,scale1), reg1
  5590. lea offset2(reg1,scale2), reg2
  5591. to
  5592. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5593. and
  5594. lea offset1(regX,scale1), reg1
  5595. lea offset2(reg3,reg1,scale2), reg2
  5596. to
  5597. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5598. ... so long as the final scale does not exceed 8
  5599. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5600. }
  5601. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5602. (
  5603. { Don't optimise if size is a concern and the intermediate register remains in use }
  5604. IntermediateRegDiscarded or
  5605. not (cs_opt_size in current_settings.optimizerswitches)
  5606. ) and
  5607. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5608. (
  5609. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5610. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5611. ) and (
  5612. (
  5613. { lea (reg1,scale2), reg2 variant }
  5614. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5615. (
  5616. Adjacent or
  5617. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5618. ) and
  5619. (
  5620. (
  5621. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5622. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5623. ) or (
  5624. { lea (regX,regX), reg1 variant }
  5625. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5626. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5627. )
  5628. )
  5629. ) or (
  5630. { lea (reg1,reg1), reg1 variant }
  5631. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5632. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5633. )
  5634. ) then
  5635. begin
  5636. { Make everything homogeneous to make calculations easier }
  5637. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5638. begin
  5639. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5640. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5641. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5642. else
  5643. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5644. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5645. end;
  5646. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5647. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5648. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5649. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5650. begin
  5651. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5652. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5653. begin
  5654. { Put the register to change in the index register }
  5655. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5656. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5657. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5658. end;
  5659. { Change lea (reg,reg) to lea(,reg,2) }
  5660. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5661. begin
  5662. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5663. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5664. end;
  5665. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5666. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5667. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5668. { Just to prevent miscalculations }
  5669. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5670. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5671. else
  5672. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5673. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5674. if IntermediateRegDiscarded then
  5675. begin
  5676. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5677. RemoveCurrentP(p);
  5678. end
  5679. else
  5680. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5681. result:=true;
  5682. exit;
  5683. end;
  5684. end;
  5685. { changes
  5686. lea offset1(regX), reg1
  5687. lea offset2(reg1), reg2
  5688. to
  5689. lea offset1+offset2(regX), reg2 }
  5690. if (
  5691. { Don't optimise if size is a concern and the intermediate register remains in use }
  5692. IntermediateRegDiscarded or
  5693. not (cs_opt_size in current_settings.optimizerswitches)
  5694. ) and
  5695. (
  5696. (
  5697. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5698. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5699. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5700. ) or (
  5701. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5702. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5703. (
  5704. (
  5705. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5706. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5707. ) or (
  5708. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5709. (
  5710. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5711. (
  5712. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5713. (
  5714. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5715. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5716. )
  5717. )
  5718. )
  5719. )
  5720. )
  5721. )
  5722. ) then
  5723. begin
  5724. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5725. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5726. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5727. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5728. begin
  5729. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5730. begin
  5731. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5732. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5733. { if the register is used as index and base, we have to increase for base as well
  5734. and adapt base }
  5735. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5736. begin
  5737. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5738. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5739. end;
  5740. end
  5741. else
  5742. begin
  5743. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5744. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5745. end;
  5746. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5747. begin
  5748. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5749. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5750. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  5751. { Catch the situation where the base = index
  5752. and treat this as *2. The scalefactor of
  5753. p will be 0 or 1 due to the conditional
  5754. checks above. Fixes i40647 }
  5755. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  5756. else
  5757. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  5758. end;
  5759. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5760. if IntermediateRegDiscarded then
  5761. begin
  5762. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5763. RemoveCurrentP(p);
  5764. end
  5765. else
  5766. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5767. result:=true;
  5768. exit;
  5769. end;
  5770. end;
  5771. end;
  5772. { Change:
  5773. leal/q $x(%reg1),%reg2
  5774. ...
  5775. shll/q $y,%reg2
  5776. To:
  5777. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5778. }
  5779. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5780. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5781. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5782. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5783. (taicpu(hp1).oper[0]^.val <= 3) then
  5784. begin
  5785. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5786. TransferUsedRegs(TmpUsedRegs);
  5787. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5788. if
  5789. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5790. (this works even if scalefactor is zero) }
  5791. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5792. { Ensure offset doesn't go out of bounds }
  5793. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5794. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5795. (
  5796. (
  5797. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5798. (
  5799. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5800. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5801. (
  5802. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5803. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5804. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5805. )
  5806. )
  5807. ) or (
  5808. (
  5809. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5810. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5811. ) and
  5812. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5813. )
  5814. ) then
  5815. begin
  5816. repeat
  5817. with taicpu(p).oper[0]^.ref^ do
  5818. begin
  5819. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5820. if index = base then
  5821. begin
  5822. if Multiple > 4 then
  5823. { Optimisation will no longer work because resultant
  5824. scale factor will exceed 8 }
  5825. Break;
  5826. base := NR_NO;
  5827. scalefactor := 2;
  5828. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5829. end
  5830. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5831. begin
  5832. { Scale factor only works on the index register }
  5833. index := base;
  5834. base := NR_NO;
  5835. end;
  5836. { For safety }
  5837. if scalefactor <= 1 then
  5838. begin
  5839. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5840. scalefactor := Multiple;
  5841. end
  5842. else
  5843. begin
  5844. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5845. scalefactor := scalefactor * Multiple;
  5846. end;
  5847. offset := offset * Multiple;
  5848. end;
  5849. RemoveInstruction(hp1);
  5850. Result := True;
  5851. Exit;
  5852. { This repeat..until loop exists for the benefit of Break }
  5853. until True;
  5854. end;
  5855. end;
  5856. end;
  5857. end;
  5858. end;
  5859. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5860. var
  5861. hp1 : tai;
  5862. SubInstr: Boolean;
  5863. ThisConst: TCGInt;
  5864. const
  5865. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5866. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5867. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5868. begin
  5869. Result := False;
  5870. if taicpu(p).oper[0]^.typ <> top_const then
  5871. { Should have been confirmed before calling }
  5872. InternalError(2021102601);
  5873. SubInstr := (taicpu(p).opcode = A_SUB);
  5874. if GetLastInstruction(p, hp1) and
  5875. (hp1.typ = ait_instruction) and
  5876. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5877. begin
  5878. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5879. { Bad size }
  5880. InternalError(2022042001);
  5881. case taicpu(hp1).opcode Of
  5882. A_INC:
  5883. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5884. begin
  5885. if SubInstr then
  5886. ThisConst := taicpu(p).oper[0]^.val - 1
  5887. else
  5888. ThisConst := taicpu(p).oper[0]^.val + 1;
  5889. end
  5890. else
  5891. Exit;
  5892. A_DEC:
  5893. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5894. begin
  5895. if SubInstr then
  5896. ThisConst := taicpu(p).oper[0]^.val + 1
  5897. else
  5898. ThisConst := taicpu(p).oper[0]^.val - 1;
  5899. end
  5900. else
  5901. Exit;
  5902. A_SUB:
  5903. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5904. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5905. begin
  5906. if SubInstr then
  5907. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5908. else
  5909. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5910. end
  5911. else
  5912. Exit;
  5913. A_ADD:
  5914. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5915. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5916. begin
  5917. if SubInstr then
  5918. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5919. else
  5920. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5921. end
  5922. else
  5923. Exit;
  5924. else
  5925. Exit;
  5926. end;
  5927. { Check that the values are in range }
  5928. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5929. { Overflow; abort }
  5930. Exit;
  5931. if (ThisConst = 0) then
  5932. begin
  5933. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5934. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5935. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5936. RemoveInstruction(hp1);
  5937. hp1 := tai(p.next);
  5938. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5939. if not GetLastInstruction(hp1, p) then
  5940. p := hp1;
  5941. end
  5942. else
  5943. begin
  5944. if taicpu(hp1).opercnt=1 then
  5945. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5946. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5947. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5948. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5949. else
  5950. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5951. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5952. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5953. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5954. RemoveInstruction(hp1);
  5955. taicpu(p).loadconst(0, ThisConst);
  5956. end;
  5957. Result := True;
  5958. end;
  5959. end;
  5960. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  5961. begin
  5962. Result := False;
  5963. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5964. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5965. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5966. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5967. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5968. (
  5969. (
  5970. (taicpu(hp1).opcode = A_TEST)
  5971. ) or (
  5972. (taicpu(hp1).opcode = A_CMP) and
  5973. { A sanity check more than anything }
  5974. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5975. )
  5976. ) then
  5977. begin
  5978. { change
  5979. mov mem, %reg
  5980. ...
  5981. cmp/test x, %reg / test %reg,%reg
  5982. (reg deallocated)
  5983. to
  5984. cmp/test x, mem / cmp 0, mem
  5985. }
  5986. TransferUsedRegs(TmpUsedRegs);
  5987. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5988. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5989. begin
  5990. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5991. if (taicpu(hp1).opcode = A_TEST) and
  5992. (
  5993. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5994. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5995. ) then
  5996. begin
  5997. taicpu(hp1).opcode := A_CMP;
  5998. taicpu(hp1).loadconst(0, 0);
  5999. end;
  6000. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6001. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6002. RemoveCurrentP(p);
  6003. if (p <> hp1) then
  6004. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6005. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6006. { Make sure the flags are allocated across the CMP instruction }
  6007. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6008. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6009. Result := True;
  6010. Exit;
  6011. end;
  6012. end;
  6013. end;
  6014. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6015. var
  6016. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6017. ThisReg, SecondReg: TRegister;
  6018. JumpLoc: TAsmLabel;
  6019. NewSize: TOpSize;
  6020. begin
  6021. Result := False;
  6022. {
  6023. Convert:
  6024. j<c> .L1
  6025. .L2:
  6026. mov 1,reg
  6027. jmp .L3 (or ret, although it might not be a RET yet)
  6028. .L1:
  6029. mov 0,reg
  6030. jmp .L3 (or ret)
  6031. ( As long as .L3 <> .L1 or .L2)
  6032. To:
  6033. mov 0,reg
  6034. set<not(c)> reg
  6035. jmp .L3 (or ret)
  6036. .L2:
  6037. mov 1,reg
  6038. jmp .L3 (or ret)
  6039. .L1:
  6040. mov 0,reg
  6041. jmp .L3 (or ret)
  6042. }
  6043. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6044. Exit;
  6045. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6046. if GetNextInstruction(hp_label, hp2) and
  6047. MatchInstruction(hp2,A_MOV,[]) and
  6048. (taicpu(hp2).oper[0]^.typ = top_const) and
  6049. (
  6050. (
  6051. (taicpu(hp2).oper[1]^.typ = top_reg)
  6052. {$ifdef i386}
  6053. { Under i386, ESI, EDI, EBP and ESP
  6054. don't have an 8-bit representation }
  6055. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6056. {$endif i386}
  6057. ) or (
  6058. {$ifdef i386}
  6059. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6060. {$endif i386}
  6061. (taicpu(hp2).opsize = S_B)
  6062. )
  6063. ) and
  6064. GetNextInstruction(hp2, hp3) and
  6065. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6066. (
  6067. (taicpu(hp3).opcode=A_RET) or
  6068. (
  6069. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6070. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6071. )
  6072. ) and
  6073. GetNextInstruction(hp3, hp4) and
  6074. (hp4.typ=ait_label) and
  6075. (tai_label(hp4).labsym=JumpLoc) and
  6076. (
  6077. not (cs_opt_size in current_settings.optimizerswitches) or
  6078. { If the initial jump is the label's only reference, then it will
  6079. become a dead label if the other conditions are met and hence
  6080. remove at least 2 instructions, including a jump }
  6081. (JumpLoc.getrefs = 1)
  6082. ) and
  6083. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6084. that will be optimised out }
  6085. GetNextInstruction(hp4, hp5) and
  6086. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6087. (taicpu(hp5).oper[0]^.typ = top_const) and
  6088. (
  6089. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6090. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6091. ) and
  6092. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6093. GetNextInstruction(hp5,hp6) and
  6094. (
  6095. (hp6.typ<>ait_label) or
  6096. SkipLabels(hp6, hp6)
  6097. ) and
  6098. (hp6.typ=ait_instruction) then
  6099. begin
  6100. { First, let's look at the two jumps that are hp3 and hp6 }
  6101. if not
  6102. (
  6103. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6104. (
  6105. (taicpu(hp6).opcode=A_RET) or
  6106. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6107. )
  6108. ) then
  6109. { If condition is False, then the JMP/RET instructions matched conventionally }
  6110. begin
  6111. { See if one of the jumps can be instantly converted into a RET }
  6112. if (taicpu(hp3).opcode=A_JMP) then
  6113. begin
  6114. { Reuse hp5 }
  6115. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6116. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  6117. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  6118. Exit;
  6119. if MatchInstruction(hp5, A_RET, []) then
  6120. begin
  6121. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6122. ConvertJumpToRET(hp3, hp5);
  6123. Result := True;
  6124. end
  6125. else
  6126. Exit;
  6127. end;
  6128. if (taicpu(hp6).opcode=A_JMP) then
  6129. begin
  6130. { Reuse hp5 }
  6131. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6132. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6133. Exit;
  6134. if MatchInstruction(hp5, A_RET, []) then
  6135. begin
  6136. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6137. ConvertJumpToRET(hp6, hp5);
  6138. Result := True;
  6139. end
  6140. else
  6141. Exit;
  6142. end;
  6143. if not
  6144. (
  6145. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6146. (
  6147. (taicpu(hp6).opcode=A_RET) or
  6148. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6149. )
  6150. ) then
  6151. { Still doesn't match }
  6152. Exit;
  6153. end;
  6154. if (taicpu(hp2).oper[0]^.val = 1) then
  6155. begin
  6156. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6157. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6158. end
  6159. else
  6160. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6161. if taicpu(hp2).opsize=S_B then
  6162. begin
  6163. if taicpu(hp2).oper[1]^.typ = top_reg then
  6164. begin
  6165. SecondReg := taicpu(hp2).oper[1]^.reg;
  6166. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6167. end
  6168. else
  6169. begin
  6170. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6171. SecondReg := NR_NO;
  6172. end;
  6173. hp_pos := p;
  6174. hp_allocstart := hp4;
  6175. end
  6176. else
  6177. begin
  6178. { Will be a register because the size can't be S_B otherwise }
  6179. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6180. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6181. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6182. if (cs_opt_size in current_settings.optimizerswitches) then
  6183. begin
  6184. { Favour using MOVZX when optimising for size }
  6185. case taicpu(hp2).opsize of
  6186. S_W:
  6187. NewSize := S_BW;
  6188. S_L:
  6189. NewSize := S_BL;
  6190. {$ifdef x86_64}
  6191. S_Q:
  6192. begin
  6193. NewSize := S_BL;
  6194. { Will implicitly zero-extend to 64-bit }
  6195. setsubreg(SecondReg, R_SUBD);
  6196. end;
  6197. {$endif x86_64}
  6198. else
  6199. InternalError(2022101301);
  6200. end;
  6201. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6202. { Inserting it right before p will guarantee that the flags are also tracked }
  6203. Asml.InsertBefore(hp5, p);
  6204. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6205. hp_pos := hp5;
  6206. hp_allocstart := hp4;
  6207. end
  6208. else
  6209. begin
  6210. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6211. { Inserting it right before p will guarantee that the flags are also tracked }
  6212. Asml.InsertBefore(hp5, p);
  6213. hp_pos := p;
  6214. hp_allocstart := hp5;
  6215. end;
  6216. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6217. end;
  6218. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6219. taicpu(hp4).condition := taicpu(p).condition;
  6220. asml.InsertBefore(hp4, hp_pos);
  6221. if taicpu(hp3).is_jmp then
  6222. begin
  6223. JumpLoc.decrefs;
  6224. MakeUnconditional(taicpu(p));
  6225. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6226. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6227. end
  6228. else
  6229. ConvertJumpToRET(p, hp3);
  6230. if SecondReg <> NR_NO then
  6231. { Ensure the destination register is allocated over this region }
  6232. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6233. if (JumpLoc.getrefs = 0) then
  6234. RemoveDeadCodeAfterJump(hp3);
  6235. Result:=true;
  6236. exit;
  6237. end;
  6238. end;
  6239. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6240. var
  6241. hp1, hp2: tai;
  6242. ActiveReg: TRegister;
  6243. OldOffset: asizeint;
  6244. ThisConst: TCGInt;
  6245. function RegDeallocated: Boolean;
  6246. begin
  6247. TransferUsedRegs(TmpUsedRegs);
  6248. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6249. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6250. end;
  6251. begin
  6252. Result:=false;
  6253. hp1 := nil;
  6254. { replace
  6255. subX const,%reg1
  6256. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6257. dealloc %reg1
  6258. by
  6259. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6260. }
  6261. if MatchOpType(taicpu(p),top_const,top_reg) then
  6262. begin
  6263. ActiveReg := taicpu(p).oper[1]^.reg;
  6264. { Ensures the entire register was updated }
  6265. if (taicpu(p).opsize >= S_L) and
  6266. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6267. MatchInstruction(hp1,A_LEA,[]) and
  6268. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6269. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6270. (
  6271. { Cover the case where the register in the reference is also the destination register }
  6272. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6273. (
  6274. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6275. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6276. RegDeallocated
  6277. )
  6278. ) then
  6279. begin
  6280. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6281. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6282. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6283. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6284. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6285. {$ifdef x86_64}
  6286. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6287. begin
  6288. { Overflow; abort }
  6289. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6290. end
  6291. else
  6292. {$endif x86_64}
  6293. begin
  6294. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6295. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6296. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6297. RemoveCurrentP(p, hp1)
  6298. else
  6299. RemoveCurrentP(p);
  6300. result:=true;
  6301. Exit;
  6302. end;
  6303. end;
  6304. if (
  6305. { Save calling GetNextInstructionUsingReg again }
  6306. Assigned(hp1) or
  6307. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6308. ) and
  6309. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6310. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6311. begin
  6312. if taicpu(hp1).oper[0]^.typ = top_const then
  6313. begin
  6314. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6315. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6316. Result := True;
  6317. { Handle any overflows }
  6318. case taicpu(p).opsize of
  6319. S_B:
  6320. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6321. S_W:
  6322. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6323. S_L:
  6324. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6325. {$ifdef x86_64}
  6326. S_Q:
  6327. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6328. { Overflow; abort }
  6329. Result := False
  6330. else
  6331. taicpu(p).oper[0]^.val := ThisConst;
  6332. {$endif x86_64}
  6333. else
  6334. InternalError(2021102611);
  6335. end;
  6336. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6337. if Result then
  6338. begin
  6339. if (taicpu(p).oper[0]^.val < 0) and
  6340. (
  6341. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6342. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6343. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6344. ) then
  6345. begin
  6346. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6347. taicpu(p).opcode := A_SUB;
  6348. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6349. end
  6350. else
  6351. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6352. RemoveInstruction(hp1);
  6353. end;
  6354. end
  6355. else
  6356. begin
  6357. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6358. TransferUsedRegs(TmpUsedRegs);
  6359. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6360. hp2 := p;
  6361. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6362. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6363. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6364. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6365. begin
  6366. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6367. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6368. Asml.Remove(p);
  6369. Asml.InsertAfter(p, hp1);
  6370. p := hp1;
  6371. Result := True;
  6372. Exit;
  6373. end;
  6374. end;
  6375. end;
  6376. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6377. { * change "sub/add const1, reg" or "dec reg" followed by
  6378. "sub const2, reg" to one "sub ..., reg" }
  6379. {$ifdef i386}
  6380. if (taicpu(p).oper[0]^.val = 2) and
  6381. (ActiveReg = NR_ESP) and
  6382. { Don't do the sub/push optimization if the sub }
  6383. { comes from setting up the stack frame (JM) }
  6384. (not(GetLastInstruction(p,hp1)) or
  6385. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6386. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6387. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6388. begin
  6389. hp1 := tai(p.next);
  6390. while Assigned(hp1) and
  6391. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6392. not RegReadByInstruction(NR_ESP,hp1) and
  6393. not RegModifiedByInstruction(NR_ESP,hp1) do
  6394. hp1 := tai(hp1.next);
  6395. if Assigned(hp1) and
  6396. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6397. begin
  6398. taicpu(hp1).changeopsize(S_L);
  6399. if taicpu(hp1).oper[0]^.typ=top_reg then
  6400. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6401. hp1 := tai(p.next);
  6402. RemoveCurrentp(p, hp1);
  6403. Result:=true;
  6404. exit;
  6405. end;
  6406. end;
  6407. {$endif i386}
  6408. if DoArithCombineOpt(p) then
  6409. Result:=true;
  6410. end;
  6411. end;
  6412. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6413. var
  6414. TmpBool1,TmpBool2 : Boolean;
  6415. tmpref : treference;
  6416. hp1,hp2: tai;
  6417. mask, shiftval: tcgint;
  6418. begin
  6419. Result:=false;
  6420. { All these optimisations work on "shl/sal const,%reg" }
  6421. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6422. Exit;
  6423. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6424. (taicpu(p).oper[0]^.val <= 3) then
  6425. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6426. begin
  6427. { should we check the next instruction? }
  6428. TmpBool1 := True;
  6429. { have we found an add/sub which could be
  6430. integrated in the lea? }
  6431. TmpBool2 := False;
  6432. reference_reset(tmpref,2,[]);
  6433. TmpRef.index := taicpu(p).oper[1]^.reg;
  6434. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6435. while TmpBool1 and
  6436. GetNextInstruction(p, hp1) and
  6437. (tai(hp1).typ = ait_instruction) and
  6438. ((((taicpu(hp1).opcode = A_ADD) or
  6439. (taicpu(hp1).opcode = A_SUB)) and
  6440. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6441. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6442. (((taicpu(hp1).opcode = A_INC) or
  6443. (taicpu(hp1).opcode = A_DEC)) and
  6444. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6445. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6446. ((taicpu(hp1).opcode = A_LEA) and
  6447. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6448. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6449. (not GetNextInstruction(hp1,hp2) or
  6450. not instrReadsFlags(hp2)) Do
  6451. begin
  6452. TmpBool1 := False;
  6453. if taicpu(hp1).opcode=A_LEA then
  6454. begin
  6455. if (TmpRef.base = NR_NO) and
  6456. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6457. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6458. { Segment register isn't a concern here }
  6459. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6460. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6461. begin
  6462. TmpBool1 := True;
  6463. TmpBool2 := True;
  6464. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6465. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6466. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6467. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6468. RemoveInstruction(hp1);
  6469. end
  6470. end
  6471. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6472. begin
  6473. TmpBool1 := True;
  6474. TmpBool2 := True;
  6475. case taicpu(hp1).opcode of
  6476. A_ADD:
  6477. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6478. A_SUB:
  6479. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6480. else
  6481. internalerror(2019050536);
  6482. end;
  6483. RemoveInstruction(hp1);
  6484. end
  6485. else
  6486. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6487. (((taicpu(hp1).opcode = A_ADD) and
  6488. (TmpRef.base = NR_NO)) or
  6489. (taicpu(hp1).opcode = A_INC) or
  6490. (taicpu(hp1).opcode = A_DEC)) then
  6491. begin
  6492. TmpBool1 := True;
  6493. TmpBool2 := True;
  6494. case taicpu(hp1).opcode of
  6495. A_ADD:
  6496. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6497. A_INC:
  6498. inc(TmpRef.offset);
  6499. A_DEC:
  6500. dec(TmpRef.offset);
  6501. else
  6502. internalerror(2019050535);
  6503. end;
  6504. RemoveInstruction(hp1);
  6505. end;
  6506. end;
  6507. if TmpBool2
  6508. {$ifndef x86_64}
  6509. or
  6510. ((current_settings.optimizecputype < cpu_Pentium2) and
  6511. (taicpu(p).oper[0]^.val <= 3) and
  6512. not(cs_opt_size in current_settings.optimizerswitches))
  6513. {$endif x86_64}
  6514. then
  6515. begin
  6516. if not(TmpBool2) and
  6517. (taicpu(p).oper[0]^.val=1) then
  6518. begin
  6519. taicpu(p).opcode := A_ADD;
  6520. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6521. end
  6522. else
  6523. begin
  6524. taicpu(p).opcode := A_LEA;
  6525. taicpu(p).loadref(0, TmpRef);
  6526. end;
  6527. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6528. Result := True;
  6529. end;
  6530. end
  6531. {$ifndef x86_64}
  6532. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6533. begin
  6534. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6535. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6536. (unlike shl, which is only Tairable in the U pipe) }
  6537. if taicpu(p).oper[0]^.val=1 then
  6538. begin
  6539. taicpu(p).opcode := A_ADD;
  6540. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6541. Result := True;
  6542. end
  6543. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6544. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6545. else if (taicpu(p).opsize = S_L) and
  6546. (taicpu(p).oper[0]^.val<= 3) then
  6547. begin
  6548. reference_reset(tmpref,2,[]);
  6549. TmpRef.index := taicpu(p).oper[1]^.reg;
  6550. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6551. taicpu(p).opcode := A_LEA;
  6552. taicpu(p).loadref(0, TmpRef);
  6553. Result := True;
  6554. end;
  6555. end
  6556. {$endif x86_64}
  6557. else if
  6558. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6559. (
  6560. (
  6561. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6562. SetAndTest(hp1, hp2)
  6563. {$ifdef x86_64}
  6564. ) or
  6565. (
  6566. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6567. GetNextInstruction(hp1, hp2) and
  6568. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6569. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6570. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6571. {$endif x86_64}
  6572. )
  6573. ) and
  6574. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6575. begin
  6576. { Change:
  6577. shl x, %reg1
  6578. mov -(1<<x), %reg2
  6579. and %reg2, %reg1
  6580. Or:
  6581. shl x, %reg1
  6582. and -(1<<x), %reg1
  6583. To just:
  6584. shl x, %reg1
  6585. Since the and operation only zeroes bits that are already zero from the shl operation
  6586. }
  6587. case taicpu(p).oper[0]^.val of
  6588. 8:
  6589. mask:=$FFFFFFFFFFFFFF00;
  6590. 16:
  6591. mask:=$FFFFFFFFFFFF0000;
  6592. 32:
  6593. mask:=$FFFFFFFF00000000;
  6594. 63:
  6595. { Constant pre-calculated to prevent overflow errors with Int64 }
  6596. mask:=$8000000000000000;
  6597. else
  6598. begin
  6599. if taicpu(p).oper[0]^.val >= 64 then
  6600. { Shouldn't happen realistically, since the register
  6601. is guaranteed to be set to zero at this point }
  6602. mask := 0
  6603. else
  6604. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6605. end;
  6606. end;
  6607. if taicpu(hp1).oper[0]^.val = mask then
  6608. begin
  6609. { Everything checks out, perform the optimisation, as long as
  6610. the FLAGS register isn't being used}
  6611. TransferUsedRegs(TmpUsedRegs);
  6612. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6613. {$ifdef x86_64}
  6614. if (hp1 <> hp2) then
  6615. begin
  6616. { "shl/mov/and" version }
  6617. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6618. { Don't do the optimisation if the FLAGS register is in use }
  6619. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6620. begin
  6621. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6622. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6623. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6624. begin
  6625. RemoveInstruction(hp1);
  6626. Result := True;
  6627. end;
  6628. { Only set Result to True if the 'mov' instruction was removed }
  6629. RemoveInstruction(hp2);
  6630. end;
  6631. end
  6632. else
  6633. {$endif x86_64}
  6634. begin
  6635. { "shl/and" version }
  6636. { Don't do the optimisation if the FLAGS register is in use }
  6637. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6638. begin
  6639. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6640. RemoveInstruction(hp1);
  6641. Result := True;
  6642. end;
  6643. end;
  6644. Exit;
  6645. end
  6646. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6647. begin
  6648. { Even if the mask doesn't allow for its removal, we might be
  6649. able to optimise the mask for the "shl/and" version, which
  6650. may permit other peephole optimisations }
  6651. {$ifdef DEBUG_AOPTCPU}
  6652. mask := taicpu(hp1).oper[0]^.val and mask;
  6653. if taicpu(hp1).oper[0]^.val <> mask then
  6654. begin
  6655. DebugMsg(
  6656. SPeepholeOptimization +
  6657. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6658. ' to $' + debug_tostr(mask) +
  6659. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6660. taicpu(hp1).oper[0]^.val := mask;
  6661. end;
  6662. {$else DEBUG_AOPTCPU}
  6663. { If debugging is off, just set the operand even if it's the same }
  6664. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6665. {$endif DEBUG_AOPTCPU}
  6666. end;
  6667. end;
  6668. {
  6669. change
  6670. shl/sal const,reg
  6671. <op> ...(...,reg,1),...
  6672. into
  6673. <op> ...(...,reg,1 shl const),...
  6674. if const in 1..3
  6675. }
  6676. if MatchOpType(taicpu(p), top_const, top_reg) and
  6677. (taicpu(p).oper[0]^.val in [1..3]) and
  6678. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6679. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6680. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6681. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6682. MatchOpType(taicpu(hp1),top_ref))
  6683. ) and
  6684. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6685. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6686. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6687. begin
  6688. TransferUsedRegs(TmpUsedRegs);
  6689. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6690. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6691. begin
  6692. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6693. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6694. RemoveCurrentP(p);
  6695. Result:=true;
  6696. exit;
  6697. end;
  6698. end;
  6699. if MatchOpType(taicpu(p), top_const, top_reg) and
  6700. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6701. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6702. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6703. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6704. begin
  6705. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6706. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6707. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6708. {$ifdef x86_64}
  6709. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6710. {$endif x86_64}
  6711. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6712. begin
  6713. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6714. taicpu(hp1).opcode:=A_MOV;
  6715. taicpu(hp1).oper[0]^.val:=0;
  6716. end
  6717. else
  6718. begin
  6719. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6720. taicpu(hp1).oper[0]^.val:=shiftval;
  6721. end;
  6722. RemoveCurrentP(p);
  6723. Result:=true;
  6724. exit;
  6725. end;
  6726. end;
  6727. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6728. begin
  6729. case shr_size of
  6730. S_B:
  6731. { No valid combinations }
  6732. Result := False;
  6733. S_W:
  6734. Result := (Shift >= 8) and (movz_size = S_BW);
  6735. S_L:
  6736. Result :=
  6737. (Shift >= 24) { Any opsize is valid for this shift } or
  6738. ((Shift >= 16) and (movz_size = S_WL));
  6739. {$ifdef x86_64}
  6740. S_Q:
  6741. Result :=
  6742. (Shift >= 56) { Any opsize is valid for this shift } or
  6743. ((Shift >= 48) and (movz_size = S_WL));
  6744. {$endif x86_64}
  6745. else
  6746. InternalError(2022081510);
  6747. end;
  6748. end;
  6749. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6750. var
  6751. hp1, hp2: tai;
  6752. Shift: TCGInt;
  6753. LimitSize: Topsize;
  6754. DoNotMerge: Boolean;
  6755. begin
  6756. Result := False;
  6757. { All these optimisations work on "shr const,%reg" }
  6758. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6759. Exit;
  6760. DoNotMerge := False;
  6761. Shift := taicpu(p).oper[0]^.val;
  6762. LimitSize := taicpu(p).opsize;
  6763. hp1 := p;
  6764. repeat
  6765. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6766. Exit;
  6767. case taicpu(hp1).opcode of
  6768. A_TEST, A_CMP, A_Jcc:
  6769. { Skip over conditional jumps and relevant comparisons }
  6770. Continue;
  6771. A_MOVZX:
  6772. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6773. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6774. begin
  6775. { Since the original register is being read as is, subsequent
  6776. SHRs must not be merged at this point }
  6777. DoNotMerge := True;
  6778. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6779. begin
  6780. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6781. begin
  6782. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6783. taicpu(hp1).opcode := A_MOV;
  6784. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6785. case taicpu(hp1).opsize of
  6786. S_BW:
  6787. taicpu(hp1).opsize := S_W;
  6788. S_BL, S_WL:
  6789. taicpu(hp1).opsize := S_L;
  6790. else
  6791. InternalError(2022081503);
  6792. end;
  6793. { p itself hasn't changed, so no need to set Result to True }
  6794. Include(OptsToCheck, aoc_ForceNewIteration);
  6795. { See if there's anything afterwards that can be
  6796. optimised, since the input register hasn't changed }
  6797. Continue;
  6798. end;
  6799. { NOTE: If the MOVZX instruction reads and writes the same
  6800. register, defer this to the post-peephole optimisation stage }
  6801. Exit;
  6802. end;
  6803. end;
  6804. A_SHL, A_SAL, A_SHR:
  6805. if (taicpu(hp1).opsize <= LimitSize) and
  6806. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6807. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6808. begin
  6809. { Make sure the sizes don't exceed the register size limit
  6810. (measured by the shift value falling below the limit) }
  6811. if taicpu(hp1).opsize < LimitSize then
  6812. LimitSize := taicpu(hp1).opsize;
  6813. if taicpu(hp1).opcode = A_SHR then
  6814. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6815. else
  6816. begin
  6817. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6818. DoNotMerge := True;
  6819. end;
  6820. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6821. Exit;
  6822. { Since we've established that the combined shift is within
  6823. limits, we can actually combine the adjacent SHR
  6824. instructions even if they're different sizes }
  6825. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6826. begin
  6827. hp2 := tai(hp1.Previous);
  6828. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6829. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6830. RemoveInstruction(hp1);
  6831. hp1 := hp2;
  6832. { Though p has changed, only the constant has, and its
  6833. effects can still be detected on the next iteration of
  6834. the repeat..until loop }
  6835. Include(OptsToCheck, aoc_ForceNewIteration);
  6836. end;
  6837. { Move onto the next instruction }
  6838. Continue;
  6839. end;
  6840. else
  6841. ;
  6842. end;
  6843. Break;
  6844. until False;
  6845. end;
  6846. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6847. var
  6848. CurrentRef: TReference;
  6849. FullReg: TRegister;
  6850. hp1, hp2: tai;
  6851. begin
  6852. Result := False;
  6853. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6854. Exit;
  6855. { We assume you've checked if the operand is actually a reference by
  6856. this point. If it isn't, you'll most likely get an access violation }
  6857. CurrentRef := first_mov.oper[1]^.ref^;
  6858. { Memory must be aligned }
  6859. if (CurrentRef.offset mod 4) <> 0 then
  6860. Exit;
  6861. Inc(CurrentRef.offset);
  6862. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6863. if MatchOperand(second_mov.oper[0]^, 0) and
  6864. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6865. GetNextInstruction(second_mov, hp1) and
  6866. (hp1.typ = ait_instruction) and
  6867. (taicpu(hp1).opcode = A_MOV) and
  6868. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6869. (taicpu(hp1).oper[0]^.val = 0) then
  6870. begin
  6871. Inc(CurrentRef.offset);
  6872. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6873. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6874. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6875. begin
  6876. case taicpu(hp1).opsize of
  6877. S_B:
  6878. if GetNextInstruction(hp1, hp2) and
  6879. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6880. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6881. (taicpu(hp2).oper[0]^.val = 0) then
  6882. begin
  6883. Inc(CurrentRef.offset);
  6884. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6885. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6886. (taicpu(hp2).opsize = S_B) then
  6887. begin
  6888. RemoveInstruction(hp1);
  6889. RemoveInstruction(hp2);
  6890. first_mov.opsize := S_L;
  6891. if first_mov.oper[0]^.typ = top_reg then
  6892. begin
  6893. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6894. { Reuse second_mov as a MOVZX instruction }
  6895. second_mov.opcode := A_MOVZX;
  6896. second_mov.opsize := S_BL;
  6897. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6898. second_mov.loadreg(1, FullReg);
  6899. first_mov.oper[0]^.reg := FullReg;
  6900. asml.Remove(second_mov);
  6901. asml.InsertBefore(second_mov, first_mov);
  6902. end
  6903. else
  6904. { It's a value }
  6905. begin
  6906. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6907. RemoveInstruction(second_mov);
  6908. end;
  6909. Result := True;
  6910. Exit;
  6911. end;
  6912. end;
  6913. S_W:
  6914. begin
  6915. RemoveInstruction(hp1);
  6916. first_mov.opsize := S_L;
  6917. if first_mov.oper[0]^.typ = top_reg then
  6918. begin
  6919. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6920. { Reuse second_mov as a MOVZX instruction }
  6921. second_mov.opcode := A_MOVZX;
  6922. second_mov.opsize := S_BL;
  6923. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6924. second_mov.loadreg(1, FullReg);
  6925. first_mov.oper[0]^.reg := FullReg;
  6926. asml.Remove(second_mov);
  6927. asml.InsertBefore(second_mov, first_mov);
  6928. end
  6929. else
  6930. { It's a value }
  6931. begin
  6932. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6933. RemoveInstruction(second_mov);
  6934. end;
  6935. Result := True;
  6936. Exit;
  6937. end;
  6938. else
  6939. ;
  6940. end;
  6941. end;
  6942. end;
  6943. end;
  6944. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6945. { returns true if a "continue" should be done after this optimization }
  6946. var
  6947. hp1, hp2, hp3: tai;
  6948. begin
  6949. Result := false;
  6950. hp3 := nil;
  6951. if MatchOpType(taicpu(p),top_ref) and
  6952. GetNextInstruction(p, hp1) and
  6953. (hp1.typ = ait_instruction) and
  6954. (((taicpu(hp1).opcode = A_FLD) and
  6955. (taicpu(p).opcode = A_FSTP)) or
  6956. ((taicpu(p).opcode = A_FISTP) and
  6957. (taicpu(hp1).opcode = A_FILD))) and
  6958. MatchOpType(taicpu(hp1),top_ref) and
  6959. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6960. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6961. begin
  6962. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6963. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6964. GetNextInstruction(hp1, hp2) and
  6965. (((hp2.typ = ait_instruction) and
  6966. IsExitCode(hp2) and
  6967. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6968. not(assigned(current_procinfo.procdef.funcretsym) and
  6969. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6970. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6971. { fstp <temp>
  6972. fld <temp>
  6973. <dealloc> <temp>
  6974. }
  6975. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6976. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6977. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6978. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6979. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6980. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6981. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6982. )
  6983. )
  6984. ) then
  6985. begin
  6986. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6987. RemoveInstruction(hp1);
  6988. RemoveCurrentP(p, hp2);
  6989. { first case: exit code }
  6990. if hp2.typ = ait_instruction then
  6991. RemoveLastDeallocForFuncRes(p);
  6992. Result := true;
  6993. end
  6994. else
  6995. { we can do this only in fast math mode as fstp is rounding ...
  6996. ... still disabled as it breaks the compiler and/or rtl }
  6997. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6998. { ... or if another fstp equal to the first one follows }
  6999. GetNextInstruction(hp1,hp2) and
  7000. (hp2.typ = ait_instruction) and
  7001. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7002. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7003. begin
  7004. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7005. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7006. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7007. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7008. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7009. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7010. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7011. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7012. ) then
  7013. begin
  7014. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7015. RemoveCurrentP(p,hp2);
  7016. RemoveInstruction(hp1);
  7017. Result := true;
  7018. end
  7019. else if { fst can't store an extended/comp value }
  7020. (taicpu(p).opsize <> S_FX) and
  7021. (taicpu(p).opsize <> S_IQ) then
  7022. begin
  7023. if (taicpu(p).opcode = A_FSTP) then
  7024. taicpu(p).opcode := A_FST
  7025. else
  7026. taicpu(p).opcode := A_FIST;
  7027. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7028. RemoveInstruction(hp1);
  7029. Result := true;
  7030. end;
  7031. end;
  7032. end;
  7033. end;
  7034. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7035. var
  7036. hp1, hp2, hp3: tai;
  7037. begin
  7038. result:=false;
  7039. if MatchOpType(taicpu(p),top_reg) and
  7040. GetNextInstruction(p, hp1) and
  7041. (hp1.typ = Ait_Instruction) and
  7042. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7043. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7044. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7045. { change to
  7046. fld reg fxxx reg,st
  7047. fxxxp st, st1 (hp1)
  7048. Remark: non commutative operations must be reversed!
  7049. }
  7050. begin
  7051. case taicpu(hp1).opcode Of
  7052. A_FMULP,A_FADDP,
  7053. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7054. begin
  7055. case taicpu(hp1).opcode Of
  7056. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7057. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7058. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7059. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7060. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7061. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7062. else
  7063. internalerror(2019050534);
  7064. end;
  7065. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7066. taicpu(hp1).oper[1]^.reg := NR_ST;
  7067. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7068. RemoveCurrentP(p, hp1);
  7069. Result:=true;
  7070. exit;
  7071. end;
  7072. else
  7073. ;
  7074. end;
  7075. end
  7076. else
  7077. if MatchOpType(taicpu(p),top_ref) and
  7078. GetNextInstruction(p, hp2) and
  7079. (hp2.typ = Ait_Instruction) and
  7080. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7081. (taicpu(p).opsize in [S_FS, S_FL]) and
  7082. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7083. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7084. if GetLastInstruction(p, hp1) and
  7085. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7086. MatchOpType(taicpu(hp1),top_ref) and
  7087. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7088. if ((taicpu(hp2).opcode = A_FMULP) or
  7089. (taicpu(hp2).opcode = A_FADDP)) then
  7090. { change to
  7091. fld/fst mem1 (hp1) fld/fst mem1
  7092. fld mem1 (p) fadd/
  7093. faddp/ fmul st, st
  7094. fmulp st, st1 (hp2) }
  7095. begin
  7096. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7097. RemoveCurrentP(p, hp1);
  7098. if (taicpu(hp2).opcode = A_FADDP) then
  7099. taicpu(hp2).opcode := A_FADD
  7100. else
  7101. taicpu(hp2).opcode := A_FMUL;
  7102. taicpu(hp2).oper[1]^.reg := NR_ST;
  7103. end
  7104. else
  7105. { change to
  7106. fld/fst mem1 (hp1) fld/fst mem1
  7107. fld mem1 (p) fld st
  7108. }
  7109. begin
  7110. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7111. taicpu(p).changeopsize(S_FL);
  7112. taicpu(p).loadreg(0,NR_ST);
  7113. end
  7114. else
  7115. begin
  7116. case taicpu(hp2).opcode Of
  7117. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7118. { change to
  7119. fld/fst mem1 (hp1) fld/fst mem1
  7120. fld mem2 (p) fxxx mem2
  7121. fxxxp st, st1 (hp2) }
  7122. begin
  7123. case taicpu(hp2).opcode Of
  7124. A_FADDP: taicpu(p).opcode := A_FADD;
  7125. A_FMULP: taicpu(p).opcode := A_FMUL;
  7126. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7127. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7128. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7129. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7130. else
  7131. internalerror(2019050533);
  7132. end;
  7133. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7134. RemoveInstruction(hp2);
  7135. end
  7136. else
  7137. ;
  7138. end
  7139. end
  7140. end;
  7141. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7142. begin
  7143. Result := condition_in(cond1, cond2) or
  7144. { Not strictly subsets due to the actual flags checked, but because we're
  7145. comparing integers, E is a subset of AE and GE and their aliases }
  7146. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7147. end;
  7148. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7149. var
  7150. v: TCGInt;
  7151. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7152. FirstMatch, TempBool: Boolean;
  7153. NewReg: TRegister;
  7154. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7155. begin
  7156. Result:=false;
  7157. { All these optimisations need a next instruction }
  7158. if not GetNextInstruction(p, hp1) then
  7159. Exit;
  7160. true_hp1 := hp1;
  7161. { Search for:
  7162. cmp ###,###
  7163. j(c1) @lbl1
  7164. ...
  7165. @lbl:
  7166. cmp ###,### (same comparison as above)
  7167. j(c2) @lbl2
  7168. If c1 is a subset of c2, change to:
  7169. cmp ###,###
  7170. j(c1) @lbl2
  7171. (@lbl1 may become a dead label as a result)
  7172. }
  7173. { Also handle cases where there are multiple jumps in a row }
  7174. p_jump := hp1;
  7175. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7176. begin
  7177. Prefetch(p_jump.Next);
  7178. if IsJumpToLabel(taicpu(p_jump)) then
  7179. begin
  7180. { Do jump optimisations first in case the condition becomes
  7181. unnecessary }
  7182. TempBool := True;
  7183. if DoJumpOptimizations(p_jump, TempBool) or
  7184. not TempBool then
  7185. begin
  7186. if Assigned(p_jump) then
  7187. begin
  7188. { CollapseZeroDistJump will be set to the label or an align
  7189. before it after the jump if it optimises, whether or not
  7190. the label is live or dead }
  7191. if (p_jump.typ = ait_align) or
  7192. (
  7193. (p_jump.typ = ait_label) and
  7194. not (tai_label(p_jump).labsym.is_used)
  7195. ) then
  7196. GetNextInstruction(p_jump, p_jump);
  7197. end;
  7198. TransferUsedRegs(TmpUsedRegs);
  7199. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7200. if not Assigned(p_jump) or
  7201. (
  7202. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7203. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7204. ) then
  7205. begin
  7206. { No more conditional jumps; conditional statement is no longer required }
  7207. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7208. RemoveCurrentP(p);
  7209. Result := True;
  7210. Exit;
  7211. end;
  7212. hp1 := p_jump;
  7213. Include(OptsToCheck, aoc_ForceNewIteration);
  7214. Continue;
  7215. end;
  7216. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7217. if GetNextInstruction(p_jump, hp2) and
  7218. (
  7219. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7220. not TempBool
  7221. ) then
  7222. begin
  7223. hp1 := p_jump;
  7224. Include(OptsToCheck, aoc_ForceNewIteration);
  7225. Continue;
  7226. end;
  7227. p_label := nil;
  7228. if Assigned(JumpLabel) then
  7229. p_label := getlabelwithsym(JumpLabel);
  7230. if Assigned(p_label) and
  7231. GetNextInstruction(p_label, p_dist) and
  7232. MatchInstruction(p_dist, A_CMP, []) and
  7233. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7234. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7235. GetNextInstruction(p_dist, hp1_dist) and
  7236. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7237. begin
  7238. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7239. if JumpLabel = JumpLabel_dist then
  7240. { This is an infinite loop }
  7241. Exit;
  7242. { Best optimisation when the first condition is a subset (or equal) of the second }
  7243. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7244. begin
  7245. { Any registers used here will already be allocated }
  7246. if Assigned(JumpLabel) then
  7247. JumpLabel.DecRefs;
  7248. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7249. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7250. Include(OptsToCheck, aoc_ForceNewIteration);
  7251. { Don't exit yet. Since p and p_jump haven't actually been
  7252. removed, we can check for more on this iteration }
  7253. end
  7254. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7255. GetNextInstruction(hp1_dist, hp1_label) and
  7256. (hp1_label.typ = ait_label) then
  7257. begin
  7258. JumpLabel_far := tai_label(hp1_label).labsym;
  7259. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7260. { This is an infinite loop }
  7261. Exit;
  7262. if Assigned(JumpLabel_far) then
  7263. begin
  7264. { In this situation, if the first jump branches, the second one will never,
  7265. branch so change the destination label to after the second jump }
  7266. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7267. if Assigned(JumpLabel) then
  7268. JumpLabel.DecRefs;
  7269. JumpLabel_far.IncRefs;
  7270. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7271. Result := True;
  7272. { Don't exit yet. Since p and p_jump haven't actually been
  7273. removed, we can check for more on this iteration }
  7274. Continue;
  7275. end;
  7276. end;
  7277. end;
  7278. end;
  7279. { Search for:
  7280. cmp ###,###
  7281. j(c1) @lbl1
  7282. cmp ###,### (same as first)
  7283. Remove second cmp
  7284. }
  7285. if GetNextInstruction(p_jump, hp2) and
  7286. (
  7287. (
  7288. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7289. (
  7290. (
  7291. MatchOpType(taicpu(p), top_const, top_reg) and
  7292. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7293. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7294. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7295. ) or (
  7296. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7297. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7298. )
  7299. )
  7300. ) or (
  7301. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7302. MatchOperand(taicpu(p).oper[0]^, 0) and
  7303. (taicpu(p).oper[1]^.typ = top_reg) and
  7304. MatchInstruction(hp2, A_TEST, []) and
  7305. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7306. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7307. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7308. )
  7309. ) then
  7310. begin
  7311. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7312. TransferUsedRegs(TmpUsedRegs);
  7313. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7314. RemoveInstruction(hp2);
  7315. Result := True;
  7316. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7317. end
  7318. else
  7319. begin
  7320. { hp2 is the next instruction, so save time and just set p_jump
  7321. to it instead of calling GetNextInstruction below }
  7322. p_jump := hp2;
  7323. Continue;
  7324. end;
  7325. GetNextInstruction(p_jump, p_jump);
  7326. end;
  7327. if (
  7328. { Don't call GetNextInstruction again if we already have it }
  7329. (true_hp1 = p_jump) or
  7330. GetNextInstruction(p, hp1)
  7331. ) and
  7332. MatchInstruction(hp1, A_Jcc, []) and
  7333. IsJumpToLabel(taicpu(hp1)) and
  7334. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7335. GetNextInstruction(hp1, hp2) then
  7336. begin
  7337. {
  7338. cmp x, y (or "cmp y, x")
  7339. je @lbl
  7340. mov x, y
  7341. @lbl:
  7342. (x and y can be constants, registers or references)
  7343. Change to:
  7344. mov x, y (x and y will always be equal in the end)
  7345. @lbl: (may beceome a dead label)
  7346. Also:
  7347. cmp x, y (or "cmp y, x")
  7348. jne @lbl
  7349. mov x, y
  7350. @lbl:
  7351. (x and y can be constants, registers or references)
  7352. Change to:
  7353. Absolutely nothing! (Except @lbl if it's still live)
  7354. }
  7355. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7356. (
  7357. (
  7358. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7359. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7360. ) or (
  7361. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7362. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7363. )
  7364. ) and
  7365. GetNextInstruction(hp2, hp1_label) and
  7366. (hp1_label.typ = ait_label) and
  7367. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7368. begin
  7369. tai_label(hp1_label).labsym.DecRefs;
  7370. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7371. begin
  7372. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7373. RemoveInstruction(hp2);
  7374. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7375. end
  7376. else
  7377. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7378. RemoveInstruction(hp1);
  7379. RemoveCurrentp(p, hp2);
  7380. Result := True;
  7381. Exit;
  7382. end;
  7383. {
  7384. Try to optimise the following:
  7385. cmp $x,### ($x and $y can be registers or constants)
  7386. je @lbl1 (only reference)
  7387. cmp $y,### (### are identical)
  7388. @Lbl:
  7389. sete %reg1
  7390. Change to:
  7391. cmp $x,###
  7392. sete %reg2 (allocate new %reg2)
  7393. cmp $y,###
  7394. sete %reg1
  7395. orb %reg2,%reg1
  7396. (dealloc %reg2)
  7397. This adds an instruction (so don't perform under -Os), but it removes
  7398. a conditional branch.
  7399. }
  7400. if not (cs_opt_size in current_settings.optimizerswitches) and
  7401. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7402. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7403. { The first operand of CMP instructions can only be a register or
  7404. immediate anyway, so no need to check }
  7405. GetNextInstruction(hp2, p_label) and
  7406. (p_label.typ = ait_label) and
  7407. (tai_label(p_label).labsym.getrefs = 1) and
  7408. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7409. GetNextInstruction(p_label, p_dist) and
  7410. MatchInstruction(p_dist, A_SETcc, []) and
  7411. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7412. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7413. begin
  7414. TransferUsedRegs(TmpUsedRegs);
  7415. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7416. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7417. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7418. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7419. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7420. { Get the instruction after the SETcc instruction so we can
  7421. allocate a new register over the entire range }
  7422. GetNextInstruction(p_dist, hp1_dist) then
  7423. begin
  7424. { Register can appear in p if it's not used afterwards, so only
  7425. allocate between hp1 and hp1_dist }
  7426. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7427. if NewReg <> NR_NO then
  7428. begin
  7429. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7430. { Change the jump instruction into a SETcc instruction }
  7431. taicpu(hp1).opcode := A_SETcc;
  7432. taicpu(hp1).opsize := S_B;
  7433. taicpu(hp1).loadreg(0, NewReg);
  7434. { This is now a dead label }
  7435. tai_label(p_label).labsym.decrefs;
  7436. { Prefer adding before the next instruction so the FLAGS
  7437. register is deallicated first }
  7438. AsmL.InsertBefore(
  7439. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7440. hp1_dist
  7441. );
  7442. Result := True;
  7443. { Don't exit yet, as p wasn't changed and hp1, while
  7444. modified, is still intact and might be optimised by the
  7445. SETcc optimisation below }
  7446. end;
  7447. end;
  7448. end;
  7449. end;
  7450. if (taicpu(p).oper[0]^.typ = top_const) and
  7451. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7452. begin
  7453. if (taicpu(p).oper[0]^.val = 0) and
  7454. (taicpu(p).oper[1]^.typ = top_reg) then
  7455. begin
  7456. hp2 := p;
  7457. FirstMatch := True;
  7458. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7459. anything meaningful once it's converted to "test %reg,%reg";
  7460. additionally, some jumps will always (or never) branch, so
  7461. evaluate every jump immediately following the
  7462. comparison, optimising the conditions if possible.
  7463. Similarly with SETcc... those that are always set to 0 or 1
  7464. are changed to MOV instructions }
  7465. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7466. (
  7467. GetNextInstruction(hp2, hp1) and
  7468. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7469. ) do
  7470. begin
  7471. Prefetch(hp1.Next);
  7472. FirstMatch := False;
  7473. case taicpu(hp1).condition of
  7474. C_B, C_C, C_NAE, C_O:
  7475. { For B/NAE:
  7476. Will never branch since an unsigned integer can never be below zero
  7477. For C/O:
  7478. Result cannot overflow because 0 is being subtracted
  7479. }
  7480. begin
  7481. if taicpu(hp1).opcode = A_Jcc then
  7482. begin
  7483. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7484. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7485. RemoveInstruction(hp1);
  7486. { Since hp1 was deleted, hp2 must not be updated }
  7487. Continue;
  7488. end
  7489. else
  7490. begin
  7491. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7492. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7493. taicpu(hp1).opcode := A_MOV;
  7494. taicpu(hp1).ops := 2;
  7495. taicpu(hp1).condition := C_None;
  7496. taicpu(hp1).opsize := S_B;
  7497. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7498. taicpu(hp1).loadconst(0, 0);
  7499. end;
  7500. end;
  7501. C_BE, C_NA:
  7502. begin
  7503. { Will only branch if equal to zero }
  7504. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7505. taicpu(hp1).condition := C_E;
  7506. end;
  7507. C_A, C_NBE:
  7508. begin
  7509. { Will only branch if not equal to zero }
  7510. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7511. taicpu(hp1).condition := C_NE;
  7512. end;
  7513. C_AE, C_NB, C_NC, C_NO:
  7514. begin
  7515. { Will always branch }
  7516. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7517. if taicpu(hp1).opcode = A_Jcc then
  7518. begin
  7519. MakeUnconditional(taicpu(hp1));
  7520. { Any jumps/set that follow will now be dead code }
  7521. RemoveDeadCodeAfterJump(taicpu(hp1));
  7522. Break;
  7523. end
  7524. else
  7525. begin
  7526. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7527. taicpu(hp1).opcode := A_MOV;
  7528. taicpu(hp1).ops := 2;
  7529. taicpu(hp1).condition := C_None;
  7530. taicpu(hp1).opsize := S_B;
  7531. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7532. taicpu(hp1).loadconst(0, 1);
  7533. end;
  7534. end;
  7535. C_None:
  7536. InternalError(2020012201);
  7537. C_P, C_PE, C_NP, C_PO:
  7538. { We can't handle parity checks and they should never be generated
  7539. after a general-purpose CMP (it's used in some floating-point
  7540. comparisons that don't use CMP) }
  7541. InternalError(2020012202);
  7542. else
  7543. { Zero/Equality, Sign, their complements and all of the
  7544. signed comparisons do not need to be converted };
  7545. end;
  7546. hp2 := hp1;
  7547. end;
  7548. { Convert the instruction to a TEST }
  7549. taicpu(p).opcode := A_TEST;
  7550. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7551. Result := True;
  7552. Exit;
  7553. end
  7554. else
  7555. begin
  7556. TransferUsedRegs(TmpUsedRegs);
  7557. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7558. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7559. begin
  7560. if (taicpu(p).oper[0]^.val = 1) and
  7561. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7562. begin
  7563. { Convert; To:
  7564. cmp $1,r/m cmp $0,r/m
  7565. jl @lbl jle @lbl
  7566. (Also do inverted conditions)
  7567. }
  7568. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7569. taicpu(p).oper[0]^.val := 0;
  7570. if taicpu(hp1).condition in [C_L, C_NGE] then
  7571. taicpu(hp1).condition := C_LE
  7572. else
  7573. taicpu(hp1).condition := C_NLE;
  7574. { If the instruction is now "cmp $0,%reg", convert it to a
  7575. TEST (and effectively do the work of the "cmp $0,%reg" in
  7576. the block above)
  7577. }
  7578. if (taicpu(p).oper[1]^.typ = top_reg) then
  7579. begin
  7580. taicpu(p).opcode := A_TEST;
  7581. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7582. end;
  7583. Result := True;
  7584. Exit;
  7585. end
  7586. else if (taicpu(p).oper[1]^.typ = top_reg)
  7587. {$ifdef x86_64}
  7588. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7589. {$endif x86_64}
  7590. then
  7591. begin
  7592. { cmp register,$8000 neg register
  7593. je target --> jo target
  7594. .... only if register is deallocated before jump.}
  7595. case Taicpu(p).opsize of
  7596. S_B: v:=$80;
  7597. S_W: v:=$8000;
  7598. S_L: v:=qword($80000000);
  7599. else
  7600. internalerror(2013112905);
  7601. end;
  7602. if (taicpu(p).oper[0]^.val=v) and
  7603. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7604. begin
  7605. TransferUsedRegs(TmpUsedRegs);
  7606. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7607. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7608. begin
  7609. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7610. Taicpu(p).opcode:=A_NEG;
  7611. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7612. Taicpu(p).clearop(1);
  7613. Taicpu(p).ops:=1;
  7614. if Taicpu(hp1).condition=C_E then
  7615. Taicpu(hp1).condition:=C_O
  7616. else
  7617. Taicpu(hp1).condition:=C_NO;
  7618. Result:=true;
  7619. exit;
  7620. end;
  7621. end;
  7622. end;
  7623. end;
  7624. end;
  7625. end;
  7626. if TrySwapMovCmp(p, hp1) then
  7627. begin
  7628. Result := True;
  7629. Exit;
  7630. end;
  7631. end;
  7632. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7633. var
  7634. hp1: tai;
  7635. begin
  7636. {
  7637. remove the second (v)pxor from
  7638. pxor reg,reg
  7639. ...
  7640. pxor reg,reg
  7641. }
  7642. Result:=false;
  7643. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7644. MatchOpType(taicpu(p),top_reg,top_reg) and
  7645. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7646. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7647. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7648. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7649. begin
  7650. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7651. RemoveInstruction(hp1);
  7652. Result:=true;
  7653. Exit;
  7654. end
  7655. {
  7656. replace
  7657. pxor reg1,reg1
  7658. movapd/s reg1,reg2
  7659. dealloc reg1
  7660. by
  7661. pxor reg2,reg2
  7662. }
  7663. else if GetNextInstruction(p,hp1) and
  7664. { we mix single and double opperations here because we assume that the compiler
  7665. generates vmovapd only after double operations and vmovaps only after single operations }
  7666. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7667. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7668. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7669. (taicpu(p).oper[0]^.typ=top_reg) then
  7670. begin
  7671. TransferUsedRegs(TmpUsedRegs);
  7672. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7673. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7674. begin
  7675. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7676. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7677. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7678. RemoveInstruction(hp1);
  7679. result:=true;
  7680. end;
  7681. end;
  7682. end;
  7683. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7684. var
  7685. hp1: tai;
  7686. begin
  7687. {
  7688. remove the second (v)pxor from
  7689. (v)pxor reg,reg
  7690. ...
  7691. (v)pxor reg,reg
  7692. }
  7693. Result:=false;
  7694. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7695. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7696. begin
  7697. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7698. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7699. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7700. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7701. begin
  7702. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7703. RemoveInstruction(hp1);
  7704. Result:=true;
  7705. Exit;
  7706. end;
  7707. {$ifdef x86_64}
  7708. {
  7709. replace
  7710. vpxor reg1,reg1,reg1
  7711. vmov reg,mem
  7712. by
  7713. movq $0,mem
  7714. }
  7715. if GetNextInstruction(p,hp1) and
  7716. MatchInstruction(hp1,A_VMOVSD,[]) and
  7717. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7718. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7719. begin
  7720. TransferUsedRegs(TmpUsedRegs);
  7721. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7722. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7723. begin
  7724. taicpu(hp1).loadconst(0,0);
  7725. taicpu(hp1).opcode:=A_MOV;
  7726. taicpu(hp1).opsize:=S_Q;
  7727. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7728. RemoveCurrentP(p);
  7729. result:=true;
  7730. Exit;
  7731. end;
  7732. end;
  7733. {$endif x86_64}
  7734. end
  7735. {
  7736. replace
  7737. vpxor reg1,reg1,reg2
  7738. by
  7739. vpxor reg2,reg2,reg2
  7740. to avoid unncessary data dependencies
  7741. }
  7742. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7743. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7744. begin
  7745. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7746. { avoid unncessary data dependency }
  7747. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7748. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7749. result:=true;
  7750. exit;
  7751. end;
  7752. Result:=OptPass1VOP(p);
  7753. end;
  7754. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7755. var
  7756. hp1 : tai;
  7757. begin
  7758. result:=false;
  7759. { replace
  7760. IMul const,%mreg1,%mreg2
  7761. Mov %reg2,%mreg3
  7762. dealloc %mreg3
  7763. by
  7764. Imul const,%mreg1,%mreg23
  7765. }
  7766. if (taicpu(p).ops=3) and
  7767. GetNextInstruction(p,hp1) and
  7768. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7769. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7770. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7771. begin
  7772. TransferUsedRegs(TmpUsedRegs);
  7773. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7774. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7775. begin
  7776. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7777. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7778. RemoveInstruction(hp1);
  7779. result:=true;
  7780. end;
  7781. end;
  7782. end;
  7783. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7784. var
  7785. hp1 : tai;
  7786. begin
  7787. result:=false;
  7788. { replace
  7789. IMul %reg0,%reg1,%reg2
  7790. Mov %reg2,%reg3
  7791. dealloc %reg2
  7792. by
  7793. Imul %reg0,%reg1,%reg3
  7794. }
  7795. if GetNextInstruction(p,hp1) and
  7796. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7797. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7798. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7799. begin
  7800. TransferUsedRegs(TmpUsedRegs);
  7801. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7802. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7803. begin
  7804. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7805. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7806. RemoveInstruction(hp1);
  7807. result:=true;
  7808. end;
  7809. end;
  7810. end;
  7811. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7812. var
  7813. hp1: tai;
  7814. begin
  7815. Result:=false;
  7816. { get rid of
  7817. (v)cvtss2sd reg0,<reg1,>reg2
  7818. (v)cvtss2sd reg2,<reg2,>reg0
  7819. }
  7820. if GetNextInstruction(p,hp1) and
  7821. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7822. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7823. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7824. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7825. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7826. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7827. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7828. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7829. )
  7830. ) then
  7831. begin
  7832. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7833. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7834. begin
  7835. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7836. RemoveCurrentP(p);
  7837. RemoveInstruction(hp1);
  7838. end
  7839. else
  7840. begin
  7841. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7842. if taicpu(hp1).opcode=A_CVTSD2SS then
  7843. begin
  7844. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7845. taicpu(p).opcode:=A_MOVAPS;
  7846. end
  7847. else
  7848. begin
  7849. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7850. taicpu(p).opcode:=A_VMOVAPS;
  7851. end;
  7852. taicpu(p).ops:=2;
  7853. RemoveInstruction(hp1);
  7854. end;
  7855. Result:=true;
  7856. Exit;
  7857. end;
  7858. end;
  7859. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7860. var
  7861. hp1, hp2, hp3, hp4, hp5: tai;
  7862. ThisReg: TRegister;
  7863. begin
  7864. Result := False;
  7865. if not GetNextInstruction(p,hp1) then
  7866. Exit;
  7867. {
  7868. convert
  7869. j<c> .L1
  7870. mov 1,reg
  7871. jmp .L2
  7872. .L1
  7873. mov 0,reg
  7874. .L2
  7875. into
  7876. mov 0,reg
  7877. set<not(c)> reg
  7878. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7879. would destroy the flag contents
  7880. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7881. executed at the same time as a previous comparison.
  7882. set<not(c)> reg
  7883. movzx reg, reg
  7884. }
  7885. if MatchInstruction(hp1,A_MOV,[]) and
  7886. (taicpu(hp1).oper[0]^.typ = top_const) and
  7887. (
  7888. (
  7889. (taicpu(hp1).oper[1]^.typ = top_reg)
  7890. {$ifdef i386}
  7891. { Under i386, ESI, EDI, EBP and ESP
  7892. don't have an 8-bit representation }
  7893. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7894. {$endif i386}
  7895. ) or (
  7896. {$ifdef i386}
  7897. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7898. {$endif i386}
  7899. (taicpu(hp1).opsize = S_B)
  7900. )
  7901. ) and
  7902. GetNextInstruction(hp1,hp2) and
  7903. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7904. GetNextInstruction(hp2,hp3) and
  7905. (hp3.typ=ait_label) and
  7906. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7907. GetNextInstruction(hp3,hp4) and
  7908. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7909. (taicpu(hp4).oper[0]^.typ = top_const) and
  7910. (
  7911. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7912. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7913. ) and
  7914. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7915. GetNextInstruction(hp4,hp5) and
  7916. (hp5.typ=ait_label) and
  7917. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7918. begin
  7919. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7920. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7921. tai_label(hp3).labsym.DecRefs;
  7922. { If this isn't the only reference to the middle label, we can
  7923. still make a saving - only that the first jump and everything
  7924. that follows will remain. }
  7925. if (tai_label(hp3).labsym.getrefs = 0) then
  7926. begin
  7927. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7928. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7929. else
  7930. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7931. { remove jump, first label and second MOV (also catching any aligns) }
  7932. repeat
  7933. if not GetNextInstruction(hp2, hp3) then
  7934. InternalError(2021040810);
  7935. RemoveInstruction(hp2);
  7936. hp2 := hp3;
  7937. until hp2 = hp5;
  7938. { Don't decrement reference count before the removal loop
  7939. above, otherwise GetNextInstruction won't stop on the
  7940. the label }
  7941. tai_label(hp5).labsym.DecRefs;
  7942. end
  7943. else
  7944. begin
  7945. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7946. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7947. else
  7948. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7949. end;
  7950. taicpu(p).opcode:=A_SETcc;
  7951. taicpu(p).opsize:=S_B;
  7952. taicpu(p).is_jmp:=False;
  7953. if taicpu(hp1).opsize=S_B then
  7954. begin
  7955. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7956. if taicpu(hp1).oper[1]^.typ = top_reg then
  7957. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7958. RemoveInstruction(hp1);
  7959. end
  7960. else
  7961. begin
  7962. { Will be a register because the size can't be S_B otherwise }
  7963. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7964. taicpu(p).loadreg(0, ThisReg);
  7965. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7966. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7967. begin
  7968. case taicpu(hp1).opsize of
  7969. S_W:
  7970. taicpu(hp1).opsize := S_BW;
  7971. S_L:
  7972. taicpu(hp1).opsize := S_BL;
  7973. {$ifdef x86_64}
  7974. S_Q:
  7975. begin
  7976. taicpu(hp1).opsize := S_BL;
  7977. { Change the destination register to 32-bit }
  7978. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7979. end;
  7980. {$endif x86_64}
  7981. else
  7982. InternalError(2021040820);
  7983. end;
  7984. taicpu(hp1).opcode := A_MOVZX;
  7985. taicpu(hp1).loadreg(0, ThisReg);
  7986. end
  7987. else
  7988. begin
  7989. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7990. { hp1 is already a MOV instruction with the correct register }
  7991. taicpu(hp1).loadconst(0, 0);
  7992. { Inserting it right before p will guarantee that the flags are also tracked }
  7993. asml.Remove(hp1);
  7994. asml.InsertBefore(hp1, p);
  7995. end;
  7996. end;
  7997. Result:=true;
  7998. exit;
  7999. end
  8000. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8001. Result := TryJccStcClcOpt(p, hp1)
  8002. else if (hp1.typ = ait_label) then
  8003. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8004. end;
  8005. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8006. var
  8007. hp1, hp2, hp3: tai;
  8008. SourceRef, TargetRef: TReference;
  8009. CurrentReg: TRegister;
  8010. begin
  8011. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8012. if not UseAVX then
  8013. InternalError(2021100501);
  8014. Result := False;
  8015. { Look for the following to simplify:
  8016. vmovdqa/u x(mem1), %xmmreg
  8017. vmovdqa/u %xmmreg, y(mem2)
  8018. vmovdqa/u x+16(mem1), %xmmreg
  8019. vmovdqa/u %xmmreg, y+16(mem2)
  8020. Change to:
  8021. vmovdqa/u x(mem1), %ymmreg
  8022. vmovdqa/u %ymmreg, y(mem2)
  8023. vpxor %ymmreg, %ymmreg, %ymmreg
  8024. ( The VPXOR instruction is to zero the upper half, thus removing the
  8025. need to call the potentially expensive VZEROUPPER instruction. Other
  8026. peephole optimisations can remove VPXOR if it's unnecessary )
  8027. }
  8028. TransferUsedRegs(TmpUsedRegs);
  8029. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8030. { NOTE: In the optimisations below, if the references dictate that an
  8031. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8032. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8033. if (taicpu(p).opsize = S_XMM) and
  8034. MatchOpType(taicpu(p), top_ref, top_reg) and
  8035. GetNextInstruction(p, hp1) and
  8036. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8037. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8038. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8039. begin
  8040. SourceRef := taicpu(p).oper[0]^.ref^;
  8041. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8042. if GetNextInstruction(hp1, hp2) and
  8043. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8044. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8045. begin
  8046. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8047. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8048. Inc(SourceRef.offset, 16);
  8049. { Reuse the register in the first block move }
  8050. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8051. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8052. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8053. begin
  8054. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8055. Inc(TargetRef.offset, 16);
  8056. if GetNextInstruction(hp2, hp3) and
  8057. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8058. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8059. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8060. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8061. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8062. begin
  8063. { Update the register tracking to the new size }
  8064. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8065. { Remember that the offsets are 16 ahead }
  8066. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8067. if not (
  8068. ((SourceRef.offset mod 32) = 16) and
  8069. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8070. ) then
  8071. taicpu(p).opcode := A_VMOVDQU;
  8072. taicpu(p).opsize := S_YMM;
  8073. taicpu(p).oper[1]^.reg := CurrentReg;
  8074. if not (
  8075. ((TargetRef.offset mod 32) = 16) and
  8076. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8077. ) then
  8078. taicpu(hp1).opcode := A_VMOVDQU;
  8079. taicpu(hp1).opsize := S_YMM;
  8080. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8081. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8082. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8083. if (pi_uses_ymm in current_procinfo.flags) then
  8084. RemoveInstruction(hp2)
  8085. else
  8086. begin
  8087. taicpu(hp2).opcode := A_VPXOR;
  8088. taicpu(hp2).opsize := S_YMM;
  8089. taicpu(hp2).loadreg(0, CurrentReg);
  8090. taicpu(hp2).loadreg(1, CurrentReg);
  8091. taicpu(hp2).loadreg(2, CurrentReg);
  8092. taicpu(hp2).ops := 3;
  8093. end;
  8094. RemoveInstruction(hp3);
  8095. Result := True;
  8096. Exit;
  8097. end;
  8098. end
  8099. else
  8100. begin
  8101. { See if the next references are 16 less rather than 16 greater }
  8102. Dec(SourceRef.offset, 32); { -16 the other way }
  8103. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8104. begin
  8105. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8106. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8107. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8108. GetNextInstruction(hp2, hp3) and
  8109. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8110. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8111. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8112. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8113. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8114. begin
  8115. { Update the register tracking to the new size }
  8116. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8117. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8118. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8119. if not(
  8120. ((SourceRef.offset mod 32) = 0) and
  8121. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8122. ) then
  8123. taicpu(hp2).opcode := A_VMOVDQU;
  8124. taicpu(hp2).opsize := S_YMM;
  8125. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8126. if not (
  8127. ((TargetRef.offset mod 32) = 0) and
  8128. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8129. ) then
  8130. taicpu(hp3).opcode := A_VMOVDQU;
  8131. taicpu(hp3).opsize := S_YMM;
  8132. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8133. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8134. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8135. if (pi_uses_ymm in current_procinfo.flags) then
  8136. RemoveInstruction(hp1)
  8137. else
  8138. begin
  8139. taicpu(hp1).opcode := A_VPXOR;
  8140. taicpu(hp1).opsize := S_YMM;
  8141. taicpu(hp1).loadreg(0, CurrentReg);
  8142. taicpu(hp1).loadreg(1, CurrentReg);
  8143. taicpu(hp1).loadreg(2, CurrentReg);
  8144. taicpu(hp1).ops := 3;
  8145. Asml.Remove(hp1);
  8146. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8147. end;
  8148. RemoveCurrentP(p, hp2);
  8149. Result := True;
  8150. Exit;
  8151. end;
  8152. end;
  8153. end;
  8154. end;
  8155. end;
  8156. end;
  8157. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8158. var
  8159. hp2, hp3, first_assignment: tai;
  8160. IncCount, OperIdx: Integer;
  8161. OrigLabel: TAsmLabel;
  8162. begin
  8163. Count := 0;
  8164. Result := False;
  8165. first_assignment := nil;
  8166. if (LoopCount >= 20) then
  8167. begin
  8168. { Guard against infinite loops }
  8169. Exit;
  8170. end;
  8171. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8172. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8173. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8174. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8175. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8176. Exit;
  8177. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8178. {
  8179. change
  8180. jmp .L1
  8181. ...
  8182. .L1:
  8183. mov ##, ## ( multiple movs possible )
  8184. jmp/ret
  8185. into
  8186. mov ##, ##
  8187. jmp/ret
  8188. }
  8189. if not Assigned(hp1) then
  8190. begin
  8191. hp1 := GetLabelWithSym(OrigLabel);
  8192. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8193. Exit;
  8194. end;
  8195. hp2 := hp1;
  8196. while Assigned(hp2) do
  8197. begin
  8198. if Assigned(hp2) and (hp2.typ = ait_label) then
  8199. SkipLabels(hp2,hp2);
  8200. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8201. Break;
  8202. case taicpu(hp2).opcode of
  8203. A_MOVSD:
  8204. begin
  8205. if taicpu(hp2).ops = 0 then
  8206. { Wrong MOVSD }
  8207. Break;
  8208. Inc(Count);
  8209. if Count >= 5 then
  8210. { Too many to be worthwhile }
  8211. Break;
  8212. GetNextInstruction(hp2, hp2);
  8213. Continue;
  8214. end;
  8215. A_MOV,
  8216. A_MOVD,
  8217. A_MOVQ,
  8218. A_MOVSX,
  8219. {$ifdef x86_64}
  8220. A_MOVSXD,
  8221. {$endif x86_64}
  8222. A_MOVZX,
  8223. A_MOVAPS,
  8224. A_MOVUPS,
  8225. A_MOVSS,
  8226. A_MOVAPD,
  8227. A_MOVUPD,
  8228. A_MOVDQA,
  8229. A_MOVDQU,
  8230. A_VMOVSS,
  8231. A_VMOVAPS,
  8232. A_VMOVUPS,
  8233. A_VMOVSD,
  8234. A_VMOVAPD,
  8235. A_VMOVUPD,
  8236. A_VMOVDQA,
  8237. A_VMOVDQU:
  8238. begin
  8239. Inc(Count);
  8240. if Count >= 5 then
  8241. { Too many to be worthwhile }
  8242. Break;
  8243. GetNextInstruction(hp2, hp2);
  8244. Continue;
  8245. end;
  8246. A_JMP:
  8247. begin
  8248. { Guard against infinite loops }
  8249. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8250. Exit;
  8251. { Analyse this jump first in case it also duplicates assignments }
  8252. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8253. begin
  8254. { Something did change! }
  8255. Result := True;
  8256. Inc(Count, IncCount);
  8257. if Count >= 5 then
  8258. begin
  8259. { Too many to be worthwhile }
  8260. Exit;
  8261. end;
  8262. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8263. Break;
  8264. end;
  8265. Result := True;
  8266. Break;
  8267. end;
  8268. A_RET:
  8269. begin
  8270. Result := True;
  8271. Break;
  8272. end;
  8273. else
  8274. Break;
  8275. end;
  8276. end;
  8277. if Result then
  8278. begin
  8279. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8280. if Count = 0 then
  8281. begin
  8282. Result := False;
  8283. Exit;
  8284. end;
  8285. hp3 := p;
  8286. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8287. while True do
  8288. begin
  8289. if Assigned(hp1) and (hp1.typ = ait_label) then
  8290. SkipLabels(hp1,hp1);
  8291. if (hp1.typ <> ait_instruction) then
  8292. InternalError(2021040720);
  8293. case taicpu(hp1).opcode of
  8294. A_JMP:
  8295. begin
  8296. { Change the original jump to the new destination }
  8297. OrigLabel.decrefs;
  8298. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8299. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8300. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8301. if not Assigned(first_assignment) then
  8302. InternalError(2021040810)
  8303. else
  8304. p := first_assignment;
  8305. Exit;
  8306. end;
  8307. A_RET:
  8308. begin
  8309. { Now change the jump into a RET instruction }
  8310. ConvertJumpToRET(p, hp1);
  8311. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8312. if not Assigned(first_assignment) then
  8313. InternalError(2021040811)
  8314. else
  8315. p := first_assignment;
  8316. Exit;
  8317. end;
  8318. else
  8319. begin
  8320. { Duplicate the MOV instruction }
  8321. hp3:=tai(hp1.getcopy);
  8322. if first_assignment = nil then
  8323. first_assignment := hp3;
  8324. asml.InsertBefore(hp3, p);
  8325. { Make sure the compiler knows about any final registers written here }
  8326. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8327. with taicpu(hp3).oper[OperIdx]^ do
  8328. begin
  8329. case typ of
  8330. top_ref:
  8331. begin
  8332. if (ref^.base <> NR_NO) and
  8333. (getsupreg(ref^.base) <> RS_ESP) and
  8334. (getsupreg(ref^.base) <> RS_EBP)
  8335. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8336. then
  8337. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8338. if (ref^.index <> NR_NO) and
  8339. (getsupreg(ref^.index) <> RS_ESP) and
  8340. (getsupreg(ref^.index) <> RS_EBP)
  8341. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8342. (ref^.index <> ref^.base) then
  8343. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8344. end;
  8345. top_reg:
  8346. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8347. else
  8348. ;
  8349. end;
  8350. end;
  8351. end;
  8352. end;
  8353. if not GetNextInstruction(hp1, hp1) then
  8354. { Should have dropped out earlier }
  8355. InternalError(2021040710);
  8356. end;
  8357. end;
  8358. end;
  8359. const
  8360. WriteOp: array[0..3] of set of TInsChange = (
  8361. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8362. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8363. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8364. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8365. RegWriteFlags: array[0..7] of set of TInsChange = (
  8366. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8367. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8368. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8369. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8370. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8371. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8372. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8373. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8374. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8375. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8376. var
  8377. hp2: tai;
  8378. X: Integer;
  8379. begin
  8380. { If we have something like:
  8381. op ###,###
  8382. mov ###,###
  8383. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8384. interfere in regards to what they write to.
  8385. NOTE: p must be a 2-operand instruction
  8386. }
  8387. Result := False;
  8388. if (hp1.typ <> ait_instruction) or
  8389. taicpu(hp1).is_jmp or
  8390. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8391. Exit;
  8392. { NOP is a pipeline fence, likely marking the beginning of the function
  8393. epilogue, so drop out. Similarly, drop out if POP or RET are
  8394. encountered }
  8395. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8396. Exit;
  8397. if (taicpu(hp1).opcode = A_MOVSD) and
  8398. (taicpu(hp1).ops = 0) then
  8399. { Wrong MOVSD }
  8400. Exit;
  8401. { Check for writes to specific registers first }
  8402. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8403. for X := 0 to 7 do
  8404. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8405. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8406. Exit;
  8407. for X := 0 to taicpu(hp1).ops - 1 do
  8408. begin
  8409. { Check to see if this operand writes to something }
  8410. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8411. { And matches something in the CMP/TEST instruction }
  8412. (
  8413. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8414. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8415. (
  8416. { If it's a register, make sure the register written to doesn't
  8417. appear in the cmp instruction as part of a reference }
  8418. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8419. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8420. )
  8421. ) then
  8422. Exit;
  8423. end;
  8424. { Check p to make sure it doesn't write to something that affects hp1 }
  8425. { Check for writes to specific registers first }
  8426. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8427. for X := 0 to 7 do
  8428. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8429. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8430. Exit;
  8431. for X := 0 to taicpu(p).ops - 1 do
  8432. begin
  8433. { Check to see if this operand writes to something }
  8434. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8435. { And matches something in hp1 }
  8436. (taicpu(p).oper[X]^.typ = top_reg) and
  8437. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8438. Exit;
  8439. end;
  8440. { The instruction can be safely moved }
  8441. asml.Remove(hp1);
  8442. { Try to insert after the last instructions where the FLAGS register is not
  8443. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8444. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8445. asml.InsertBefore(hp1, hp2)
  8446. { Failing that, try to insert after the last instructions where the
  8447. FLAGS register is not yet in use }
  8448. else if GetLastInstruction(p, hp2) and
  8449. (
  8450. (hp2.typ <> ait_instruction) or
  8451. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8452. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8453. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8454. ) then
  8455. asml.InsertAfter(hp1, hp2)
  8456. else
  8457. { Note, if p.Previous is nil (even if it should logically never be the
  8458. case), FindRegAllocBackward immediately exits with False and so we
  8459. safely land here (we can't just pass p because FindRegAllocBackward
  8460. immediately exits on an instruction). [Kit] }
  8461. asml.InsertBefore(hp1, p);
  8462. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8463. { We can't trust UsedRegs because we're looking backwards, although we
  8464. know the registers are allocated after p at the very least, so manually
  8465. create tai_regalloc objects if needed }
  8466. for X := 0 to taicpu(hp1).ops - 1 do
  8467. case taicpu(hp1).oper[X]^.typ of
  8468. top_reg:
  8469. begin
  8470. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8471. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8472. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8473. end;
  8474. top_ref:
  8475. begin
  8476. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8477. begin
  8478. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8479. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8480. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8481. end;
  8482. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8483. begin
  8484. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8485. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8486. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8487. end;
  8488. end;
  8489. else
  8490. ;
  8491. end;
  8492. Result := True;
  8493. end;
  8494. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8495. var
  8496. hp2: tai;
  8497. X: Integer;
  8498. begin
  8499. { If we have something like:
  8500. cmp ###,%reg1
  8501. mov 0,%reg2
  8502. And no modified registers are shared, move the instruction to before
  8503. the comparison as this means it can be optimised without worrying
  8504. about the FLAGS register. (CMP/MOV is generated by
  8505. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8506. As long as the second instruction doesn't use the flags or one of the
  8507. registers used by CMP or TEST (also check any references that use the
  8508. registers), then it can be moved prior to the comparison.
  8509. }
  8510. Result := False;
  8511. if not TrySwapMovOp(p, hp1) then
  8512. Exit;
  8513. if taicpu(hp1).opcode = A_LEA then
  8514. { The flags will be overwritten by the CMP/TEST instruction }
  8515. ConvertLEA(taicpu(hp1));
  8516. Result := True;
  8517. { Can we move it one further back? }
  8518. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8519. { Check to see if CMP/TEST is a comparison against zero }
  8520. (
  8521. (
  8522. (taicpu(p).opcode = A_CMP) and
  8523. MatchOperand(taicpu(p).oper[0]^, 0)
  8524. ) or
  8525. (
  8526. (taicpu(p).opcode = A_TEST) and
  8527. (
  8528. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8529. MatchOperand(taicpu(p).oper[0]^, -1)
  8530. )
  8531. )
  8532. ) and
  8533. { These instructions set the zero flag if the result is zero }
  8534. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8535. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8536. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8537. TrySwapMovOp(hp2, hp1);
  8538. end;
  8539. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  8540. var
  8541. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  8542. JumpLabel: TAsmLabel;
  8543. TmpBool: Boolean;
  8544. begin
  8545. Result := False;
  8546. { Look for:
  8547. stc/clc
  8548. j(c) .L1
  8549. ...
  8550. .L1:
  8551. set(n)cb %reg
  8552. (flags deallocated)
  8553. j(c) .L2
  8554. Change to:
  8555. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  8556. j(c) .L2
  8557. }
  8558. p_last := p;
  8559. while GetNextInstruction(p_last, hp1) and
  8560. (hp1.typ = ait_instruction) and
  8561. IsJumpToLabel(taicpu(hp1)) do
  8562. begin
  8563. if DoJumpOptimizations(hp1, TmpBool) then
  8564. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8565. Continue;
  8566. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  8567. if not Assigned(JumpLabel) then
  8568. InternalError(2024012801);
  8569. { Optimise the J(c); stc/clc optimisation first since this will
  8570. get missed if the main optimisation takes place }
  8571. if (taicpu(hp1).opcode = A_JCC) then
  8572. begin
  8573. if GetNextInstruction(hp1, hp2) and
  8574. MatchInstruction(hp2, A_CLC, A_STC, []) and
  8575. TryJccStcClcOpt(hp1, hp2) then
  8576. begin
  8577. Result := True;
  8578. Exit;
  8579. end;
  8580. hp2 := nil; { Suppress compiler warning }
  8581. if (taicpu(hp1).condition in [C_C, C_NC]) and
  8582. { Make sure the flags aren't used again }
  8583. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  8584. begin
  8585. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8586. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  8587. begin
  8588. if (taicpu(p).opcode = A_STC) then
  8589. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  8590. else
  8591. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  8592. MakeUnconditional(taicpu(hp1));
  8593. { Move the jump to after the flag deallocations }
  8594. Asml.Remove(hp1);
  8595. Asml.InsertAfter(hp1, hp2);
  8596. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8597. Result := True;
  8598. Exit;
  8599. end
  8600. else
  8601. begin
  8602. if (taicpu(p).opcode = A_STC) then
  8603. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  8604. else
  8605. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  8606. { In this case, the jump is deterministic in that it will never be taken }
  8607. JumpLabel.DecRefs;
  8608. RemoveInstruction(hp1);
  8609. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  8610. Result := True;
  8611. Exit;
  8612. end;
  8613. end;
  8614. end;
  8615. hp2 := nil; { Suppress compiler warning }
  8616. if
  8617. { Make sure the carry flag doesn't appear in the jump conditions }
  8618. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8619. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  8620. GetNextInstruction(hp2, p_dist) and
  8621. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  8622. (taicpu(p_dist).condition in [C_C, C_NC]) then
  8623. begin
  8624. case taicpu(p_dist).opcode of
  8625. A_Jcc:
  8626. begin
  8627. if DoJumpOptimizations(p_dist, TmpBool) then
  8628. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8629. Continue;
  8630. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8631. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  8632. begin
  8633. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  8634. JumpLabel.decrefs;
  8635. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  8636. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8637. Result := True;
  8638. Exit;
  8639. end
  8640. else if GetNextInstruction(p_dist, hp1_dist) and
  8641. (hp1_dist.typ = ait_label) then
  8642. begin
  8643. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  8644. JumpLabel.decrefs;
  8645. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  8646. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8647. Result := True;
  8648. Exit;
  8649. end;
  8650. end;
  8651. A_SETcc:
  8652. if { Make sure the flags aren't used again }
  8653. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  8654. GetNextInstruction(hp2, hp1_dist) and
  8655. (hp1_dist.typ = ait_instruction) and
  8656. IsJumpToLabel(taicpu(hp1_dist)) and
  8657. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8658. { This works if hp1_dist or both are regular JMP instructions }
  8659. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  8660. (
  8661. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  8662. { Make sure the register isn't still in use, otherwise it
  8663. may get corrupted (fixes #40659) }
  8664. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  8665. ) then
  8666. begin
  8667. taicpu(p).allocate_oper(2);
  8668. taicpu(p).ops := 2;
  8669. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  8670. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  8671. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  8672. taicpu(p).opcode := A_MOV;
  8673. taicpu(p).opsize := S_B;
  8674. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8675. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  8676. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  8677. JumpLabel.decrefs;
  8678. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  8679. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  8680. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  8681. (tai_regalloc(hp2).ratype = ra_alloc) then
  8682. begin
  8683. Asml.Remove(hp2);
  8684. Asml.InsertAfter(hp2, p);
  8685. end;
  8686. Result := True;
  8687. Exit;
  8688. end;
  8689. else
  8690. ;
  8691. end;
  8692. end;
  8693. p_last := hp1;
  8694. end;
  8695. end;
  8696. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  8697. var
  8698. hp2, hp3: tai;
  8699. TempBool: Boolean;
  8700. begin
  8701. Result := False;
  8702. {
  8703. j(c) .L1
  8704. stc/clc
  8705. .L1:
  8706. jc/jnc .L2
  8707. (Flags deallocated)
  8708. Change to:
  8709. j)c) .L1
  8710. jmp .L2
  8711. .L1:
  8712. jc/jnc .L2
  8713. Then call DoJumpOptimizations to convert to:
  8714. j(nc) .L2
  8715. .L1: (may become a dead label)
  8716. jc/jnc .L2
  8717. }
  8718. if GetNextInstruction(hp1, hp2) and
  8719. (hp2.typ = ait_label) and
  8720. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  8721. GetNextInstruction(hp2, hp3) and
  8722. MatchInstruction(hp3, A_Jcc, []) and
  8723. (
  8724. (
  8725. (taicpu(hp3).condition = C_C) and
  8726. (taicpu(hp1).opcode = A_STC)
  8727. ) or (
  8728. (taicpu(hp3).condition = C_NC) and
  8729. (taicpu(hp1).opcode = A_CLC)
  8730. )
  8731. ) and
  8732. { Make sure the flags aren't used again }
  8733. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  8734. begin
  8735. taicpu(hp1).allocate_oper(1);
  8736. taicpu(hp1).ops := 1;
  8737. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  8738. taicpu(hp1).opcode := A_JMP;
  8739. taicpu(hp1).is_jmp := True;
  8740. TempBool := True; { Prevent compiler warnings }
  8741. if DoJumpOptimizations(p, TempBool) then
  8742. Result := True
  8743. else
  8744. Include(OptsToCheck, aoc_ForceNewIteration);
  8745. end;
  8746. end;
  8747. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  8748. begin
  8749. { This generally only executes under -O3 and above }
  8750. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  8751. end;
  8752. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8753. function IsXCHGAcceptable: Boolean; inline;
  8754. begin
  8755. { Always accept if optimising for size }
  8756. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8757. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8758. than 3, so it becomes a saving compared to three MOVs with two of
  8759. them able to execute simultaneously. [Kit] }
  8760. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8761. end;
  8762. var
  8763. NewRef: TReference;
  8764. hp1, hp2, hp3, hp4: Tai;
  8765. {$ifndef x86_64}
  8766. OperIdx: Integer;
  8767. {$endif x86_64}
  8768. NewInstr : Taicpu;
  8769. NewAligh : Tai_align;
  8770. DestLabel: TAsmLabel;
  8771. TempTracking: TAllUsedRegs;
  8772. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8773. var
  8774. NextInstr: tai;
  8775. begin
  8776. Result := False;
  8777. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8778. if not GetNextInstruction(InputInstr, NextInstr) or
  8779. (
  8780. { The FLAGS register isn't always tracked properly, so do not
  8781. perform this optimisation if a conditional statement follows }
  8782. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8783. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8784. ) then
  8785. begin
  8786. reference_reset(NewRef, 1, []);
  8787. NewRef.base := taicpu(p).oper[0]^.reg;
  8788. NewRef.scalefactor := 1;
  8789. if taicpu(InputInstr).opcode = A_ADD then
  8790. begin
  8791. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8792. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8793. end
  8794. else
  8795. begin
  8796. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8797. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8798. end;
  8799. taicpu(p).opcode := A_LEA;
  8800. taicpu(p).loadref(0, NewRef);
  8801. RemoveInstruction(InputInstr);
  8802. Result := True;
  8803. end;
  8804. end;
  8805. begin
  8806. Result:=false;
  8807. { This optimisation adds an instruction, so only do it for speed }
  8808. if not (cs_opt_size in current_settings.optimizerswitches) and
  8809. MatchOpType(taicpu(p), top_const, top_reg) and
  8810. (taicpu(p).oper[0]^.val = 0) then
  8811. begin
  8812. { To avoid compiler warning }
  8813. DestLabel := nil;
  8814. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8815. InternalError(2021040750);
  8816. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8817. Exit;
  8818. case hp1.typ of
  8819. ait_label:
  8820. begin
  8821. { Change:
  8822. mov $0,%reg mov $0,%reg
  8823. @Lbl1: @Lbl1:
  8824. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8825. je @Lbl2 jne @Lbl2
  8826. To: To:
  8827. mov $0,%reg mov $0,%reg
  8828. jmp @Lbl2 jmp @Lbl3
  8829. (align) (align)
  8830. @Lbl1: @Lbl1:
  8831. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8832. je @Lbl2 je @Lbl2
  8833. @Lbl3: <-- Only if label exists
  8834. (Not if it's optimised for size)
  8835. }
  8836. if not GetNextInstruction(hp1, hp2) then
  8837. Exit;
  8838. if (hp2.typ = ait_instruction) and
  8839. (
  8840. { Register sizes must exactly match }
  8841. (
  8842. (taicpu(hp2).opcode = A_CMP) and
  8843. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8844. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8845. ) or (
  8846. (taicpu(hp2).opcode = A_TEST) and
  8847. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8848. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8849. )
  8850. ) and GetNextInstruction(hp2, hp3) and
  8851. (hp3.typ = ait_instruction) and
  8852. (taicpu(hp3).opcode = A_JCC) and
  8853. (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
  8854. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8855. begin
  8856. { Check condition of jump }
  8857. { Always true? }
  8858. if condition_in(C_E, taicpu(hp3).condition) then
  8859. begin
  8860. { Copy label symbol and obtain matching label entry for the
  8861. conditional jump, as this will be our destination}
  8862. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8863. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8864. Result := True;
  8865. end
  8866. { Always false? }
  8867. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8868. begin
  8869. { This is only worth it if there's a jump to take }
  8870. case hp2.typ of
  8871. ait_instruction:
  8872. begin
  8873. if taicpu(hp2).opcode = A_JMP then
  8874. begin
  8875. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8876. { An unconditional jump follows the conditional jump which will always be false,
  8877. so use this jump's destination for the new jump }
  8878. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8879. Result := True;
  8880. end
  8881. else if taicpu(hp2).opcode = A_JCC then
  8882. begin
  8883. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8884. if condition_in(C_E, taicpu(hp2).condition) then
  8885. begin
  8886. { A second conditional jump follows the conditional jump which will always be false,
  8887. while the second jump is always True, so use this jump's destination for the new jump }
  8888. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8889. Result := True;
  8890. end;
  8891. { Don't risk it if the jump isn't always true (Result remains False) }
  8892. end;
  8893. end;
  8894. else
  8895. { If anything else don't optimise };
  8896. end;
  8897. end;
  8898. if Result then
  8899. begin
  8900. { Just so we have something to insert as a paremeter}
  8901. reference_reset(NewRef, 1, []);
  8902. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8903. { Now actually load the correct parameter (this also
  8904. increases the reference count) }
  8905. NewInstr.loadsymbol(0, DestLabel, 0);
  8906. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8907. begin
  8908. { Get instruction before original label (may not be p under -O3) }
  8909. if not GetLastInstruction(hp1, hp2) then
  8910. { Shouldn't fail here }
  8911. InternalError(2021040701);
  8912. end
  8913. else
  8914. hp2 := p;
  8915. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8916. AsmL.InsertAfter(NewInstr, hp2);
  8917. { Add new alignment field }
  8918. (* AsmL.InsertAfter(
  8919. cai_align.create_max(
  8920. current_settings.alignment.jumpalign,
  8921. current_settings.alignment.jumpalignskipmax
  8922. ),
  8923. NewInstr
  8924. ); *)
  8925. end;
  8926. Exit;
  8927. end;
  8928. end;
  8929. else
  8930. ;
  8931. end;
  8932. end;
  8933. if not GetNextInstruction(p, hp1) then
  8934. Exit;
  8935. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8936. and DoMovCmpMemOpt(p, hp1) then
  8937. begin
  8938. Result := True;
  8939. Exit;
  8940. end
  8941. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8942. begin
  8943. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8944. further, but we can't just put this jump optimisation in pass 1
  8945. because it tends to perform worse when conditional jumps are
  8946. nearby (e.g. when converting CMOV instructions). [Kit] }
  8947. CopyUsedRegs(TempTracking);
  8948. UpdateUsedRegs(tai(p.Next));
  8949. if OptPass2JMP(hp1) then
  8950. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8951. Result := OptPass1MOV(p);
  8952. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8953. returned True and the instruction is still a MOV, thus checking
  8954. the optimisations below }
  8955. { If OptPass2JMP returned False, no optimisations were done to
  8956. the jump and there are no further optimisations that can be done
  8957. to the MOV instruction on this pass }
  8958. { Restore register state }
  8959. RestoreUsedRegs(TempTracking);
  8960. ReleaseUsedRegs(TempTracking);
  8961. end
  8962. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8963. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8964. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8965. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8966. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8967. begin
  8968. { Change:
  8969. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8970. addl/q $x,%reg2 subl/q $x,%reg2
  8971. To:
  8972. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8973. }
  8974. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8975. { be lazy, checking separately for sub would be slightly better }
  8976. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8977. begin
  8978. TransferUsedRegs(TmpUsedRegs);
  8979. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8980. if TryMovArith2Lea(hp1) then
  8981. begin
  8982. Result := True;
  8983. Exit;
  8984. end
  8985. end
  8986. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8987. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8988. { Same as above, but also adds or subtracts to %reg2 in between.
  8989. It's still valid as long as the flags aren't in use }
  8990. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8991. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8992. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8993. { be lazy, checking separately for sub would be slightly better }
  8994. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8995. begin
  8996. TransferUsedRegs(TmpUsedRegs);
  8997. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8998. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8999. if TryMovArith2Lea(hp2) then
  9000. begin
  9001. Result := True;
  9002. Exit;
  9003. end;
  9004. end;
  9005. end
  9006. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  9007. {$ifdef x86_64}
  9008. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9009. {$else x86_64}
  9010. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9011. {$endif x86_64}
  9012. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9013. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9014. { mov reg1, reg2 mov reg1, reg2
  9015. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9016. begin
  9017. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9018. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9019. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9020. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9021. TransferUsedRegs(TmpUsedRegs);
  9022. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9023. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9024. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9025. then
  9026. begin
  9027. RemoveCurrentP(p, hp1);
  9028. Result:=true;
  9029. end;
  9030. exit;
  9031. end
  9032. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  9033. IsXCHGAcceptable and
  9034. { XCHG doesn't support 8-byte registers }
  9035. (taicpu(p).opsize <> S_B) and
  9036. MatchInstruction(hp1, A_MOV, []) and
  9037. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9038. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9039. GetNextInstruction(hp1, hp2) and
  9040. MatchInstruction(hp2, A_MOV, []) and
  9041. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9042. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9043. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9044. begin
  9045. { mov %reg1,%reg2
  9046. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9047. mov %reg2,%reg3
  9048. (%reg2 not used afterwards)
  9049. Note that xchg takes 3 cycles to execute, and generally mov's take
  9050. only one cycle apiece, but the first two mov's can be executed in
  9051. parallel, only taking 2 cycles overall. Older processors should
  9052. therefore only optimise for size. [Kit]
  9053. }
  9054. TransferUsedRegs(TmpUsedRegs);
  9055. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9056. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9057. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9058. begin
  9059. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9060. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9061. taicpu(hp1).opcode := A_XCHG;
  9062. RemoveCurrentP(p, hp1);
  9063. RemoveInstruction(hp2);
  9064. Result := True;
  9065. Exit;
  9066. end;
  9067. end
  9068. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  9069. MatchInstruction(hp1, A_SAR, []) then
  9070. begin
  9071. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9072. begin
  9073. { the use of %edx also covers the opsize being S_L }
  9074. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9075. begin
  9076. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9077. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9078. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9079. begin
  9080. { Change:
  9081. movl %eax,%edx
  9082. sarl $31,%edx
  9083. To:
  9084. cltd
  9085. }
  9086. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9087. RemoveInstruction(hp1);
  9088. taicpu(p).opcode := A_CDQ;
  9089. taicpu(p).opsize := S_NO;
  9090. taicpu(p).clearop(1);
  9091. taicpu(p).clearop(0);
  9092. taicpu(p).ops:=0;
  9093. Result := True;
  9094. end
  9095. else if (cs_opt_size in current_settings.optimizerswitches) and
  9096. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9097. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9098. begin
  9099. { Change:
  9100. movl %edx,%eax
  9101. sarl $31,%edx
  9102. To:
  9103. movl %edx,%eax
  9104. cltd
  9105. Note that this creates a dependency between the two instructions,
  9106. so only perform if optimising for size.
  9107. }
  9108. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9109. taicpu(hp1).opcode := A_CDQ;
  9110. taicpu(hp1).opsize := S_NO;
  9111. taicpu(hp1).clearop(1);
  9112. taicpu(hp1).clearop(0);
  9113. taicpu(hp1).ops:=0;
  9114. end;
  9115. {$ifndef x86_64}
  9116. end
  9117. { Don't bother if CMOV is supported, because a more optimal
  9118. sequence would have been generated for the Abs() intrinsic }
  9119. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9120. { the use of %eax also covers the opsize being S_L }
  9121. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9122. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9123. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9124. GetNextInstruction(hp1, hp2) and
  9125. MatchInstruction(hp2, A_XOR, [S_L]) and
  9126. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9127. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9128. GetNextInstruction(hp2, hp3) and
  9129. MatchInstruction(hp3, A_SUB, [S_L]) and
  9130. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9131. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9132. begin
  9133. { Change:
  9134. movl %eax,%edx
  9135. sarl $31,%eax
  9136. xorl %eax,%edx
  9137. subl %eax,%edx
  9138. (Instruction that uses %edx)
  9139. (%eax deallocated)
  9140. (%edx deallocated)
  9141. To:
  9142. cltd
  9143. xorl %edx,%eax <-- Note the registers have swapped
  9144. subl %edx,%eax
  9145. (Instruction that uses %eax) <-- %eax rather than %edx
  9146. }
  9147. TransferUsedRegs(TmpUsedRegs);
  9148. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9149. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9150. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9151. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9152. begin
  9153. if GetNextInstruction(hp3, hp4) and
  9154. not RegModifiedByInstruction(NR_EDX, hp4) and
  9155. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9156. begin
  9157. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9158. taicpu(p).opcode := A_CDQ;
  9159. taicpu(p).clearop(1);
  9160. taicpu(p).clearop(0);
  9161. taicpu(p).ops:=0;
  9162. RemoveInstruction(hp1);
  9163. taicpu(hp2).loadreg(0, NR_EDX);
  9164. taicpu(hp2).loadreg(1, NR_EAX);
  9165. taicpu(hp3).loadreg(0, NR_EDX);
  9166. taicpu(hp3).loadreg(1, NR_EAX);
  9167. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9168. { Convert references in the following instruction (hp4) from %edx to %eax }
  9169. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9170. with taicpu(hp4).oper[OperIdx]^ do
  9171. case typ of
  9172. top_reg:
  9173. if getsupreg(reg) = RS_EDX then
  9174. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9175. top_ref:
  9176. begin
  9177. if getsupreg(reg) = RS_EDX then
  9178. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9179. if getsupreg(reg) = RS_EDX then
  9180. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9181. end;
  9182. else
  9183. ;
  9184. end;
  9185. end;
  9186. end;
  9187. {$else x86_64}
  9188. end;
  9189. end
  9190. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9191. { the use of %rdx also covers the opsize being S_Q }
  9192. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9193. begin
  9194. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9195. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9196. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9197. begin
  9198. { Change:
  9199. movq %rax,%rdx
  9200. sarq $63,%rdx
  9201. To:
  9202. cqto
  9203. }
  9204. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9205. RemoveInstruction(hp1);
  9206. taicpu(p).opcode := A_CQO;
  9207. taicpu(p).opsize := S_NO;
  9208. taicpu(p).clearop(1);
  9209. taicpu(p).clearop(0);
  9210. taicpu(p).ops:=0;
  9211. Result := True;
  9212. end
  9213. else if (cs_opt_size in current_settings.optimizerswitches) and
  9214. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9215. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9216. begin
  9217. { Change:
  9218. movq %rdx,%rax
  9219. sarq $63,%rdx
  9220. To:
  9221. movq %rdx,%rax
  9222. cqto
  9223. Note that this creates a dependency between the two instructions,
  9224. so only perform if optimising for size.
  9225. }
  9226. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9227. taicpu(hp1).opcode := A_CQO;
  9228. taicpu(hp1).opsize := S_NO;
  9229. taicpu(hp1).clearop(1);
  9230. taicpu(hp1).clearop(0);
  9231. taicpu(hp1).ops:=0;
  9232. {$endif x86_64}
  9233. end;
  9234. end;
  9235. end
  9236. else if MatchInstruction(hp1, A_MOV, []) and
  9237. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9238. { Though "GetNextInstruction" could be factored out, along with
  9239. the instructions that depend on hp2, it is an expensive call that
  9240. should be delayed for as long as possible, hence we do cheaper
  9241. checks first that are likely to be False. [Kit] }
  9242. begin
  9243. if (
  9244. (
  9245. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9246. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9247. (
  9248. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9249. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9250. )
  9251. ) or
  9252. (
  9253. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9254. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9255. (
  9256. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9257. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9258. )
  9259. )
  9260. ) and
  9261. GetNextInstruction(hp1, hp2) and
  9262. MatchInstruction(hp2, A_SAR, []) and
  9263. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9264. begin
  9265. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9266. begin
  9267. { Change:
  9268. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9269. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9270. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9271. To:
  9272. movl r/m,%eax <- Note the change in register
  9273. cltd
  9274. }
  9275. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9276. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9277. taicpu(p).loadreg(1, NR_EAX);
  9278. taicpu(hp1).opcode := A_CDQ;
  9279. taicpu(hp1).clearop(1);
  9280. taicpu(hp1).clearop(0);
  9281. taicpu(hp1).ops:=0;
  9282. RemoveInstruction(hp2);
  9283. (*
  9284. {$ifdef x86_64}
  9285. end
  9286. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9287. { This code sequence does not get generated - however it might become useful
  9288. if and when 128-bit signed integer types make an appearance, so the code
  9289. is kept here for when it is eventually needed. [Kit] }
  9290. (
  9291. (
  9292. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9293. (
  9294. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9295. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9296. )
  9297. ) or
  9298. (
  9299. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9300. (
  9301. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9302. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9303. )
  9304. )
  9305. ) and
  9306. GetNextInstruction(hp1, hp2) and
  9307. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9308. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9309. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9310. begin
  9311. { Change:
  9312. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9313. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9314. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9315. To:
  9316. movq r/m,%rax <- Note the change in register
  9317. cqto
  9318. }
  9319. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9320. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9321. taicpu(p).loadreg(1, NR_RAX);
  9322. taicpu(hp1).opcode := A_CQO;
  9323. taicpu(hp1).clearop(1);
  9324. taicpu(hp1).clearop(0);
  9325. taicpu(hp1).ops:=0;
  9326. RemoveInstruction(hp2);
  9327. {$endif x86_64}
  9328. *)
  9329. end;
  9330. end;
  9331. {$ifdef x86_64}
  9332. end
  9333. else if (taicpu(p).opsize = S_L) and
  9334. (taicpu(p).oper[1]^.typ = top_reg) and
  9335. (
  9336. MatchInstruction(hp1, A_MOV,[]) and
  9337. (taicpu(hp1).opsize = S_L) and
  9338. (taicpu(hp1).oper[1]^.typ = top_reg)
  9339. ) and (
  9340. GetNextInstruction(hp1, hp2) and
  9341. (tai(hp2).typ=ait_instruction) and
  9342. (taicpu(hp2).opsize = S_Q) and
  9343. (
  9344. (
  9345. MatchInstruction(hp2, A_ADD,[]) and
  9346. (taicpu(hp2).opsize = S_Q) and
  9347. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9348. (
  9349. (
  9350. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9351. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9352. ) or (
  9353. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9354. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9355. )
  9356. )
  9357. ) or (
  9358. MatchInstruction(hp2, A_LEA,[]) and
  9359. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9360. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9361. (
  9362. (
  9363. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9364. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9365. ) or (
  9366. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9367. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9368. )
  9369. ) and (
  9370. (
  9371. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9372. ) or (
  9373. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9374. )
  9375. )
  9376. )
  9377. )
  9378. ) and (
  9379. GetNextInstruction(hp2, hp3) and
  9380. MatchInstruction(hp3, A_SHR,[]) and
  9381. (taicpu(hp3).opsize = S_Q) and
  9382. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9383. (taicpu(hp3).oper[0]^.val = 1) and
  9384. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9385. ) then
  9386. begin
  9387. { Change movl x, reg1d movl x, reg1d
  9388. movl y, reg2d movl y, reg2d
  9389. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9390. shrq $1, reg1q shrq $1, reg1q
  9391. ( reg1d and reg2d can be switched around in the first two instructions )
  9392. To movl x, reg1d
  9393. addl y, reg1d
  9394. rcrl $1, reg1d
  9395. This corresponds to the common expression (x + y) shr 1, where
  9396. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9397. smaller code, but won't account for x + y causing an overflow). [Kit]
  9398. }
  9399. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9400. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9401. { Change first MOV command to have the same register as the final output }
  9402. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  9403. else
  9404. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9405. { Change second MOV command to an ADD command. This is easier than
  9406. converting the existing command because it means we don't have to
  9407. touch 'y', which might be a complicated reference, and also the
  9408. fact that the third command might either be ADD or LEA. [Kit] }
  9409. taicpu(hp1).opcode := A_ADD;
  9410. { Delete old ADD/LEA instruction }
  9411. RemoveInstruction(hp2);
  9412. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9413. taicpu(hp3).opcode := A_RCR;
  9414. taicpu(hp3).changeopsize(S_L);
  9415. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9416. {$endif x86_64}
  9417. end;
  9418. if FuncMov2Func(p, hp1) then
  9419. begin
  9420. Result := True;
  9421. Exit;
  9422. end;
  9423. end;
  9424. {$push}
  9425. {$q-}{$r-}
  9426. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9427. var
  9428. ThisReg: TRegister;
  9429. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9430. TargetSubReg: TSubRegister;
  9431. hp1, hp2: tai;
  9432. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9433. { Store list of found instructions so we don't have to call
  9434. GetNextInstructionUsingReg multiple times }
  9435. InstrList: array of taicpu;
  9436. InstrMax, Index: Integer;
  9437. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9438. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9439. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9440. WorkingValue: TCgInt;
  9441. PreMessage: string;
  9442. { Data flow analysis }
  9443. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9444. BitwiseOnly, OrXorUsed,
  9445. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9446. function CheckOverflowConditions: Boolean;
  9447. begin
  9448. Result := True;
  9449. if (TestValSignedMax > SignedUpperLimit) then
  9450. UpperSignedOverflow := True;
  9451. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9452. LowerSignedOverflow := True;
  9453. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9454. LowerUnsignedOverflow := True;
  9455. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9456. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9457. begin
  9458. { Absolute overflow }
  9459. Result := False;
  9460. Exit;
  9461. end;
  9462. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9463. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9464. ShiftDownOverflow := True;
  9465. if (TestValMin < 0) or (TestValMax < 0) then
  9466. begin
  9467. LowerUnsignedOverflow := True;
  9468. UpperUnsignedOverflow := True;
  9469. end;
  9470. end;
  9471. function AdjustInitialLoadAndSize: Boolean;
  9472. begin
  9473. Result := False;
  9474. if not p_removed then
  9475. begin
  9476. if TargetSize = MinSize then
  9477. begin
  9478. { Convert the input MOVZX to a MOV }
  9479. if (taicpu(p).oper[0]^.typ = top_reg) and
  9480. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9481. begin
  9482. { Or remove it completely! }
  9483. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9484. RemoveCurrentP(p);
  9485. p_removed := True;
  9486. end
  9487. else
  9488. begin
  9489. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9490. taicpu(p).opcode := A_MOV;
  9491. taicpu(p).oper[1]^.reg := ThisReg;
  9492. taicpu(p).opsize := TargetSize;
  9493. end;
  9494. Result := True;
  9495. end
  9496. else if TargetSize <> MaxSize then
  9497. begin
  9498. case MaxSize of
  9499. S_L:
  9500. if TargetSize = S_W then
  9501. begin
  9502. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9503. taicpu(p).opsize := S_BW;
  9504. taicpu(p).oper[1]^.reg := ThisReg;
  9505. Result := True;
  9506. end
  9507. else
  9508. InternalError(2020112341);
  9509. S_W:
  9510. if TargetSize = S_L then
  9511. begin
  9512. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9513. taicpu(p).opsize := S_BL;
  9514. taicpu(p).oper[1]^.reg := ThisReg;
  9515. Result := True;
  9516. end
  9517. else
  9518. InternalError(2020112342);
  9519. else
  9520. ;
  9521. end;
  9522. end
  9523. else if not hp1_removed and not RegInUse then
  9524. begin
  9525. { If we have something like:
  9526. movzbl (oper),%regd
  9527. add x, %regd
  9528. movzbl %regb, %regd
  9529. We can reduce the register size to the input of the final
  9530. movzbl instruction. Overflows won't have any effect.
  9531. }
  9532. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9533. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9534. begin
  9535. TargetSize := S_B;
  9536. setsubreg(ThisReg, R_SUBL);
  9537. Result := True;
  9538. end
  9539. else if (taicpu(p).opsize = S_WL) and
  9540. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9541. begin
  9542. TargetSize := S_W;
  9543. setsubreg(ThisReg, R_SUBW);
  9544. Result := True;
  9545. end;
  9546. if Result then
  9547. begin
  9548. { Convert the input MOVZX to a MOV }
  9549. if (taicpu(p).oper[0]^.typ = top_reg) and
  9550. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9551. begin
  9552. { Or remove it completely! }
  9553. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9554. RemoveCurrentP(p);
  9555. p_removed := True;
  9556. end
  9557. else
  9558. begin
  9559. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9560. taicpu(p).opcode := A_MOV;
  9561. taicpu(p).oper[1]^.reg := ThisReg;
  9562. taicpu(p).opsize := TargetSize;
  9563. end;
  9564. end;
  9565. end;
  9566. end;
  9567. end;
  9568. procedure AdjustFinalLoad;
  9569. begin
  9570. if not LowerUnsignedOverflow then
  9571. begin
  9572. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9573. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9574. begin
  9575. { Convert the output MOVZX to a MOV }
  9576. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9577. begin
  9578. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9579. if (MinSize = S_B) or
  9580. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9581. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9582. begin
  9583. { Remove it completely! }
  9584. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9585. { Be careful; if p = hp1 and p was also removed, p
  9586. will become a dangling pointer }
  9587. if p = hp1 then
  9588. begin
  9589. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9590. p_removed := True;
  9591. end
  9592. else
  9593. RemoveInstruction(hp1);
  9594. hp1_removed := True;
  9595. end;
  9596. end
  9597. else
  9598. begin
  9599. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9600. taicpu(hp1).opcode := A_MOV;
  9601. taicpu(hp1).oper[0]^.reg := ThisReg;
  9602. taicpu(hp1).opsize := TargetSize;
  9603. end;
  9604. end
  9605. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9606. begin
  9607. { Need to change the size of the output }
  9608. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9609. taicpu(hp1).oper[0]^.reg := ThisReg;
  9610. taicpu(hp1).opsize := S_BL;
  9611. end;
  9612. end;
  9613. end;
  9614. function CompressInstructions: Boolean;
  9615. var
  9616. LocalIndex: Integer;
  9617. begin
  9618. Result := False;
  9619. { The objective here is to try to find a combination that
  9620. removes one of the MOV/Z instructions. }
  9621. if (
  9622. (taicpu(p).oper[0]^.typ <> top_reg) or
  9623. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9624. ) and
  9625. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9626. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9627. begin
  9628. { Make a preference to remove the second MOVZX instruction }
  9629. case taicpu(hp1).opsize of
  9630. S_BL, S_WL:
  9631. begin
  9632. TargetSize := S_L;
  9633. TargetSubReg := R_SUBD;
  9634. end;
  9635. S_BW:
  9636. begin
  9637. TargetSize := S_W;
  9638. TargetSubReg := R_SUBW;
  9639. end;
  9640. else
  9641. InternalError(2020112302);
  9642. end;
  9643. end
  9644. else
  9645. begin
  9646. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9647. begin
  9648. { Exceeded lower bound but not upper bound }
  9649. TargetSize := MaxSize;
  9650. end
  9651. else if not LowerUnsignedOverflow then
  9652. begin
  9653. { Size didn't exceed lower bound }
  9654. TargetSize := MinSize;
  9655. end
  9656. else
  9657. Exit;
  9658. end;
  9659. case TargetSize of
  9660. S_B:
  9661. TargetSubReg := R_SUBL;
  9662. S_W:
  9663. TargetSubReg := R_SUBW;
  9664. S_L:
  9665. TargetSubReg := R_SUBD;
  9666. else
  9667. InternalError(2020112350);
  9668. end;
  9669. { Update the register to its new size }
  9670. setsubreg(ThisReg, TargetSubReg);
  9671. RegInUse := False;
  9672. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9673. begin
  9674. { Check to see if the active register is used afterwards;
  9675. if not, we can change it and make a saving. }
  9676. TransferUsedRegs(TmpUsedRegs);
  9677. { The target register may be marked as in use to cross
  9678. a jump to a distant label, so exclude it }
  9679. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9680. hp2 := p;
  9681. repeat
  9682. { Explicitly check for the excluded register (don't include the first
  9683. instruction as it may be reading from here }
  9684. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9685. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9686. begin
  9687. RegInUse := True;
  9688. Break;
  9689. end;
  9690. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9691. if not GetNextInstruction(hp2, hp2) then
  9692. InternalError(2020112340);
  9693. until (hp2 = hp1);
  9694. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9695. { We might still be able to get away with this }
  9696. RegInUse := not
  9697. (
  9698. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9699. (hp2.typ = ait_instruction) and
  9700. (
  9701. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9702. instruction that doesn't actually contain ThisReg }
  9703. (cs_opt_level3 in current_settings.optimizerswitches) or
  9704. RegInInstruction(ThisReg, hp2)
  9705. ) and
  9706. RegLoadedWithNewValue(ThisReg, hp2)
  9707. );
  9708. if not RegInUse then
  9709. begin
  9710. { Force the register size to the same as this instruction so it can be removed}
  9711. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9712. begin
  9713. TargetSize := S_L;
  9714. TargetSubReg := R_SUBD;
  9715. end
  9716. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9717. begin
  9718. TargetSize := S_W;
  9719. TargetSubReg := R_SUBW;
  9720. end;
  9721. ThisReg := taicpu(hp1).oper[1]^.reg;
  9722. setsubreg(ThisReg, TargetSubReg);
  9723. RegChanged := True;
  9724. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9725. TransferUsedRegs(TmpUsedRegs);
  9726. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9727. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9728. if p = hp1 then
  9729. begin
  9730. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9731. p_removed := True;
  9732. end
  9733. else
  9734. RemoveInstruction(hp1);
  9735. hp1_removed := True;
  9736. { Instruction will become "mov %reg,%reg" }
  9737. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9738. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9739. begin
  9740. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9741. RemoveCurrentP(p);
  9742. p_removed := True;
  9743. end
  9744. else
  9745. taicpu(p).oper[1]^.reg := ThisReg;
  9746. Result := True;
  9747. end
  9748. else
  9749. begin
  9750. if TargetSize <> MaxSize then
  9751. begin
  9752. { Since the register is in use, we have to force it to
  9753. MaxSize otherwise part of it may become undefined later on }
  9754. TargetSize := MaxSize;
  9755. case TargetSize of
  9756. S_B:
  9757. TargetSubReg := R_SUBL;
  9758. S_W:
  9759. TargetSubReg := R_SUBW;
  9760. S_L:
  9761. TargetSubReg := R_SUBD;
  9762. else
  9763. InternalError(2020112351);
  9764. end;
  9765. setsubreg(ThisReg, TargetSubReg);
  9766. end;
  9767. AdjustFinalLoad;
  9768. end;
  9769. end
  9770. else
  9771. AdjustFinalLoad;
  9772. Result := AdjustInitialLoadAndSize or Result;
  9773. { Now go through every instruction we found and change the
  9774. size. If TargetSize = MaxSize, then almost no changes are
  9775. needed and Result can remain False if it hasn't been set
  9776. yet.
  9777. If RegChanged is True, then the register requires changing
  9778. and so the point about TargetSize = MaxSize doesn't apply. }
  9779. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9780. begin
  9781. for LocalIndex := 0 to InstrMax do
  9782. begin
  9783. { If p_removed is true, then the original MOV/Z was removed
  9784. and removing the AND instruction may not be safe if it
  9785. appears first }
  9786. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9787. InternalError(2020112310);
  9788. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9789. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9790. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9791. InstrList[LocalIndex].opsize := TargetSize;
  9792. end;
  9793. Result := True;
  9794. end;
  9795. end;
  9796. begin
  9797. Result := False;
  9798. p_removed := False;
  9799. hp1_removed := False;
  9800. ThisReg := taicpu(p).oper[1]^.reg;
  9801. { Check for:
  9802. movs/z ###,%ecx (or %cx or %rcx)
  9803. ...
  9804. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9805. (dealloc %ecx)
  9806. Change to:
  9807. mov ###,%cl (if ### = %cl, then remove completely)
  9808. ...
  9809. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9810. }
  9811. if (getsupreg(ThisReg) = RS_ECX) and
  9812. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9813. (hp1.typ = ait_instruction) and
  9814. (
  9815. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9816. instruction that doesn't actually contain ECX }
  9817. (cs_opt_level3 in current_settings.optimizerswitches) or
  9818. RegInInstruction(NR_ECX, hp1) or
  9819. (
  9820. { It's common for the shift/rotate's read/write register to be
  9821. initialised in between, so under -O2 and under, search ahead
  9822. one more instruction
  9823. }
  9824. GetNextInstruction(hp1, hp1) and
  9825. (hp1.typ = ait_instruction) and
  9826. RegInInstruction(NR_ECX, hp1)
  9827. )
  9828. ) and
  9829. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9830. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9831. begin
  9832. TransferUsedRegs(TmpUsedRegs);
  9833. hp2 := p;
  9834. repeat
  9835. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9836. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9837. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9838. begin
  9839. case taicpu(p).opsize of
  9840. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9841. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9842. begin
  9843. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9844. RemoveCurrentP(p);
  9845. end
  9846. else
  9847. begin
  9848. taicpu(p).opcode := A_MOV;
  9849. taicpu(p).opsize := S_B;
  9850. taicpu(p).oper[1]^.reg := NR_CL;
  9851. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9852. end;
  9853. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9854. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9855. begin
  9856. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9857. RemoveCurrentP(p);
  9858. end
  9859. else
  9860. begin
  9861. taicpu(p).opcode := A_MOV;
  9862. taicpu(p).opsize := S_W;
  9863. taicpu(p).oper[1]^.reg := NR_CX;
  9864. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9865. end;
  9866. {$ifdef x86_64}
  9867. S_LQ:
  9868. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9869. begin
  9870. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9871. RemoveCurrentP(p);
  9872. end
  9873. else
  9874. begin
  9875. taicpu(p).opcode := A_MOV;
  9876. taicpu(p).opsize := S_L;
  9877. taicpu(p).oper[1]^.reg := NR_ECX;
  9878. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9879. end;
  9880. {$endif x86_64}
  9881. else
  9882. InternalError(2021120401);
  9883. end;
  9884. Result := True;
  9885. Exit;
  9886. end;
  9887. end;
  9888. { This is anything but quick! }
  9889. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9890. Exit;
  9891. SetLength(InstrList, 0);
  9892. InstrMax := -1;
  9893. case taicpu(p).opsize of
  9894. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9895. begin
  9896. {$if defined(i386) or defined(i8086)}
  9897. { If the target size is 8-bit, make sure we can actually encode it }
  9898. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9899. Exit;
  9900. {$endif i386 or i8086}
  9901. LowerLimit := $FF;
  9902. SignedLowerLimit := $7F;
  9903. SignedLowerLimitBottom := -128;
  9904. MinSize := S_B;
  9905. if taicpu(p).opsize = S_BW then
  9906. begin
  9907. MaxSize := S_W;
  9908. UpperLimit := $FFFF;
  9909. SignedUpperLimit := $7FFF;
  9910. SignedUpperLimitBottom := -32768;
  9911. end
  9912. else
  9913. begin
  9914. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9915. MaxSize := S_L;
  9916. UpperLimit := $FFFFFFFF;
  9917. SignedUpperLimit := $7FFFFFFF;
  9918. SignedUpperLimitBottom := -2147483648;
  9919. end;
  9920. end;
  9921. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9922. begin
  9923. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9924. LowerLimit := $FFFF;
  9925. SignedLowerLimit := $7FFF;
  9926. SignedLowerLimitBottom := -32768;
  9927. UpperLimit := $FFFFFFFF;
  9928. SignedUpperLimit := $7FFFFFFF;
  9929. SignedUpperLimitBottom := -2147483648;
  9930. MinSize := S_W;
  9931. MaxSize := S_L;
  9932. end;
  9933. {$ifdef x86_64}
  9934. S_LQ:
  9935. begin
  9936. { Both the lower and upper limits are set to 32-bit. If a limit
  9937. is breached, then optimisation is impossible }
  9938. LowerLimit := $FFFFFFFF;
  9939. SignedLowerLimit := $7FFFFFFF;
  9940. SignedLowerLimitBottom := -2147483648;
  9941. UpperLimit := $FFFFFFFF;
  9942. SignedUpperLimit := $7FFFFFFF;
  9943. SignedUpperLimitBottom := -2147483648;
  9944. MinSize := S_L;
  9945. MaxSize := S_L;
  9946. end;
  9947. {$endif x86_64}
  9948. else
  9949. InternalError(2020112301);
  9950. end;
  9951. TestValMin := 0;
  9952. TestValMax := LowerLimit;
  9953. TestValSignedMax := SignedLowerLimit;
  9954. TryShiftDownLimit := LowerLimit;
  9955. TryShiftDown := S_NO;
  9956. ShiftDownOverflow := False;
  9957. RegChanged := False;
  9958. BitwiseOnly := True;
  9959. OrXorUsed := False;
  9960. UpperSignedOverflow := False;
  9961. LowerSignedOverflow := False;
  9962. UpperUnsignedOverflow := False;
  9963. LowerUnsignedOverflow := False;
  9964. hp1 := p;
  9965. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9966. (hp1.typ = ait_instruction) and
  9967. (
  9968. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9969. instruction that doesn't actually contain ThisReg }
  9970. (cs_opt_level3 in current_settings.optimizerswitches) or
  9971. { This allows this Movx optimisation to work through the SETcc instructions
  9972. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9973. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9974. skip over these SETcc instructions). }
  9975. (taicpu(hp1).opcode = A_SETcc) or
  9976. RegInInstruction(ThisReg, hp1)
  9977. ) do
  9978. begin
  9979. case taicpu(hp1).opcode of
  9980. A_INC,A_DEC:
  9981. begin
  9982. { Has to be an exact match on the register }
  9983. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9984. Break;
  9985. if taicpu(hp1).opcode = A_INC then
  9986. begin
  9987. Inc(TestValMin);
  9988. Inc(TestValMax);
  9989. Inc(TestValSignedMax);
  9990. end
  9991. else
  9992. begin
  9993. Dec(TestValMin);
  9994. Dec(TestValMax);
  9995. Dec(TestValSignedMax);
  9996. end;
  9997. end;
  9998. A_TEST, A_CMP:
  9999. begin
  10000. if (
  10001. { Too high a risk of non-linear behaviour that breaks DFA
  10002. here, unless it's cmp $0,%reg, which is equivalent to
  10003. test %reg,%reg }
  10004. OrXorUsed and
  10005. (taicpu(hp1).opcode = A_CMP) and
  10006. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10007. ) or
  10008. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10009. { Has to be an exact match on the register }
  10010. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10011. (
  10012. { Permit "test %reg,%reg" }
  10013. (taicpu(hp1).opcode = A_TEST) and
  10014. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10015. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10016. ) or
  10017. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10018. { Make sure the comparison value is not smaller than the
  10019. smallest allowed signed value for the minimum size (e.g.
  10020. -128 for 8-bit) }
  10021. not (
  10022. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10023. { Is it in the negative range? }
  10024. (
  10025. (taicpu(hp1).oper[0]^.val < 0) and
  10026. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10027. )
  10028. ) then
  10029. Break;
  10030. { Check to see if the active register is used afterwards }
  10031. TransferUsedRegs(TmpUsedRegs);
  10032. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10033. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10034. begin
  10035. { Make sure the comparison or any previous instructions
  10036. hasn't pushed the test values outside of the range of
  10037. MinSize }
  10038. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10039. begin
  10040. { Exceeded lower bound but not upper bound }
  10041. Exit;
  10042. end
  10043. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10044. begin
  10045. { Size didn't exceed lower bound }
  10046. TargetSize := MinSize;
  10047. end
  10048. else
  10049. Break;
  10050. case TargetSize of
  10051. S_B:
  10052. TargetSubReg := R_SUBL;
  10053. S_W:
  10054. TargetSubReg := R_SUBW;
  10055. S_L:
  10056. TargetSubReg := R_SUBD;
  10057. else
  10058. InternalError(2021051002);
  10059. end;
  10060. if TargetSize <> MaxSize then
  10061. begin
  10062. { Update the register to its new size }
  10063. setsubreg(ThisReg, TargetSubReg);
  10064. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10065. taicpu(hp1).oper[1]^.reg := ThisReg;
  10066. taicpu(hp1).opsize := TargetSize;
  10067. { Convert the input MOVZX to a MOV if necessary }
  10068. AdjustInitialLoadAndSize;
  10069. if (InstrMax >= 0) then
  10070. begin
  10071. for Index := 0 to InstrMax do
  10072. begin
  10073. { If p_removed is true, then the original MOV/Z was removed
  10074. and removing the AND instruction may not be safe if it
  10075. appears first }
  10076. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10077. InternalError(2020112311);
  10078. if InstrList[Index].oper[0]^.typ = top_reg then
  10079. InstrList[Index].oper[0]^.reg := ThisReg;
  10080. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10081. InstrList[Index].opsize := MinSize;
  10082. end;
  10083. end;
  10084. Result := True;
  10085. end;
  10086. Exit;
  10087. end;
  10088. end;
  10089. A_SETcc:
  10090. begin
  10091. { This allows this Movx optimisation to work through the SETcc instructions
  10092. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10093. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10094. skip over these SETcc instructions). }
  10095. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10096. { Of course, break out if the current register is used }
  10097. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10098. Break
  10099. else
  10100. { We must use Continue so the instruction doesn't get added
  10101. to InstrList }
  10102. Continue;
  10103. end;
  10104. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10105. begin
  10106. if
  10107. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10108. { Has to be an exact match on the register }
  10109. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10110. (
  10111. (
  10112. (taicpu(hp1).oper[0]^.typ = top_const) and
  10113. (
  10114. (
  10115. (taicpu(hp1).opcode = A_SHL) and
  10116. (
  10117. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10118. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10119. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10120. )
  10121. ) or (
  10122. (taicpu(hp1).opcode <> A_SHL) and
  10123. (
  10124. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10125. { Is it in the negative range? }
  10126. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10127. )
  10128. )
  10129. )
  10130. ) or (
  10131. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10132. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10133. )
  10134. ) then
  10135. Break;
  10136. { Only process OR and XOR if there are only bitwise operations,
  10137. since otherwise they can too easily fool the data flow
  10138. analysis (they can cause non-linear behaviour) }
  10139. case taicpu(hp1).opcode of
  10140. A_ADD:
  10141. begin
  10142. if OrXorUsed then
  10143. { Too high a risk of non-linear behaviour that breaks DFA here }
  10144. Break
  10145. else
  10146. BitwiseOnly := False;
  10147. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10148. begin
  10149. TestValMin := TestValMin * 2;
  10150. TestValMax := TestValMax * 2;
  10151. TestValSignedMax := TestValSignedMax * 2;
  10152. end
  10153. else
  10154. begin
  10155. WorkingValue := taicpu(hp1).oper[0]^.val;
  10156. TestValMin := TestValMin + WorkingValue;
  10157. TestValMax := TestValMax + WorkingValue;
  10158. TestValSignedMax := TestValSignedMax + WorkingValue;
  10159. end;
  10160. end;
  10161. A_SUB:
  10162. begin
  10163. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10164. begin
  10165. TestValMin := 0;
  10166. TestValMax := 0;
  10167. TestValSignedMax := 0;
  10168. end
  10169. else
  10170. begin
  10171. if OrXorUsed then
  10172. { Too high a risk of non-linear behaviour that breaks DFA here }
  10173. Break
  10174. else
  10175. BitwiseOnly := False;
  10176. WorkingValue := taicpu(hp1).oper[0]^.val;
  10177. TestValMin := TestValMin - WorkingValue;
  10178. TestValMax := TestValMax - WorkingValue;
  10179. TestValSignedMax := TestValSignedMax - WorkingValue;
  10180. end;
  10181. end;
  10182. A_AND:
  10183. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10184. begin
  10185. { we might be able to go smaller if AND appears first }
  10186. if InstrMax = -1 then
  10187. case MinSize of
  10188. S_B:
  10189. ;
  10190. S_W:
  10191. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10192. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10193. begin
  10194. TryShiftDown := S_B;
  10195. TryShiftDownLimit := $FF;
  10196. end;
  10197. S_L:
  10198. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10199. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10200. begin
  10201. TryShiftDown := S_B;
  10202. TryShiftDownLimit := $FF;
  10203. end
  10204. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10205. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10206. begin
  10207. TryShiftDown := S_W;
  10208. TryShiftDownLimit := $FFFF;
  10209. end;
  10210. else
  10211. InternalError(2020112320);
  10212. end;
  10213. WorkingValue := taicpu(hp1).oper[0]^.val;
  10214. TestValMin := TestValMin and WorkingValue;
  10215. TestValMax := TestValMax and WorkingValue;
  10216. TestValSignedMax := TestValSignedMax and WorkingValue;
  10217. end;
  10218. A_OR:
  10219. begin
  10220. if not BitwiseOnly then
  10221. Break;
  10222. OrXorUsed := True;
  10223. WorkingValue := taicpu(hp1).oper[0]^.val;
  10224. TestValMin := TestValMin or WorkingValue;
  10225. TestValMax := TestValMax or WorkingValue;
  10226. TestValSignedMax := TestValSignedMax or WorkingValue;
  10227. end;
  10228. A_XOR:
  10229. begin
  10230. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10231. begin
  10232. TestValMin := 0;
  10233. TestValMax := 0;
  10234. TestValSignedMax := 0;
  10235. end
  10236. else
  10237. begin
  10238. if not BitwiseOnly then
  10239. Break;
  10240. OrXorUsed := True;
  10241. WorkingValue := taicpu(hp1).oper[0]^.val;
  10242. TestValMin := TestValMin xor WorkingValue;
  10243. TestValMax := TestValMax xor WorkingValue;
  10244. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10245. end;
  10246. end;
  10247. A_SHL:
  10248. begin
  10249. BitwiseOnly := False;
  10250. WorkingValue := taicpu(hp1).oper[0]^.val;
  10251. TestValMin := TestValMin shl WorkingValue;
  10252. TestValMax := TestValMax shl WorkingValue;
  10253. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10254. end;
  10255. A_SHR,
  10256. { The first instruction was MOVZX, so the value won't be negative }
  10257. A_SAR:
  10258. begin
  10259. if InstrMax <> -1 then
  10260. BitwiseOnly := False
  10261. else
  10262. { we might be able to go smaller if SHR appears first }
  10263. case MinSize of
  10264. S_B:
  10265. ;
  10266. S_W:
  10267. if (taicpu(hp1).oper[0]^.val >= 8) then
  10268. begin
  10269. TryShiftDown := S_B;
  10270. TryShiftDownLimit := $FF;
  10271. TryShiftDownSignedLimit := $7F;
  10272. TryShiftDownSignedLimitLower := -128;
  10273. end;
  10274. S_L:
  10275. if (taicpu(hp1).oper[0]^.val >= 24) then
  10276. begin
  10277. TryShiftDown := S_B;
  10278. TryShiftDownLimit := $FF;
  10279. TryShiftDownSignedLimit := $7F;
  10280. TryShiftDownSignedLimitLower := -128;
  10281. end
  10282. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10283. begin
  10284. TryShiftDown := S_W;
  10285. TryShiftDownLimit := $FFFF;
  10286. TryShiftDownSignedLimit := $7FFF;
  10287. TryShiftDownSignedLimitLower := -32768;
  10288. end;
  10289. else
  10290. InternalError(2020112321);
  10291. end;
  10292. WorkingValue := taicpu(hp1).oper[0]^.val;
  10293. if taicpu(hp1).opcode = A_SAR then
  10294. begin
  10295. TestValMin := SarInt64(TestValMin, WorkingValue);
  10296. TestValMax := SarInt64(TestValMax, WorkingValue);
  10297. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10298. end
  10299. else
  10300. begin
  10301. TestValMin := TestValMin shr WorkingValue;
  10302. TestValMax := TestValMax shr WorkingValue;
  10303. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10304. end;
  10305. end;
  10306. else
  10307. InternalError(2020112303);
  10308. end;
  10309. end;
  10310. (*
  10311. A_IMUL:
  10312. case taicpu(hp1).ops of
  10313. 2:
  10314. begin
  10315. if not MatchOpType(hp1, top_reg, top_reg) or
  10316. { Has to be an exact match on the register }
  10317. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10318. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10319. Break;
  10320. TestValMin := TestValMin * TestValMin;
  10321. TestValMax := TestValMax * TestValMax;
  10322. TestValSignedMax := TestValSignedMax * TestValMax;
  10323. end;
  10324. 3:
  10325. begin
  10326. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10327. { Has to be an exact match on the register }
  10328. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10329. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10330. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10331. { Is it in the negative range? }
  10332. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10333. Break;
  10334. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10335. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10336. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10337. end;
  10338. else
  10339. Break;
  10340. end;
  10341. A_IDIV:
  10342. case taicpu(hp1).ops of
  10343. 3:
  10344. begin
  10345. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10346. { Has to be an exact match on the register }
  10347. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10348. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10349. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10350. { Is it in the negative range? }
  10351. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10352. Break;
  10353. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10354. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10355. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10356. end;
  10357. else
  10358. Break;
  10359. end;
  10360. *)
  10361. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10362. begin
  10363. { If there are no instructions in between, then we might be able to make a saving }
  10364. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10365. Break;
  10366. { We have something like:
  10367. movzbw %dl,%dx
  10368. ...
  10369. movswl %dx,%edx
  10370. Change the latter to a zero-extension then enter the
  10371. A_MOVZX case branch.
  10372. }
  10373. {$ifdef x86_64}
  10374. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10375. begin
  10376. { this becomes a zero extension from 32-bit to 64-bit, but
  10377. the upper 32 bits are already zero, so just delete the
  10378. instruction }
  10379. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10380. RemoveInstruction(hp1);
  10381. Result := True;
  10382. Exit;
  10383. end
  10384. else
  10385. {$endif x86_64}
  10386. begin
  10387. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10388. taicpu(hp1).opcode := A_MOVZX;
  10389. {$ifdef x86_64}
  10390. case taicpu(hp1).opsize of
  10391. S_BQ:
  10392. begin
  10393. taicpu(hp1).opsize := S_BL;
  10394. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10395. end;
  10396. S_WQ:
  10397. begin
  10398. taicpu(hp1).opsize := S_WL;
  10399. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10400. end;
  10401. S_LQ:
  10402. begin
  10403. taicpu(hp1).opcode := A_MOV;
  10404. taicpu(hp1).opsize := S_L;
  10405. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10406. { In this instance, we need to break out because the
  10407. instruction is no longer MOVZX or MOVSXD }
  10408. Result := True;
  10409. Exit;
  10410. end;
  10411. else
  10412. ;
  10413. end;
  10414. {$endif x86_64}
  10415. Result := CompressInstructions;
  10416. Exit;
  10417. end;
  10418. end;
  10419. A_MOVZX:
  10420. begin
  10421. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10422. Break;
  10423. if (InstrMax = -1) then
  10424. begin
  10425. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10426. begin
  10427. { Optimise around i40003 }
  10428. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10429. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10430. {$ifndef x86_64}
  10431. and (
  10432. (taicpu(p).oper[0]^.typ <> top_reg) or
  10433. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10434. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10435. )
  10436. {$endif not x86_64}
  10437. then
  10438. begin
  10439. if (taicpu(p).oper[0]^.typ = top_reg) then
  10440. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10441. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10442. taicpu(p).opsize := S_BL;
  10443. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10444. RemoveInstruction(hp1);
  10445. Result := True;
  10446. Exit;
  10447. end;
  10448. end
  10449. else
  10450. begin
  10451. { Will return false if the second parameter isn't ThisReg
  10452. (can happen on -O2 and under) }
  10453. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10454. begin
  10455. { The two MOVZX instructions are adjacent, so remove the first one }
  10456. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10457. RemoveCurrentP(p);
  10458. Result := True;
  10459. Exit;
  10460. end;
  10461. Break;
  10462. end;
  10463. end;
  10464. Result := CompressInstructions;
  10465. Exit;
  10466. end;
  10467. else
  10468. { This includes ADC, SBB and IDIV }
  10469. Break;
  10470. end;
  10471. if not CheckOverflowConditions then
  10472. Break;
  10473. { Contains highest index (so instruction count - 1) }
  10474. Inc(InstrMax);
  10475. if InstrMax > High(InstrList) then
  10476. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10477. InstrList[InstrMax] := taicpu(hp1);
  10478. end;
  10479. end;
  10480. {$pop}
  10481. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10482. var
  10483. hp1 : tai;
  10484. begin
  10485. Result:=false;
  10486. if (taicpu(p).ops >= 2) and
  10487. ((taicpu(p).oper[0]^.typ = top_const) or
  10488. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10489. (taicpu(p).oper[1]^.typ = top_reg) and
  10490. ((taicpu(p).ops = 2) or
  10491. ((taicpu(p).oper[2]^.typ = top_reg) and
  10492. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10493. GetLastInstruction(p,hp1) and
  10494. MatchInstruction(hp1,A_MOV,[]) and
  10495. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10496. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10497. begin
  10498. TransferUsedRegs(TmpUsedRegs);
  10499. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10500. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10501. { change
  10502. mov reg1,reg2
  10503. imul y,reg2 to imul y,reg1,reg2 }
  10504. begin
  10505. taicpu(p).ops := 3;
  10506. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10507. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10508. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10509. RemoveInstruction(hp1);
  10510. result:=true;
  10511. end;
  10512. end;
  10513. end;
  10514. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10515. var
  10516. ThisLabel: TAsmLabel;
  10517. begin
  10518. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10519. ThisLabel.decrefs;
  10520. taicpu(p).condition := C_None;
  10521. taicpu(p).opcode := A_RET;
  10522. taicpu(p).is_jmp := false;
  10523. taicpu(p).ops := taicpu(ret_p).ops;
  10524. case taicpu(ret_p).ops of
  10525. 0:
  10526. taicpu(p).clearop(0);
  10527. 1:
  10528. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10529. else
  10530. internalerror(2016041301);
  10531. end;
  10532. { If the original label is now dead, it might turn out that the label
  10533. immediately follows p. As a result, everything beyond it, which will
  10534. be just some final register configuration and a RET instruction, is
  10535. now dead code. [Kit] }
  10536. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10537. running RemoveDeadCodeAfterJump for each RET instruction, because
  10538. this optimisation rarely happens and most RETs appear at the end of
  10539. routines where there is nothing that can be stripped. [Kit] }
  10540. if not ThisLabel.is_used then
  10541. RemoveDeadCodeAfterJump(p);
  10542. end;
  10543. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10544. var
  10545. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10546. Unconditional, PotentialModified: Boolean;
  10547. OperPtr: POper;
  10548. NewRef: TReference;
  10549. InstrList: array of taicpu;
  10550. InstrMax, Index: Integer;
  10551. const
  10552. {$ifdef DEBUG_AOPTCPU}
  10553. SNoFlags: shortstring = ' so the flags aren''t modified';
  10554. {$else DEBUG_AOPTCPU}
  10555. SNoFlags = '';
  10556. {$endif DEBUG_AOPTCPU}
  10557. begin
  10558. Result:=false;
  10559. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10560. begin
  10561. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10562. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10563. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10564. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10565. GetNextInstruction(hp1, hp2) and
  10566. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10567. { Change from: To:
  10568. set(C) %reg j(~C) label
  10569. test %reg,%reg/cmp $0,%reg
  10570. je label
  10571. set(C) %reg j(C) label
  10572. test %reg,%reg/cmp $0,%reg
  10573. jne label
  10574. (Also do something similar with sete/setne instead of je/jne)
  10575. }
  10576. begin
  10577. { Before we do anything else, we need to check the instructions
  10578. in between SETcc and TEST to make sure they don't modify the
  10579. FLAGS register - if -O2 or under, there won't be any
  10580. instructions between SET and TEST }
  10581. TransferUsedRegs(TmpUsedRegs);
  10582. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10583. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10584. begin
  10585. next := p;
  10586. SetLength(InstrList, 0);
  10587. InstrMax := -1;
  10588. PotentialModified := False;
  10589. { Make a note of every instruction that modifies the FLAGS
  10590. register }
  10591. while GetNextInstruction(next, next) and (next <> hp1) do
  10592. begin
  10593. if next.typ <> ait_instruction then
  10594. { GetNextInstructionUsingReg should have returned False }
  10595. InternalError(2021051701);
  10596. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10597. begin
  10598. case taicpu(next).opcode of
  10599. A_SETcc,
  10600. A_CMOVcc,
  10601. A_Jcc:
  10602. begin
  10603. if PotentialModified then
  10604. { Not safe because the flags were modified earlier }
  10605. Exit
  10606. else
  10607. { Condition is the same as the initial SETcc, so this is safe
  10608. (don't add to instruction list though) }
  10609. Continue;
  10610. end;
  10611. A_ADD:
  10612. begin
  10613. if (taicpu(next).opsize = S_B) or
  10614. { LEA doesn't support 8-bit operands }
  10615. (taicpu(next).oper[1]^.typ <> top_reg) or
  10616. { Must write to a register }
  10617. (taicpu(next).oper[0]^.typ = top_ref) then
  10618. { Require a constant or a register }
  10619. Exit;
  10620. PotentialModified := True;
  10621. end;
  10622. A_SUB:
  10623. begin
  10624. if (taicpu(next).opsize = S_B) or
  10625. { LEA doesn't support 8-bit operands }
  10626. (taicpu(next).oper[1]^.typ <> top_reg) or
  10627. { Must write to a register }
  10628. (taicpu(next).oper[0]^.typ <> top_const) or
  10629. (taicpu(next).oper[0]^.val = $80000000) then
  10630. { Can't subtract a register with LEA - also
  10631. check that the value isn't -2^31, as this
  10632. can't be negated }
  10633. Exit;
  10634. PotentialModified := True;
  10635. end;
  10636. A_SAL,
  10637. A_SHL:
  10638. begin
  10639. if (taicpu(next).opsize = S_B) or
  10640. { LEA doesn't support 8-bit operands }
  10641. (taicpu(next).oper[1]^.typ <> top_reg) or
  10642. { Must write to a register }
  10643. (taicpu(next).oper[0]^.typ <> top_const) or
  10644. (taicpu(next).oper[0]^.val < 0) or
  10645. (taicpu(next).oper[0]^.val > 3) then
  10646. Exit;
  10647. PotentialModified := True;
  10648. end;
  10649. A_IMUL:
  10650. begin
  10651. if (taicpu(next).ops <> 3) or
  10652. (taicpu(next).oper[1]^.typ <> top_reg) or
  10653. { Must write to a register }
  10654. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10655. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10656. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10657. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10658. Exit
  10659. else
  10660. PotentialModified := True;
  10661. end;
  10662. else
  10663. { Don't know how to change this, so abort }
  10664. Exit;
  10665. end;
  10666. { Contains highest index (so instruction count - 1) }
  10667. Inc(InstrMax);
  10668. if InstrMax > High(InstrList) then
  10669. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10670. InstrList[InstrMax] := taicpu(next);
  10671. end;
  10672. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10673. end;
  10674. if not Assigned(next) or (next <> hp1) then
  10675. { It should be equal to hp1 }
  10676. InternalError(2021051702);
  10677. { Cycle through each instruction and check to see if we can
  10678. change them to versions that don't modify the flags }
  10679. if (InstrMax >= 0) then
  10680. begin
  10681. for Index := 0 to InstrMax do
  10682. case InstrList[Index].opcode of
  10683. A_ADD:
  10684. begin
  10685. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10686. InstrList[Index].opcode := A_LEA;
  10687. reference_reset(NewRef, 1, []);
  10688. NewRef.base := InstrList[Index].oper[1]^.reg;
  10689. if InstrList[Index].oper[0]^.typ = top_reg then
  10690. begin
  10691. NewRef.index := InstrList[Index].oper[0]^.reg;
  10692. NewRef.scalefactor := 1;
  10693. end
  10694. else
  10695. NewRef.offset := InstrList[Index].oper[0]^.val;
  10696. InstrList[Index].loadref(0, NewRef);
  10697. end;
  10698. A_SUB:
  10699. begin
  10700. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10701. InstrList[Index].opcode := A_LEA;
  10702. reference_reset(NewRef, 1, []);
  10703. NewRef.base := InstrList[Index].oper[1]^.reg;
  10704. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10705. InstrList[Index].loadref(0, NewRef);
  10706. end;
  10707. A_SHL,
  10708. A_SAL:
  10709. begin
  10710. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10711. InstrList[Index].opcode := A_LEA;
  10712. reference_reset(NewRef, 1, []);
  10713. NewRef.index := InstrList[Index].oper[1]^.reg;
  10714. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10715. InstrList[Index].loadref(0, NewRef);
  10716. end;
  10717. A_IMUL:
  10718. begin
  10719. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10720. InstrList[Index].opcode := A_LEA;
  10721. reference_reset(NewRef, 1, []);
  10722. NewRef.index := InstrList[Index].oper[1]^.reg;
  10723. case InstrList[Index].oper[0]^.val of
  10724. 2, 4, 8:
  10725. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10726. else {3, 5 and 9}
  10727. begin
  10728. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10729. NewRef.base := InstrList[Index].oper[1]^.reg;
  10730. end;
  10731. end;
  10732. InstrList[Index].loadref(0, NewRef);
  10733. end;
  10734. else
  10735. InternalError(2021051710);
  10736. end;
  10737. end;
  10738. { Mark the FLAGS register as used across this whole block }
  10739. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10740. end;
  10741. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10742. JumpC := taicpu(hp2).condition;
  10743. Unconditional := False;
  10744. if conditions_equal(JumpC, C_E) then
  10745. SetC := inverse_cond(taicpu(p).condition)
  10746. else if conditions_equal(JumpC, C_NE) then
  10747. SetC := taicpu(p).condition
  10748. else
  10749. { We've got something weird here (and inefficent) }
  10750. begin
  10751. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10752. SetC := C_NONE;
  10753. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10754. if condition_in(C_AE, JumpC) then
  10755. Unconditional := True
  10756. else
  10757. { Not sure what to do with this jump - drop out }
  10758. Exit;
  10759. end;
  10760. RemoveInstruction(hp1);
  10761. if Unconditional then
  10762. MakeUnconditional(taicpu(hp2))
  10763. else
  10764. begin
  10765. if SetC = C_NONE then
  10766. InternalError(2018061402);
  10767. taicpu(hp2).SetCondition(SetC);
  10768. end;
  10769. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10770. TmpUsedRegs }
  10771. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10772. begin
  10773. RemoveCurrentp(p, hp2);
  10774. if taicpu(hp2).opcode = A_SETcc then
  10775. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10776. else
  10777. begin
  10778. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10779. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10780. Include(OptsToCheck, aoc_DoPass2JccOpts);
  10781. end;
  10782. end
  10783. else
  10784. if taicpu(hp2).opcode = A_SETcc then
  10785. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10786. else
  10787. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10788. Result := True;
  10789. end
  10790. else if
  10791. { Make sure the instructions are adjacent }
  10792. (
  10793. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10794. GetNextInstruction(p, hp1)
  10795. ) and
  10796. MatchInstruction(hp1, A_MOV, [S_B]) and
  10797. { Writing to memory is allowed }
  10798. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10799. begin
  10800. {
  10801. Watch out for sequences such as:
  10802. set(c)b %regb
  10803. movb %regb,(ref)
  10804. movb $0,1(ref)
  10805. movb $0,2(ref)
  10806. movb $0,3(ref)
  10807. Much more efficient to turn it into:
  10808. movl $0,%regl
  10809. set(c)b %regb
  10810. movl %regl,(ref)
  10811. Or:
  10812. set(c)b %regb
  10813. movzbl %regb,%regl
  10814. movl %regl,(ref)
  10815. }
  10816. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10817. GetNextInstruction(hp1, hp2) and
  10818. MatchInstruction(hp2, A_MOV, [S_B]) and
  10819. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10820. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10821. begin
  10822. { Don't do anything else except set Result to True }
  10823. end
  10824. else
  10825. begin
  10826. if taicpu(p).oper[0]^.typ = top_reg then
  10827. begin
  10828. TransferUsedRegs(TmpUsedRegs);
  10829. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10830. end;
  10831. { If it's not a register, it's a memory address }
  10832. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10833. begin
  10834. { Even if the register is still in use, we can minimise the
  10835. pipeline stall by changing the MOV into another SETcc. }
  10836. taicpu(hp1).opcode := A_SETcc;
  10837. taicpu(hp1).condition := taicpu(p).condition;
  10838. if taicpu(hp1).oper[1]^.typ = top_ref then
  10839. begin
  10840. { Swapping the operand pointers like this is probably a
  10841. bit naughty, but it is far faster than using loadoper
  10842. to transfer the reference from oper[1] to oper[0] if
  10843. you take into account the extra procedure calls and
  10844. the memory allocation and deallocation required }
  10845. OperPtr := taicpu(hp1).oper[1];
  10846. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10847. taicpu(hp1).oper[0] := OperPtr;
  10848. end
  10849. else
  10850. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10851. taicpu(hp1).clearop(1);
  10852. taicpu(hp1).ops := 1;
  10853. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10854. end
  10855. else
  10856. begin
  10857. if taicpu(hp1).oper[1]^.typ = top_reg then
  10858. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10859. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10860. RemoveInstruction(hp1);
  10861. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10862. end
  10863. end;
  10864. Result := True;
  10865. end;
  10866. end;
  10867. end;
  10868. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  10869. var
  10870. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  10871. TargetReg: TRegister;
  10872. condition, inverted_condition: TAsmCond;
  10873. FoundMOV: Boolean;
  10874. begin
  10875. Result := False;
  10876. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  10877. create the most optimial instructions possible due to limited
  10878. register availability, and there are situations where two
  10879. complementary "simple" CMOV blocks are created which, after the fact
  10880. can be merged into a "double" block. For example:
  10881. movw $257,%ax
  10882. movw $2,%r8w
  10883. xorl r9d,%r9d
  10884. testw $16,18(%rcx)
  10885. cmovew %ax,%dx
  10886. cmovew %r8w,%bx
  10887. cmovel %r9d,%r14d
  10888. movw $1283,%ax
  10889. movw $4,%r8w
  10890. movl $9,%r9d
  10891. cmovnew %ax,%dx
  10892. cmovnew %r8w,%bx
  10893. cmovnel %r9d,%r14d
  10894. The CMOVNE instructions at the end can be removed, and the
  10895. destination registers copied into the MOV instructions directly
  10896. above them, before finally being moved to before the first CMOVE
  10897. instructions, to produce:
  10898. movw $257,%ax
  10899. movw $2,%r8w
  10900. xorl r9d,%r9d
  10901. testw $16,18(%rcx)
  10902. movw $1283,%dx
  10903. movw $4,%bx
  10904. movl $9,%r14d
  10905. cmovew %ax,%dx
  10906. cmovew %r8w,%bx
  10907. cmovel %r9d,%r14d
  10908. Which can then be later optimised to:
  10909. movw $257,%ax
  10910. movw $2,%r8w
  10911. xorl r9d,%r9d
  10912. movw $1283,%dx
  10913. movw $4,%bx
  10914. movl $9,%r14d
  10915. testw $16,18(%rcx)
  10916. cmovew %ax,%dx
  10917. cmovew %r8w,%bx
  10918. cmovel %r9d,%r14d
  10919. }
  10920. TargetReg := taicpu(hp1).oper[1]^.reg;
  10921. condition := taicpu(hp1).condition;
  10922. inverted_condition := inverse_cond(condition);
  10923. pFirstMov := nil;
  10924. pLastMov := nil;
  10925. pCMOV := nil;
  10926. if (p.typ = ait_instruction) then
  10927. pCond := p
  10928. else if not GetNextInstruction(p, pCond) then
  10929. InternalError(2024012501);
  10930. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  10931. { We should get the CMP or TEST instructeion }
  10932. InternalError(2024012502);
  10933. if (
  10934. (taicpu(hp1).oper[0]^.typ = top_reg) or
  10935. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  10936. ) then
  10937. begin
  10938. { We have to tread carefully here, hence why we're not using
  10939. GetNextInstructionUsingReg... we can only accept MOV and other
  10940. CMOV instructions. Anything else and we must drop out}
  10941. hp2 := hp1;
  10942. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  10943. begin
  10944. if (hp2.typ <> ait_instruction) then
  10945. Exit;
  10946. case taicpu(hp2).opcode of
  10947. A_MOV:
  10948. begin
  10949. if not Assigned(pFirstMov) then
  10950. pFirstMov := hp2;
  10951. pLastMOV := hp2;
  10952. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  10953. { Something different - drop out }
  10954. Exit;
  10955. { Otherwise, leave it for now }
  10956. end;
  10957. A_CMOVcc:
  10958. begin
  10959. if taicpu(hp2).condition = inverted_condition then
  10960. begin
  10961. { We found what we're looking for }
  10962. if taicpu(hp2).oper[1]^.reg = TargetReg then
  10963. begin
  10964. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  10965. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  10966. begin
  10967. pCMOV := hp2;
  10968. Break;
  10969. end
  10970. else
  10971. { Unsafe reference - drop out }
  10972. Exit;
  10973. end;
  10974. end
  10975. else if taicpu(hp2).condition <> condition then
  10976. { Something weird - drop out }
  10977. Exit;
  10978. end;
  10979. else
  10980. { Invalid }
  10981. Exit;
  10982. end;
  10983. end;
  10984. if not Assigned(pCMOV) then
  10985. { No complementary CMOV found }
  10986. Exit;
  10987. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  10988. begin
  10989. { Don't need to do anything special or search for a matching MOV }
  10990. Asml.Remove(pCMOV);
  10991. if RegInInstruction(TargetReg, pCond) then
  10992. { Make sure we don't overwrite the register if it's being used in the condition }
  10993. Asml.InsertAfter(pCMOV, pCond)
  10994. else
  10995. Asml.InsertBefore(pCMOV, pCond);
  10996. taicpu(pCMOV).opcode := A_MOV;
  10997. taicpu(pCMOV).condition := C_None;
  10998. { Don't need to worry about allocating new registers in these cases }
  10999. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11000. Result := True;
  11001. Exit;
  11002. end
  11003. else
  11004. begin
  11005. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11006. FoundMOV := False;
  11007. { Search for the MOV that sets the target register }
  11008. hp2 := pFirstMov;
  11009. repeat
  11010. if (taicpu(hp2).opcode = A_MOV) and
  11011. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11012. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11013. begin
  11014. { Change the destination }
  11015. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11016. if not FoundMOV then
  11017. begin
  11018. FoundMOV := True;
  11019. { Make sure the register is allocated }
  11020. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11021. end;
  11022. hp1 := tai(hp2.Previous);
  11023. Asml.Remove(hp2);
  11024. if RegInInstruction(TargetReg, pCond) then
  11025. { Make sure we don't overwrite the register if it's being used in the condition }
  11026. Asml.InsertAfter(hp2, pCond)
  11027. else
  11028. Asml.InsertBefore(hp2, pCond);
  11029. if (hp2 = pLastMov) then
  11030. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11031. Break;
  11032. hp2 := hp1;
  11033. end;
  11034. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11035. if FoundMOV then
  11036. { Delete the CMOV }
  11037. RemoveInstruction(pCMOV)
  11038. else
  11039. begin
  11040. { If no MOV was found, we have to actually move and transmute the CMOV }
  11041. Asml.Remove(pCMOV);
  11042. if RegInInstruction(TargetReg, pCond) then
  11043. { Make sure we don't overwrite the register if it's being used in the condition }
  11044. Asml.InsertAfter(pCMOV, pCond)
  11045. else
  11046. Asml.InsertBefore(pCMOV, pCond);
  11047. taicpu(pCMOV).opcode := A_MOV;
  11048. taicpu(pCMOV).condition := C_None;
  11049. end;
  11050. Result := True;
  11051. Exit;
  11052. end;
  11053. end;
  11054. end;
  11055. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11056. var
  11057. hp1, hp2, pCond: tai;
  11058. begin
  11059. Result := False;
  11060. { Search ahead for CMOV instructions }
  11061. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11062. begin
  11063. hp1 := p;
  11064. hp2 := p;
  11065. pCond := nil; { To prevent compiler warnings }
  11066. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11067. DEFAULTFLAGS }
  11068. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11069. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11070. pCond := p;
  11071. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11072. begin
  11073. if (hp1.typ <> ait_instruction) then
  11074. { Break out on markers and labels etc. }
  11075. Break;
  11076. case taicpu(hp1).opcode of
  11077. A_MOV:
  11078. { Ignore regular MOVs unless they are obviously not related
  11079. to a CMOV block }
  11080. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11081. Break;
  11082. A_CMOVcc:
  11083. if TryCmpCMovOpts(pCond, hp1) then
  11084. begin
  11085. hp1 := hp2;
  11086. { p itself isn't changed, and we're still inside a
  11087. while loop to catch subsequent CMOVs, so just flag
  11088. a new iteration }
  11089. Include(OptsToCheck, aoc_ForceNewIteration);
  11090. Continue;
  11091. end;
  11092. else
  11093. { Drop out if we find anything else }
  11094. Break;
  11095. end;
  11096. hp2 := hp1;
  11097. end;
  11098. end;
  11099. end;
  11100. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11101. var
  11102. hp1, hp2, pCond: tai;
  11103. begin
  11104. Result := False;
  11105. { Search ahead for CMOV instructions }
  11106. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11107. begin
  11108. hp1 := p;
  11109. hp2 := p;
  11110. pCond := nil; { To prevent compiler warnings }
  11111. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11112. DEFAULTFLAGS }
  11113. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11114. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11115. pCond := p;
  11116. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11117. begin
  11118. if (hp1.typ <> ait_instruction) then
  11119. { Break out on markers and labels etc. }
  11120. Break;
  11121. case taicpu(hp1).opcode of
  11122. A_MOV:
  11123. { Ignore regular MOVs unless they are obviously not related
  11124. to a CMOV block }
  11125. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11126. Break;
  11127. A_CMOVcc:
  11128. if TryCmpCMovOpts(pCond, hp1) then
  11129. begin
  11130. hp1 := hp2;
  11131. { p itself isn't changed, and we're still inside a
  11132. while loop to catch subsequent CMOVs, so just flag
  11133. a new iteration }
  11134. Include(OptsToCheck, aoc_ForceNewIteration);
  11135. Continue;
  11136. end;
  11137. else
  11138. { Drop out if we find anything else }
  11139. Break;
  11140. end;
  11141. hp2 := hp1;
  11142. end;
  11143. end;
  11144. end;
  11145. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11146. var
  11147. hp1: tai;
  11148. Count: Integer;
  11149. OrigLabel: TAsmLabel;
  11150. begin
  11151. result := False;
  11152. { Sometimes, the optimisations below can permit this }
  11153. RemoveDeadCodeAfterJump(p);
  11154. 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
  11155. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11156. begin
  11157. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11158. { Also a side-effect of optimisations }
  11159. if CollapseZeroDistJump(p, OrigLabel) then
  11160. begin
  11161. Result := True;
  11162. Exit;
  11163. end;
  11164. hp1 := GetLabelWithSym(OrigLabel);
  11165. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11166. begin
  11167. if taicpu(hp1).opcode = A_RET then
  11168. begin
  11169. {
  11170. change
  11171. jmp .L1
  11172. ...
  11173. .L1:
  11174. ret
  11175. into
  11176. ret
  11177. }
  11178. begin
  11179. ConvertJumpToRET(p, hp1);
  11180. result:=true;
  11181. end;
  11182. end
  11183. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11184. not (cs_opt_size in current_settings.optimizerswitches) and
  11185. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11186. begin
  11187. Result := True;
  11188. Exit;
  11189. end;
  11190. end;
  11191. end;
  11192. end;
  11193. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11194. begin
  11195. Result := assigned(p) and
  11196. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11197. (taicpu(p).oper[1]^.typ = top_reg) and
  11198. (
  11199. (taicpu(p).oper[0]^.typ = top_reg) or
  11200. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11201. it is not expected that this can cause a seg. violation }
  11202. (
  11203. (taicpu(p).oper[0]^.typ = top_ref) and
  11204. { TODO: Can we detect which references become constants at this
  11205. stage so we don't have to do a blanket ban? }
  11206. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11207. (
  11208. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11209. (
  11210. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11211. not RefModified and
  11212. { If the reference also appears in the condition, then we know it's safe, otherwise
  11213. any kind of access violation would have occurred already }
  11214. Assigned(cond_p) and
  11215. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11216. (cond_p.typ = ait_instruction) and
  11217. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11218. { Just consider 2-operand comparison instructions for now to be safe }
  11219. (taicpu(cond_p).ops = 2) and
  11220. (
  11221. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11222. (
  11223. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11224. { Don't risk identical registers but different offsets, as we may have constructs
  11225. such as buffer streams with things like length fields that indicate whether
  11226. any more data follows. And there are probably some contrived examples where
  11227. writing to offsets behind the one being read also lead to access violations }
  11228. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11229. (
  11230. { Check that we're not modifying a register that appears in the reference }
  11231. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11232. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11233. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11234. )
  11235. )
  11236. )
  11237. )
  11238. )
  11239. )
  11240. );
  11241. end;
  11242. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11243. begin
  11244. { Update integer registers, ignoring deallocations }
  11245. repeat
  11246. while assigned(p) and
  11247. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11248. (p.typ = ait_label) or
  11249. ((p.typ = ait_marker) and
  11250. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11251. p := tai(p.next);
  11252. while assigned(p) and
  11253. (p.typ=ait_RegAlloc) Do
  11254. begin
  11255. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11256. begin
  11257. case tai_regalloc(p).ratype of
  11258. ra_alloc :
  11259. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11260. else
  11261. ;
  11262. end;
  11263. end;
  11264. p := tai(p.next);
  11265. end;
  11266. until not(assigned(p)) or
  11267. (not(p.typ in SkipInstr) and
  11268. not((p.typ = ait_label) and
  11269. labelCanBeSkipped(tai_label(p))));
  11270. end;
  11271. {$ifndef 8086}
  11272. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11273. begin
  11274. Result := False;
  11275. EndJump := nil;
  11276. BlockStop := nil;
  11277. while (BlockStart <> fOptimizer.BlockEnd) and
  11278. { stop on labels }
  11279. (BlockStart.typ <> ait_label) do
  11280. begin
  11281. { Keep track of all integer registers that are used }
  11282. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11283. if BlockStart.typ = ait_instruction then
  11284. begin
  11285. if (taicpu(BlockStart).opcode = A_JMP) then
  11286. begin
  11287. if not IsJumpToLabel(taicpu(BlockStart)) or
  11288. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11289. Exit;
  11290. EndJump := BlockStart;
  11291. Break;
  11292. end
  11293. { Check to see if we have a valid MOV instruction instead }
  11294. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11295. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11296. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11297. begin
  11298. Exit;
  11299. end
  11300. else
  11301. { This will be a valid MOV }
  11302. fAllocationRange := BlockStart;
  11303. end;
  11304. OneBeforeBlock := BlockStart;
  11305. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11306. end;
  11307. if (BlockStart = fOptimizer.BlockEnd) then
  11308. Exit;
  11309. BlockStop := BlockStart;
  11310. Result := True;
  11311. end;
  11312. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  11313. var
  11314. hp1: tai;
  11315. RefModified: Boolean;
  11316. begin
  11317. Result := 0;
  11318. hp1 := BlockStart;
  11319. RefModified := False; { As long as the condition is inverted, this can be reset }
  11320. while assigned(hp1) and
  11321. (hp1 <> BlockStop) do
  11322. begin
  11323. case hp1.typ of
  11324. ait_instruction:
  11325. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11326. begin
  11327. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  11328. begin
  11329. Inc(Result);
  11330. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11331. Assigned(fCondition) and
  11332. { Will have 2 operands }
  11333. (
  11334. (
  11335. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  11336. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  11337. ) or
  11338. (
  11339. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  11340. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  11341. )
  11342. ) then
  11343. { It is no longer safe to use the reference in the condition.
  11344. this prevents problems such as:
  11345. mov (%reg),%reg
  11346. mov (%reg),...
  11347. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11348. (fixes #40165)
  11349. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11350. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11351. }
  11352. RefModified := True;
  11353. end
  11354. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11355. { CMOV with constants grows the code size }
  11356. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  11357. begin
  11358. { Register was reserved by TryCMOVConst and
  11359. stored on ConstRegs }
  11360. end
  11361. else
  11362. begin
  11363. Result := -1;
  11364. Exit;
  11365. end;
  11366. end
  11367. else
  11368. begin
  11369. Result := -1;
  11370. Exit;
  11371. end;
  11372. else
  11373. { Most likely an align };
  11374. end;
  11375. fOptimizer.GetNextInstruction(hp1, hp1);
  11376. end;
  11377. end;
  11378. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  11379. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  11380. (this is done as a separate stage because the double types are extensions of the branching type,
  11381. but we can't discount the conditional jump until the last step) }
  11382. procedure EvaluateBranchingType;
  11383. begin
  11384. Inc(CMOVScore);
  11385. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  11386. { Too many instructions to be worthwhile }
  11387. fState := tsInvalid;
  11388. end;
  11389. var
  11390. hp1: tai;
  11391. Count: Integer;
  11392. begin
  11393. { Table of valid CMOV block types
  11394. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  11395. ---------- --------- --------- --------- --------- ---------
  11396. tsSimple X Yes X X X
  11397. tsDetour = 1st X X X X
  11398. tsBranching <> Mid Yes X X X
  11399. tsDouble End-label Yes * Yes X Yes
  11400. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  11401. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  11402. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  11403. * Only one reference allowed
  11404. }
  11405. hp1 := nil; { To prevent compiler warnings }
  11406. Optimizer.CopyUsedRegs(RegisterTracking);
  11407. fOptimizer := Optimizer;
  11408. fLabel := AFirstLabel;
  11409. CMOVScore := 0;
  11410. ConstCount := 0;
  11411. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11412. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11413. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11414. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11415. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11416. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11417. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11418. fInsertionPoint := p_initialjump;
  11419. fCondition := nil;
  11420. fInitialJump := p_initialjump;
  11421. fFirstMovBlock := p_initialmov;
  11422. fFirstMovBlockStop := nil;
  11423. fSecondJump := nil;
  11424. fSecondMovBlock := nil;
  11425. fSecondMovBlockStop := nil;
  11426. fMidLabel := nil;
  11427. fSecondJump := nil;
  11428. fSecondMovBlock := nil;
  11429. fEndLabel := nil;
  11430. fAllocationRange := nil;
  11431. { Assume it all goes horribly wrong! }
  11432. fState := tsInvalid;
  11433. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  11434. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  11435. 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
  11436. begin
  11437. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11438. for Count := 0 to 1 do
  11439. with taicpu(fCondition).oper[Count]^ do
  11440. case typ of
  11441. top_reg:
  11442. if getregtype(reg) = R_INTREGISTER then
  11443. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11444. top_ref:
  11445. begin
  11446. if
  11447. {$ifdef x86_64}
  11448. (ref^.base <> NR_RIP) and
  11449. {$endif x86_64}
  11450. (ref^.base <> NR_NO) then
  11451. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11452. if (ref^.index <> NR_NO) then
  11453. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11454. end
  11455. else
  11456. ;
  11457. end;
  11458. { When inserting instructions before hp_prev, try to insert them
  11459. before the allocation of the FLAGS register }
  11460. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  11461. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  11462. { If not found, set it equal to the condition so it's something sensible }
  11463. fInsertionPoint := fCondition;
  11464. { When dealing with a comparison against zero, take note of the
  11465. instruction before it to see if we can move instructions further
  11466. back in order to benefit PostPeepholeOptTestOr.
  11467. }
  11468. if (
  11469. (
  11470. (taicpu(fCondition).opcode = A_CMP) and
  11471. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  11472. ) or
  11473. (
  11474. (taicpu(fCondition).opcode = A_TEST) and
  11475. (
  11476. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  11477. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  11478. )
  11479. )
  11480. ) and
  11481. Optimizer.GetLastInstruction(fCondition, hp1) then
  11482. begin
  11483. { These instructions set the zero flag if the result is zero }
  11484. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11485. begin
  11486. fInsertionPoint := hp1;
  11487. { Also mark all the registers in this previous instruction
  11488. as 'in use', even if they've just been deallocated }
  11489. for Count := 0 to 1 do
  11490. with taicpu(hp1).oper[Count]^ do
  11491. case typ of
  11492. top_reg:
  11493. if getregtype(reg) = R_INTREGISTER then
  11494. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11495. top_ref:
  11496. begin
  11497. if
  11498. {$ifdef x86_64}
  11499. (ref^.base <> NR_RIP) and
  11500. {$endif x86_64}
  11501. (ref^.base <> NR_NO) then
  11502. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11503. if (ref^.index <> NR_NO) then
  11504. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11505. end
  11506. else
  11507. ;
  11508. end;
  11509. end;
  11510. end;
  11511. end
  11512. else
  11513. fCondition := nil;
  11514. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  11515. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  11516. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  11517. { If not found, set it equal to p so it's something sensible }
  11518. fInsertionPoint := hp1;
  11519. hp1 := p_initialmov;
  11520. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  11521. Exit;
  11522. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  11523. if (hp1.typ <> ait_label) then { should be on a jump }
  11524. begin
  11525. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  11526. { Need a label afterwards }
  11527. Exit;
  11528. end
  11529. else
  11530. fMidLabel := hp1;
  11531. if tai_label(fMidLabel).labsym <> AFirstLabel then
  11532. { Not the correct label }
  11533. fMidLabel := nil;
  11534. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  11535. { If there's neither a 2nd jump nor correct label, then it's invalid
  11536. (see above table) }
  11537. Exit;
  11538. { Analyse the first block of MOVs more closely }
  11539. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  11540. if Assigned(fSecondJump) then
  11541. begin
  11542. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  11543. begin
  11544. fState := tsDetour
  11545. end
  11546. else
  11547. begin
  11548. { Need the correct mid-label for this one }
  11549. if not Assigned(fMidLabel) then
  11550. Exit;
  11551. fState := tsBranching;
  11552. end;
  11553. end
  11554. else
  11555. { No jump. but mid-label is present }
  11556. fState := tsSimple;
  11557. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  11558. begin
  11559. { Invalid or too many instructions to be worthwhile }
  11560. fState := tsInvalid;
  11561. Exit;
  11562. end;
  11563. { check further for
  11564. jCC xxx
  11565. <several movs 1>
  11566. jmp yyy
  11567. xxx:
  11568. <several movs 2>
  11569. yyy:
  11570. etc.
  11571. }
  11572. if (fState = tsBranching) and
  11573. { Estimate for required savings for extra jump }
  11574. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  11575. { Only one reference is allowed for double blocks }
  11576. (AFirstLabel.getrefs = 1) then
  11577. begin
  11578. Optimizer.GetNextInstruction(fMidLabel, hp1);
  11579. fSecondMovBlock := hp1;
  11580. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  11581. begin
  11582. EvaluateBranchingType;
  11583. Exit;
  11584. end;
  11585. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  11586. if (hp1.typ <> ait_label) then { should be on a jump }
  11587. begin
  11588. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  11589. begin
  11590. { Need a label afterwards }
  11591. EvaluateBranchingType;
  11592. Exit;
  11593. end;
  11594. end
  11595. else
  11596. fEndLabel := hp1;
  11597. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  11598. { Second jump doesn't go to the end }
  11599. fEndLabel := nil;
  11600. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  11601. begin
  11602. { If there's neither a 3rd jump nor correct end label, then it's
  11603. not a invalid double block, but is a valid single branching
  11604. block (see above table) }
  11605. EvaluateBranchingType;
  11606. Exit;
  11607. end;
  11608. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  11609. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  11610. { Invalid or too many instructions to be worthwhile }
  11611. Exit;
  11612. Inc(CMOVScore, Count);
  11613. if Assigned(fThirdJump) then
  11614. begin
  11615. if not Assigned(fSecondJump) then
  11616. fState := tsDoubleSecondBranching
  11617. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  11618. fState := tsDoubleBranchSame
  11619. else
  11620. fState := tsDoubleBranchDifferent;
  11621. end
  11622. else
  11623. fState := tsDouble;
  11624. end;
  11625. if fState = tsBranching then
  11626. EvaluateBranchingType;
  11627. end;
  11628. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  11629. new register to store the constant }
  11630. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  11631. var
  11632. RegSize: TSubRegister;
  11633. CurrentVal: TCGInt;
  11634. ANewReg: TRegister;
  11635. X: ShortInt;
  11636. begin
  11637. Result := False;
  11638. if not MatchOpType(taicpu(p), top_const, top_reg) then
  11639. Exit;
  11640. if ConstCount >= MAX_CMOV_REGISTERS then
  11641. { Arrays are full }
  11642. Exit;
  11643. { Remember that CMOV can't encode 8-bit registers }
  11644. case taicpu(p).opsize of
  11645. S_W:
  11646. RegSize := R_SUBW;
  11647. S_L:
  11648. RegSize := R_SUBD;
  11649. {$ifdef x86_64}
  11650. S_Q:
  11651. RegSize := R_SUBQ;
  11652. {$endif x86_64}
  11653. else
  11654. InternalError(2021100401);
  11655. end;
  11656. { See if the value has already been reserved for another CMOV instruction }
  11657. CurrentVal := taicpu(p).oper[0]^.val;
  11658. for X := 0 to ConstCount - 1 do
  11659. if ConstVals[X] = CurrentVal then
  11660. begin
  11661. ConstRegs[ConstCount] := ConstRegs[X];
  11662. ConstSizes[ConstCount] := RegSize;
  11663. ConstVals[ConstCount] := CurrentVal;
  11664. Inc(ConstCount);
  11665. Inc(Count);
  11666. Result := True;
  11667. Exit;
  11668. end;
  11669. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  11670. if ANewReg = NR_NO then
  11671. { No free registers }
  11672. Exit;
  11673. { Reserve the register so subsequent TryCMOVConst calls don't all end
  11674. up vying for the same register }
  11675. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  11676. ConstRegs[ConstCount] := ANewReg;
  11677. ConstSizes[ConstCount] := RegSize;
  11678. ConstVals[ConstCount] := CurrentVal;
  11679. Inc(ConstCount);
  11680. Inc(Count);
  11681. Result := True;
  11682. end;
  11683. destructor TCMOVTracking.Done;
  11684. begin
  11685. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  11686. end;
  11687. procedure TCMOVTracking.Process(out new_p: tai);
  11688. var
  11689. Count, Writes: LongInt;
  11690. RegMatch: Boolean;
  11691. hp1, hp_new: tai;
  11692. inverted_condition, condition: TAsmCond;
  11693. begin
  11694. if (fState in [tsInvalid, tsProcessed]) then
  11695. InternalError(2023110701);
  11696. { Repurpose RegisterTracking to mark registers that we've defined }
  11697. RegisterTracking[R_INTREGISTER].Clear;
  11698. Count := 0;
  11699. Writes := 0;
  11700. condition := taicpu(fInitialJump).condition;
  11701. inverted_condition := inverse_cond(condition);
  11702. { Exclude tsDoubleBranchDifferent from this check, as the second block
  11703. doesn't get CMOVs in this case }
  11704. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  11705. begin
  11706. { Include the jump in the flag tracking }
  11707. if Assigned(fThirdJump) then
  11708. begin
  11709. if (fState = tsDoubleBranchSame) then
  11710. begin
  11711. { Will be an unconditional jump, so track to the instruction before it }
  11712. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  11713. InternalError(2023110710);
  11714. end
  11715. else
  11716. hp1 := fThirdJump;
  11717. end
  11718. else
  11719. hp1 := fSecondMovBlockStop;
  11720. end
  11721. else
  11722. begin
  11723. { Include a conditional jump in the flag tracking }
  11724. if Assigned(fSecondJump) then
  11725. begin
  11726. if (fState = tsDetour) then
  11727. begin
  11728. { Will be an unconditional jump, so track to the instruction before it }
  11729. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  11730. InternalError(2023110711);
  11731. end
  11732. else
  11733. hp1 := fSecondJump;
  11734. end
  11735. else
  11736. hp1 := fFirstMovBlockStop;
  11737. end;
  11738. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  11739. { Process the second set of MOVs first, because if a destination
  11740. register is shared between the first and second MOV sets, it is more
  11741. efficient to turn the first one into a MOV instruction and place it
  11742. before the CMP if possible, but we won't know which registers are
  11743. shared until we've processed at least one list, so we might as well
  11744. make it the second one since that won't be modified again. }
  11745. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  11746. begin
  11747. hp1 := fSecondMovBlock;
  11748. repeat
  11749. if not Assigned(hp1) then
  11750. InternalError(2018062902);
  11751. if (hp1.typ = ait_instruction) then
  11752. begin
  11753. { Extra safeguard }
  11754. if (taicpu(hp1).opcode <> A_MOV) then
  11755. InternalError(2018062903);
  11756. { Note: tsDoubleBranchDifferent is essentially identical to
  11757. tsBranching and the 2nd block is best left largely
  11758. untouched, but we need to evaluate which registers the MOVs
  11759. write to in order to track what would be complementary CMOV
  11760. pairs that can be further optimised. [Kit] }
  11761. if fState <> tsDoubleBranchDifferent then
  11762. begin
  11763. if taicpu(hp1).oper[0]^.typ = top_const then
  11764. begin
  11765. RegMatch := False;
  11766. for Count := 0 to ConstCount - 1 do
  11767. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  11768. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  11769. begin
  11770. RegMatch := True;
  11771. { If it's in RegisterTracking, then this register
  11772. is being used more than once and hence has
  11773. already had its value defined (it gets added to
  11774. UsedRegs through AllocRegBetween below) }
  11775. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  11776. begin
  11777. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  11778. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  11779. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  11780. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  11781. ConstMovs[Count] := hp_new;
  11782. end
  11783. else
  11784. { We just need an instruction between hp_prev and hp1
  11785. where we know the register is marked as in use }
  11786. hp_new := fSecondMovBlock;
  11787. { Keep track of largest write for this register so it can be optimised later }
  11788. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  11789. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11790. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  11791. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  11792. Break;
  11793. end;
  11794. if not RegMatch then
  11795. InternalError(2021100411);
  11796. end;
  11797. taicpu(hp1).opcode := A_CMOVcc;
  11798. taicpu(hp1).condition := condition;
  11799. end;
  11800. { Store these writes to search for duplicates later on }
  11801. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  11802. Inc(Writes);
  11803. end;
  11804. fOptimizer.GetNextInstruction(hp1, hp1);
  11805. until (hp1 = fSecondMovBlockStop);
  11806. end;
  11807. { Now do the first set of MOVs }
  11808. hp1 := fFirstMovBlock;
  11809. repeat
  11810. if not Assigned(hp1) then
  11811. InternalError(2018062904);
  11812. if (hp1.typ = ait_instruction) then
  11813. begin
  11814. RegMatch := False;
  11815. { Extra safeguard }
  11816. if (taicpu(hp1).opcode <> A_MOV) then
  11817. InternalError(2018062905);
  11818. { Search through the RegWrites list to see if there are any
  11819. opposing CMOV pairs that write to the same register }
  11820. for Count := 0 to Writes - 1 do
  11821. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  11822. begin
  11823. { We have a match. Keep this as a MOV }
  11824. { Move ahead in preparation }
  11825. fOptimizer.GetNextInstruction(hp1, hp1);
  11826. RegMatch := True;
  11827. Break;
  11828. end;
  11829. if RegMatch then
  11830. Continue;
  11831. if taicpu(hp1).oper[0]^.typ = top_const then
  11832. begin
  11833. for Count := 0 to ConstCount - 1 do
  11834. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  11835. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  11836. begin
  11837. RegMatch := True;
  11838. { If it's in RegisterTracking, then this register is
  11839. being used more than once and hence has already had
  11840. its value defined (it gets added to UsedRegs through
  11841. AllocRegBetween below) }
  11842. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  11843. begin
  11844. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  11845. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  11846. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  11847. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  11848. ConstMovs[Count] := hp_new;
  11849. end
  11850. else
  11851. { We just need an instruction between hp_prev and hp1
  11852. where we know the register is marked as in use }
  11853. hp_new := fFirstMovBlock;
  11854. { Keep track of largest write for this register so it can be optimised later }
  11855. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  11856. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11857. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  11858. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  11859. Break;
  11860. end;
  11861. if not RegMatch then
  11862. InternalError(2021100412);
  11863. end;
  11864. taicpu(hp1).opcode := A_CMOVcc;
  11865. taicpu(hp1).condition := inverted_condition;
  11866. if (fState = tsDoubleBranchDifferent) then
  11867. begin
  11868. { Store these writes to search for duplicates later on }
  11869. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  11870. Inc(Writes);
  11871. end;
  11872. end;
  11873. fOptimizer.GetNextInstruction(hp1, hp1);
  11874. until (hp1 = fFirstMovBlockStop);
  11875. { Update initialisation MOVs to the smallest possible size }
  11876. for Count := 0 to ConstCount - 1 do
  11877. if Assigned(ConstMovs[Count]) then
  11878. begin
  11879. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  11880. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  11881. end;
  11882. case fState of
  11883. tsSimple:
  11884. begin
  11885. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  11886. { No branch to delete }
  11887. end;
  11888. tsDetour:
  11889. begin
  11890. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  11891. { Preserve jump }
  11892. end;
  11893. tsBranching, tsDoubleBranchDifferent:
  11894. begin
  11895. if (fState = tsBranching) then
  11896. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  11897. else
  11898. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  11899. taicpu(fSecondJump).opcode := A_JCC;
  11900. taicpu(fSecondJump).condition := inverted_condition;
  11901. end;
  11902. tsDouble, tsDoubleBranchSame:
  11903. begin
  11904. if (fState = tsDouble) then
  11905. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  11906. else
  11907. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  11908. { Delete second jump }
  11909. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  11910. fOptimizer.RemoveInstruction(fSecondJump);
  11911. end;
  11912. tsDoubleSecondBranching:
  11913. begin
  11914. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  11915. { Delete second jump, preserve third jump as conditional }
  11916. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  11917. fOptimizer.RemoveInstruction(fSecondJump);
  11918. taicpu(fThirdJump).opcode := A_JCC;
  11919. taicpu(fThirdJump).condition := condition;
  11920. end;
  11921. else
  11922. InternalError(2023110720);
  11923. end;
  11924. { Now we can safely decrement the reference count }
  11925. tasmlabel(fLabel).decrefs;
  11926. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  11927. { Remove the original jump }
  11928. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  11929. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  11930. fState := tsProcessed;
  11931. end;
  11932. {$endif 8086}
  11933. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  11934. var
  11935. hp1,hp2: tai;
  11936. carryadd_opcode : TAsmOp;
  11937. symbol: TAsmSymbol;
  11938. increg, tmpreg: TRegister;
  11939. {$ifndef i8086}
  11940. CMOVTracking: PCMOVTracking;
  11941. hp3,hp4,hp5: tai;
  11942. {$endif i8086}
  11943. TempBool: Boolean;
  11944. begin
  11945. if (aoc_DoPass2JccOpts in OptsToCheck) and
  11946. DoJumpOptimizations(p, TempBool) then
  11947. Exit(True);
  11948. result:=false;
  11949. if GetNextInstruction(p,hp1) then
  11950. begin
  11951. if (hp1.typ=ait_label) then
  11952. begin
  11953. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  11954. Exit;
  11955. end
  11956. else if (hp1.typ<>ait_instruction) then
  11957. Exit;
  11958. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11959. if (
  11960. (
  11961. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  11962. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  11963. (Taicpu(hp1).oper[0]^.val=1)
  11964. ) or
  11965. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  11966. ) and
  11967. GetNextInstruction(hp1,hp2) and
  11968. (hp2.typ = ait_label) and
  11969. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  11970. { jb @@1 cmc
  11971. inc/dec operand --> adc/sbb operand,0
  11972. @@1:
  11973. ... and ...
  11974. jnb @@1
  11975. inc/dec operand --> adc/sbb operand,0
  11976. @@1: }
  11977. begin
  11978. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  11979. begin
  11980. case taicpu(hp1).opcode of
  11981. A_INC,
  11982. A_ADD:
  11983. carryadd_opcode:=A_ADC;
  11984. A_DEC,
  11985. A_SUB:
  11986. carryadd_opcode:=A_SBB;
  11987. else
  11988. InternalError(2021011001);
  11989. end;
  11990. Taicpu(p).clearop(0);
  11991. Taicpu(p).ops:=0;
  11992. Taicpu(p).is_jmp:=false;
  11993. Taicpu(p).opcode:=A_CMC;
  11994. Taicpu(p).condition:=C_NONE;
  11995. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  11996. Taicpu(hp1).ops:=2;
  11997. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  11998. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  11999. else
  12000. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12001. Taicpu(hp1).loadconst(0,0);
  12002. Taicpu(hp1).opcode:=carryadd_opcode;
  12003. result:=true;
  12004. exit;
  12005. end
  12006. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12007. begin
  12008. case taicpu(hp1).opcode of
  12009. A_INC,
  12010. A_ADD:
  12011. carryadd_opcode:=A_ADC;
  12012. A_DEC,
  12013. A_SUB:
  12014. carryadd_opcode:=A_SBB;
  12015. else
  12016. InternalError(2021011002);
  12017. end;
  12018. Taicpu(hp1).ops:=2;
  12019. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12020. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12021. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12022. else
  12023. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12024. Taicpu(hp1).loadconst(0,0);
  12025. Taicpu(hp1).opcode:=carryadd_opcode;
  12026. RemoveCurrentP(p, hp1);
  12027. result:=true;
  12028. exit;
  12029. end
  12030. {
  12031. jcc @@1 setcc tmpreg
  12032. inc/dec/add/sub operand -> (movzx tmpreg)
  12033. @@1: add/sub tmpreg,operand
  12034. While this increases code size slightly, it makes the code much faster if the
  12035. jump is unpredictable
  12036. }
  12037. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12038. begin
  12039. { search for an available register which is volatile }
  12040. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12041. if increg <> NR_NO then
  12042. begin
  12043. { We don't need to check if tmpreg is in hp1 or not, because
  12044. it will be marked as in use at p (if not, this is
  12045. indictive of a compiler bug). }
  12046. TAsmLabel(symbol).decrefs;
  12047. Taicpu(p).clearop(0);
  12048. Taicpu(p).ops:=1;
  12049. Taicpu(p).is_jmp:=false;
  12050. Taicpu(p).opcode:=A_SETcc;
  12051. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12052. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12053. Taicpu(p).loadreg(0,increg);
  12054. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12055. begin
  12056. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12057. R_SUBW:
  12058. begin
  12059. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12060. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12061. end;
  12062. R_SUBD:
  12063. begin
  12064. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12065. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12066. end;
  12067. {$ifdef x86_64}
  12068. R_SUBQ:
  12069. begin
  12070. { MOVZX doesn't have a 64-bit variant, because
  12071. the 32-bit version implicitly zeroes the
  12072. upper 32-bits of the destination register }
  12073. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12074. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12075. setsubreg(tmpreg, R_SUBQ);
  12076. end;
  12077. {$endif x86_64}
  12078. else
  12079. Internalerror(2020030601);
  12080. end;
  12081. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12082. asml.InsertAfter(hp2,p);
  12083. end
  12084. else
  12085. tmpreg := increg;
  12086. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12087. begin
  12088. Taicpu(hp1).ops:=2;
  12089. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12090. end;
  12091. Taicpu(hp1).loadreg(0,tmpreg);
  12092. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12093. Result := True;
  12094. { p is no longer a Jcc instruction, so exit }
  12095. Exit;
  12096. end;
  12097. end;
  12098. end;
  12099. { Detect the following:
  12100. jmp<cond> @Lbl1
  12101. jmp @Lbl2
  12102. ...
  12103. @Lbl1:
  12104. ret
  12105. Change to:
  12106. jmp<inv_cond> @Lbl2
  12107. ret
  12108. }
  12109. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12110. begin
  12111. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12112. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12113. MatchInstruction(hp2,A_RET,[S_NO]) then
  12114. begin
  12115. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12116. { Change label address to that of the unconditional jump }
  12117. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12118. TAsmLabel(symbol).DecRefs;
  12119. taicpu(hp1).opcode := A_RET;
  12120. taicpu(hp1).is_jmp := false;
  12121. taicpu(hp1).ops := taicpu(hp2).ops;
  12122. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12123. case taicpu(hp2).ops of
  12124. 0:
  12125. taicpu(hp1).clearop(0);
  12126. 1:
  12127. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12128. else
  12129. internalerror(2016041302);
  12130. end;
  12131. end;
  12132. {$ifndef i8086}
  12133. end
  12134. {
  12135. convert
  12136. j<c> .L1
  12137. mov 1,reg
  12138. jmp .L2
  12139. .L1
  12140. mov 0,reg
  12141. .L2
  12142. into
  12143. mov 0,reg
  12144. set<not(c)> reg
  12145. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12146. would destroy the flag contents
  12147. }
  12148. else if MatchInstruction(hp1,A_MOV,[]) and
  12149. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12150. {$ifdef i386}
  12151. (
  12152. { Under i386, ESI, EDI, EBP and ESP
  12153. don't have an 8-bit representation }
  12154. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12155. ) and
  12156. {$endif i386}
  12157. (taicpu(hp1).oper[0]^.val=1) and
  12158. GetNextInstruction(hp1,hp2) and
  12159. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12160. GetNextInstruction(hp2,hp3) and
  12161. (hp3.typ=ait_label) and
  12162. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12163. (tai_label(hp3).labsym.getrefs=1) and
  12164. GetNextInstruction(hp3,hp4) and
  12165. MatchInstruction(hp4,A_MOV,[]) and
  12166. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12167. (taicpu(hp4).oper[0]^.val=0) and
  12168. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12169. GetNextInstruction(hp4,hp5) and
  12170. (hp5.typ=ait_label) and
  12171. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12172. (tai_label(hp5).labsym.getrefs=1) then
  12173. begin
  12174. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12175. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12176. { remove last label }
  12177. RemoveInstruction(hp5);
  12178. { remove second label }
  12179. RemoveInstruction(hp3);
  12180. { remove jmp }
  12181. RemoveInstruction(hp2);
  12182. if taicpu(hp1).opsize=S_B then
  12183. RemoveInstruction(hp1)
  12184. else
  12185. taicpu(hp1).loadconst(0,0);
  12186. taicpu(hp4).opcode:=A_SETcc;
  12187. taicpu(hp4).opsize:=S_B;
  12188. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12189. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12190. taicpu(hp4).opercnt:=1;
  12191. taicpu(hp4).ops:=1;
  12192. taicpu(hp4).freeop(1);
  12193. RemoveCurrentP(p);
  12194. Result:=true;
  12195. exit;
  12196. end
  12197. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12198. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12199. begin
  12200. { check for
  12201. jCC xxx
  12202. <several movs>
  12203. xxx:
  12204. Also spot:
  12205. Jcc xxx
  12206. <several movs>
  12207. jmp xxx
  12208. Change to:
  12209. <several cmovs with inverted condition>
  12210. jmp xxx (only for the 2nd case)
  12211. }
  12212. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12213. if CMOVTracking^.State <> tsInvalid then
  12214. begin
  12215. CMovTracking^.Process(p);
  12216. Result := True;
  12217. end;
  12218. CMOVTracking^.Done;
  12219. {$endif i8086}
  12220. end;
  12221. end;
  12222. end;
  12223. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12224. var
  12225. hp1,hp2,hp3: tai;
  12226. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12227. NewSize: TOpSize;
  12228. NewRegSize: TSubRegister;
  12229. Limit: TCgInt;
  12230. SwapOper: POper;
  12231. begin
  12232. result:=false;
  12233. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12234. GetNextInstruction(p,hp1) and
  12235. (hp1.typ = ait_instruction);
  12236. if reg_and_hp1_is_instr and
  12237. (
  12238. (taicpu(hp1).opcode <> A_LEA) or
  12239. { If the LEA instruction can be converted into an arithmetic instruction,
  12240. it may be possible to then fold it. }
  12241. (
  12242. { If the flags register is in use, don't change the instruction
  12243. to an ADD otherwise this will scramble the flags. [Kit] }
  12244. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12245. ConvertLEA(taicpu(hp1))
  12246. )
  12247. ) and
  12248. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12249. GetNextInstruction(hp1,hp2) and
  12250. MatchInstruction(hp2,A_MOV,[]) and
  12251. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12252. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12253. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12254. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12255. {$ifdef i386}
  12256. { not all registers have byte size sub registers on i386 }
  12257. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12258. {$endif i386}
  12259. (((taicpu(hp1).ops=2) and
  12260. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12261. ((taicpu(hp1).ops=1) and
  12262. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12263. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12264. begin
  12265. { change movsX/movzX reg/ref, reg2
  12266. add/sub/or/... reg3/$const, reg2
  12267. mov reg2 reg/ref
  12268. to add/sub/or/... reg3/$const, reg/ref }
  12269. { by example:
  12270. movswl %si,%eax movswl %si,%eax p
  12271. decl %eax addl %edx,%eax hp1
  12272. movw %ax,%si movw %ax,%si hp2
  12273. ->
  12274. movswl %si,%eax movswl %si,%eax p
  12275. decw %eax addw %edx,%eax hp1
  12276. movw %ax,%si movw %ax,%si hp2
  12277. }
  12278. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12279. {
  12280. ->
  12281. movswl %si,%eax movswl %si,%eax p
  12282. decw %si addw %dx,%si hp1
  12283. movw %ax,%si movw %ax,%si hp2
  12284. }
  12285. case taicpu(hp1).ops of
  12286. 1:
  12287. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12288. 2:
  12289. begin
  12290. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12291. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12292. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12293. end;
  12294. else
  12295. internalerror(2008042702);
  12296. end;
  12297. {
  12298. ->
  12299. decw %si addw %dx,%si p
  12300. }
  12301. DebugMsg(SPeepholeOptimization + 'var3',p);
  12302. RemoveCurrentP(p, hp1);
  12303. RemoveInstruction(hp2);
  12304. Result := True;
  12305. Exit;
  12306. end;
  12307. if reg_and_hp1_is_instr and
  12308. (taicpu(hp1).opcode = A_MOV) and
  12309. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12310. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12311. {$ifdef x86_64}
  12312. { check for implicit extension to 64 bit }
  12313. or
  12314. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12315. (taicpu(hp1).opsize=S_Q) and
  12316. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  12317. )
  12318. {$endif x86_64}
  12319. )
  12320. then
  12321. begin
  12322. { change
  12323. movx %reg1,%reg2
  12324. mov %reg2,%reg3
  12325. dealloc %reg2
  12326. into
  12327. movx %reg,%reg3
  12328. }
  12329. TransferUsedRegs(TmpUsedRegs);
  12330. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12331. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  12332. begin
  12333. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  12334. {$ifdef x86_64}
  12335. if (taicpu(p).opsize in [S_BL,S_WL]) and
  12336. (taicpu(hp1).opsize=S_Q) then
  12337. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  12338. else
  12339. {$endif x86_64}
  12340. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  12341. RemoveInstruction(hp1);
  12342. Result := True;
  12343. Exit;
  12344. end;
  12345. end;
  12346. if reg_and_hp1_is_instr and
  12347. ((taicpu(hp1).opcode=A_MOV) or
  12348. (taicpu(hp1).opcode=A_ADD) or
  12349. (taicpu(hp1).opcode=A_SUB) or
  12350. (taicpu(hp1).opcode=A_CMP) or
  12351. (taicpu(hp1).opcode=A_OR) or
  12352. (taicpu(hp1).opcode=A_XOR) or
  12353. (taicpu(hp1).opcode=A_AND)
  12354. ) and
  12355. (taicpu(hp1).oper[1]^.typ = top_reg) then
  12356. begin
  12357. AndTest := (taicpu(hp1).opcode=A_AND) and
  12358. GetNextInstruction(hp1, hp2) and
  12359. (hp2.typ = ait_instruction) and
  12360. (
  12361. (
  12362. (taicpu(hp2).opcode=A_TEST) and
  12363. (
  12364. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  12365. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  12366. (
  12367. { If the AND and TEST instructions share a constant, this is also valid }
  12368. (taicpu(hp1).oper[0]^.typ = top_const) and
  12369. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  12370. )
  12371. ) and
  12372. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12373. ) or
  12374. (
  12375. (taicpu(hp2).opcode=A_CMP) and
  12376. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  12377. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12378. )
  12379. );
  12380. { change
  12381. movx (oper),%reg2
  12382. and $x,%reg2
  12383. test %reg2,%reg2
  12384. dealloc %reg2
  12385. into
  12386. op %reg1,%reg3
  12387. if the second op accesses only the bits stored in reg1
  12388. }
  12389. if ((taicpu(p).oper[0]^.typ=top_reg) or
  12390. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  12391. (taicpu(hp1).oper[0]^.typ = top_const) and
  12392. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12393. AndTest then
  12394. begin
  12395. { Check if the AND constant is in range }
  12396. case taicpu(p).opsize of
  12397. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12398. begin
  12399. NewSize := S_B;
  12400. Limit := $FF;
  12401. end;
  12402. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12403. begin
  12404. NewSize := S_W;
  12405. Limit := $FFFF;
  12406. end;
  12407. {$ifdef x86_64}
  12408. S_LQ:
  12409. begin
  12410. NewSize := S_L;
  12411. Limit := $FFFFFFFF;
  12412. end;
  12413. {$endif x86_64}
  12414. else
  12415. InternalError(2021120303);
  12416. end;
  12417. if (
  12418. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  12419. { Check for negative operands }
  12420. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  12421. ) and
  12422. GetNextInstruction(hp2,hp3) and
  12423. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  12424. (taicpu(hp3).condition in [C_E,C_NE]) then
  12425. begin
  12426. TransferUsedRegs(TmpUsedRegs);
  12427. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12428. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12429. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  12430. begin
  12431. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  12432. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12433. taicpu(hp1).opcode := A_TEST;
  12434. taicpu(hp1).opsize := NewSize;
  12435. RemoveInstruction(hp2);
  12436. RemoveCurrentP(p, hp1);
  12437. Result:=true;
  12438. exit;
  12439. end;
  12440. end;
  12441. end;
  12442. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12443. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  12444. (taicpu(hp1).opsize=S_B)) or
  12445. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  12446. (taicpu(hp1).opsize=S_W))
  12447. {$ifdef x86_64}
  12448. or ((taicpu(p).opsize=S_LQ) and
  12449. (taicpu(hp1).opsize=S_L))
  12450. {$endif x86_64}
  12451. ) and
  12452. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  12453. begin
  12454. { change
  12455. movx %reg1,%reg2
  12456. op %reg2,%reg3
  12457. dealloc %reg2
  12458. into
  12459. op %reg1,%reg3
  12460. if the second op accesses only the bits stored in reg1
  12461. }
  12462. TransferUsedRegs(TmpUsedRegs);
  12463. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12464. if AndTest then
  12465. begin
  12466. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12467. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12468. end
  12469. else
  12470. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12471. if not RegUsed then
  12472. begin
  12473. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  12474. if taicpu(p).oper[0]^.typ=top_reg then
  12475. begin
  12476. case taicpu(hp1).opsize of
  12477. S_B:
  12478. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  12479. S_W:
  12480. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  12481. S_L:
  12482. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  12483. else
  12484. Internalerror(2020102301);
  12485. end;
  12486. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  12487. end
  12488. else
  12489. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  12490. RemoveCurrentP(p);
  12491. if AndTest then
  12492. RemoveInstruction(hp2);
  12493. result:=true;
  12494. exit;
  12495. end;
  12496. end
  12497. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12498. (
  12499. { Bitwise operations only }
  12500. (taicpu(hp1).opcode=A_AND) or
  12501. (taicpu(hp1).opcode=A_TEST) or
  12502. (
  12503. (taicpu(hp1).oper[0]^.typ = top_const) and
  12504. (
  12505. (taicpu(hp1).opcode=A_OR) or
  12506. (taicpu(hp1).opcode=A_XOR)
  12507. )
  12508. )
  12509. ) and
  12510. (
  12511. (taicpu(hp1).oper[0]^.typ = top_const) or
  12512. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  12513. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  12514. ) then
  12515. begin
  12516. { change
  12517. movx %reg2,%reg2
  12518. op const,%reg2
  12519. into
  12520. op const,%reg2 (smaller version)
  12521. movx %reg2,%reg2
  12522. also change
  12523. movx %reg1,%reg2
  12524. and/test (oper),%reg2
  12525. dealloc %reg2
  12526. into
  12527. and/test (oper),%reg1
  12528. }
  12529. case taicpu(p).opsize of
  12530. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12531. begin
  12532. NewSize := S_B;
  12533. NewRegSize := R_SUBL;
  12534. Limit := $FF;
  12535. end;
  12536. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12537. begin
  12538. NewSize := S_W;
  12539. NewRegSize := R_SUBW;
  12540. Limit := $FFFF;
  12541. end;
  12542. {$ifdef x86_64}
  12543. S_LQ:
  12544. begin
  12545. NewSize := S_L;
  12546. NewRegSize := R_SUBD;
  12547. Limit := $FFFFFFFF;
  12548. end;
  12549. {$endif x86_64}
  12550. else
  12551. Internalerror(2021120302);
  12552. end;
  12553. TransferUsedRegs(TmpUsedRegs);
  12554. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12555. if AndTest then
  12556. begin
  12557. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12558. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12559. end
  12560. else
  12561. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12562. if
  12563. (
  12564. (taicpu(p).opcode = A_MOVZX) and
  12565. (
  12566. (taicpu(hp1).opcode=A_AND) or
  12567. (taicpu(hp1).opcode=A_TEST)
  12568. ) and
  12569. not (
  12570. { If both are references, then the final instruction will have
  12571. both operands as references, which is not allowed }
  12572. (taicpu(p).oper[0]^.typ = top_ref) and
  12573. (taicpu(hp1).oper[0]^.typ = top_ref)
  12574. ) and
  12575. not RegUsed
  12576. ) or
  12577. (
  12578. (
  12579. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  12580. not RegUsed
  12581. ) and
  12582. (taicpu(p).oper[0]^.typ = top_reg) and
  12583. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12584. (taicpu(hp1).oper[0]^.typ = top_const) and
  12585. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  12586. ) then
  12587. begin
  12588. {$if defined(i386) or defined(i8086)}
  12589. { If the target size is 8-bit, make sure we can actually encode it }
  12590. 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
  12591. Exit;
  12592. {$endif i386 or i8086}
  12593. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  12594. taicpu(hp1).opsize := NewSize;
  12595. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12596. if AndTest then
  12597. begin
  12598. RemoveInstruction(hp2);
  12599. if not RegUsed then
  12600. begin
  12601. taicpu(hp1).opcode := A_TEST;
  12602. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  12603. begin
  12604. { Make sure the reference is the second operand }
  12605. SwapOper := taicpu(hp1).oper[0];
  12606. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  12607. taicpu(hp1).oper[1] := SwapOper;
  12608. end;
  12609. end;
  12610. end;
  12611. case taicpu(hp1).oper[0]^.typ of
  12612. top_reg:
  12613. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  12614. top_const:
  12615. { For the AND/TEST case }
  12616. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  12617. else
  12618. ;
  12619. end;
  12620. if RegUsed then
  12621. begin
  12622. AsmL.Remove(p);
  12623. AsmL.InsertAfter(p, hp1);
  12624. p := hp1;
  12625. end
  12626. else
  12627. RemoveCurrentP(p, hp1);
  12628. result:=true;
  12629. exit;
  12630. end;
  12631. end;
  12632. end;
  12633. if reg_and_hp1_is_instr and
  12634. (taicpu(p).oper[0]^.typ = top_reg) and
  12635. (
  12636. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  12637. ) and
  12638. (taicpu(hp1).oper[0]^.typ = top_const) and
  12639. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12640. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12641. { Minimum shift value allowed is the bit difference between the sizes }
  12642. (taicpu(hp1).oper[0]^.val >=
  12643. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12644. 8 * (
  12645. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  12646. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12647. )
  12648. ) then
  12649. begin
  12650. { For:
  12651. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  12652. shl/sal ##, %reg1
  12653. Remove the movsx/movzx instruction if the shift overwrites the
  12654. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  12655. }
  12656. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  12657. RemoveCurrentP(p, hp1);
  12658. Result := True;
  12659. Exit;
  12660. end
  12661. else if reg_and_hp1_is_instr and
  12662. (taicpu(p).oper[0]^.typ = top_reg) and
  12663. (
  12664. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  12665. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  12666. ) and
  12667. (taicpu(hp1).oper[0]^.typ = top_const) and
  12668. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12669. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12670. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  12671. (taicpu(hp1).oper[0]^.val <
  12672. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12673. 8 * (
  12674. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12675. )
  12676. ) then
  12677. begin
  12678. { For:
  12679. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  12680. sar ##, %reg1 shr ##, %reg1
  12681. Move the shift to before the movx instruction if the shift value
  12682. is not too large.
  12683. }
  12684. asml.Remove(hp1);
  12685. asml.InsertBefore(hp1, p);
  12686. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12687. case taicpu(p).opsize of
  12688. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  12689. taicpu(hp1).opsize := S_B;
  12690. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  12691. taicpu(hp1).opsize := S_W;
  12692. {$ifdef x86_64}
  12693. S_LQ:
  12694. taicpu(hp1).opsize := S_L;
  12695. {$endif}
  12696. else
  12697. InternalError(2020112401);
  12698. end;
  12699. if (taicpu(hp1).opcode = A_SHR) then
  12700. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  12701. else
  12702. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  12703. Result := True;
  12704. end;
  12705. if reg_and_hp1_is_instr and
  12706. (taicpu(p).oper[0]^.typ = top_reg) and
  12707. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12708. (
  12709. (taicpu(hp1).opcode = taicpu(p).opcode)
  12710. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  12711. {$ifdef x86_64}
  12712. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  12713. {$endif x86_64}
  12714. ) then
  12715. begin
  12716. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12717. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  12718. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12719. begin
  12720. {
  12721. For example:
  12722. movzbw %al,%ax
  12723. movzwl %ax,%eax
  12724. Compress into:
  12725. movzbl %al,%eax
  12726. }
  12727. RegUsed := False;
  12728. case taicpu(p).opsize of
  12729. S_BW:
  12730. case taicpu(hp1).opsize of
  12731. S_WL:
  12732. begin
  12733. taicpu(p).opsize := S_BL;
  12734. RegUsed := True;
  12735. end;
  12736. {$ifdef x86_64}
  12737. S_WQ:
  12738. begin
  12739. if taicpu(p).opcode = A_MOVZX then
  12740. begin
  12741. taicpu(p).opsize := S_BL;
  12742. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12743. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12744. end
  12745. else
  12746. taicpu(p).opsize := S_BQ;
  12747. RegUsed := True;
  12748. end;
  12749. {$endif x86_64}
  12750. else
  12751. ;
  12752. end;
  12753. {$ifdef x86_64}
  12754. S_BL:
  12755. case taicpu(hp1).opsize of
  12756. S_LQ:
  12757. begin
  12758. if taicpu(p).opcode = A_MOVZX then
  12759. begin
  12760. taicpu(p).opsize := S_BL;
  12761. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12762. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12763. end
  12764. else
  12765. taicpu(p).opsize := S_BQ;
  12766. RegUsed := True;
  12767. end;
  12768. else
  12769. ;
  12770. end;
  12771. S_WL:
  12772. case taicpu(hp1).opsize of
  12773. S_LQ:
  12774. begin
  12775. if taicpu(p).opcode = A_MOVZX then
  12776. begin
  12777. taicpu(p).opsize := S_WL;
  12778. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12779. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12780. end
  12781. else
  12782. taicpu(p).opsize := S_WQ;
  12783. RegUsed := True;
  12784. end;
  12785. else
  12786. ;
  12787. end;
  12788. {$endif x86_64}
  12789. else
  12790. ;
  12791. end;
  12792. if RegUsed then
  12793. begin
  12794. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  12795. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  12796. RemoveInstruction(hp1);
  12797. Result := True;
  12798. Exit;
  12799. end;
  12800. end;
  12801. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12802. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  12803. GetNextInstruction(hp1, hp2) and
  12804. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  12805. (
  12806. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  12807. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  12808. {$ifdef x86_64}
  12809. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  12810. {$endif x86_64}
  12811. ) and
  12812. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  12813. (
  12814. (
  12815. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  12816. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12817. ) or
  12818. (
  12819. { Only allow the operands in reverse order for TEST instructions }
  12820. (taicpu(hp2).opcode = A_TEST) and
  12821. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12822. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  12823. )
  12824. ) then
  12825. begin
  12826. {
  12827. For example:
  12828. movzbl %al,%eax
  12829. movzbl (ref),%edx
  12830. andl %edx,%eax
  12831. (%edx deallocated)
  12832. Change to:
  12833. andb (ref),%al
  12834. movzbl %al,%eax
  12835. Rules are:
  12836. - First two instructions have the same opcode and opsize
  12837. - First instruction's operands are the same super-register
  12838. - Second instruction operates on a different register
  12839. - Third instruction is AND, OR, XOR or TEST
  12840. - Third instruction's operands are the destination registers of the first two instructions
  12841. - Third instruction writes to the destination register of the first instruction (except with TEST)
  12842. - Second instruction's destination register is deallocated afterwards
  12843. }
  12844. TransferUsedRegs(TmpUsedRegs);
  12845. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12846. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12847. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  12848. begin
  12849. case taicpu(p).opsize of
  12850. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12851. NewSize := S_B;
  12852. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12853. NewSize := S_W;
  12854. {$ifdef x86_64}
  12855. S_LQ:
  12856. NewSize := S_L;
  12857. {$endif x86_64}
  12858. else
  12859. InternalError(2021120301);
  12860. end;
  12861. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  12862. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  12863. taicpu(hp2).opsize := NewSize;
  12864. RemoveInstruction(hp1);
  12865. { With TEST, it's best to keep the MOVX instruction at the top }
  12866. if (taicpu(hp2).opcode <> A_TEST) then
  12867. begin
  12868. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  12869. asml.Remove(p);
  12870. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  12871. asml.InsertAfter(p, hp2);
  12872. p := hp2;
  12873. end
  12874. else
  12875. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  12876. Result := True;
  12877. Exit;
  12878. end;
  12879. end;
  12880. end;
  12881. if taicpu(p).opcode=A_MOVZX then
  12882. begin
  12883. { removes superfluous And's after movzx's }
  12884. if reg_and_hp1_is_instr and
  12885. (taicpu(hp1).opcode = A_AND) and
  12886. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12887. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12888. {$ifdef x86_64}
  12889. { check for implicit extension to 64 bit }
  12890. or
  12891. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12892. (taicpu(hp1).opsize=S_Q) and
  12893. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12894. )
  12895. {$endif x86_64}
  12896. )
  12897. then
  12898. begin
  12899. case taicpu(p).opsize Of
  12900. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12901. if (taicpu(hp1).oper[0]^.val = $ff) then
  12902. begin
  12903. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12904. RemoveInstruction(hp1);
  12905. Result:=true;
  12906. exit;
  12907. end;
  12908. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12909. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12910. begin
  12911. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12912. RemoveInstruction(hp1);
  12913. Result:=true;
  12914. exit;
  12915. end;
  12916. {$ifdef x86_64}
  12917. S_LQ:
  12918. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12919. begin
  12920. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12921. RemoveInstruction(hp1);
  12922. Result:=true;
  12923. exit;
  12924. end;
  12925. {$endif x86_64}
  12926. else
  12927. ;
  12928. end;
  12929. { we cannot get rid of the and, but can we get rid of the movz ?}
  12930. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12931. begin
  12932. case taicpu(p).opsize Of
  12933. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12934. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12935. begin
  12936. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12937. RemoveCurrentP(p,hp1);
  12938. Result:=true;
  12939. exit;
  12940. end;
  12941. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12942. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12943. begin
  12944. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12945. RemoveCurrentP(p,hp1);
  12946. Result:=true;
  12947. exit;
  12948. end;
  12949. {$ifdef x86_64}
  12950. S_LQ:
  12951. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12952. begin
  12953. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12954. RemoveCurrentP(p,hp1);
  12955. Result:=true;
  12956. exit;
  12957. end;
  12958. {$endif x86_64}
  12959. else
  12960. ;
  12961. end;
  12962. end;
  12963. end;
  12964. { changes some movzx constructs to faster synonyms (all examples
  12965. are given with eax/ax, but are also valid for other registers)}
  12966. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12967. begin
  12968. case taicpu(p).opsize of
  12969. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12970. (the machine code is equivalent to movzbl %al,%eax), but the
  12971. code generator still generates that assembler instruction and
  12972. it is silently converted. This should probably be checked.
  12973. [Kit] }
  12974. S_BW:
  12975. begin
  12976. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12977. (
  12978. not IsMOVZXAcceptable
  12979. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12980. or (
  12981. (cs_opt_size in current_settings.optimizerswitches) and
  12982. (taicpu(p).oper[1]^.reg = NR_AX)
  12983. )
  12984. ) then
  12985. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12986. begin
  12987. DebugMsg(SPeepholeOptimization + 'var7',p);
  12988. taicpu(p).opcode := A_AND;
  12989. taicpu(p).changeopsize(S_W);
  12990. taicpu(p).loadConst(0,$ff);
  12991. Result := True;
  12992. end
  12993. else if not IsMOVZXAcceptable and
  12994. GetNextInstruction(p, hp1) and
  12995. (tai(hp1).typ = ait_instruction) and
  12996. (taicpu(hp1).opcode = A_AND) and
  12997. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12998. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12999. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13000. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13001. begin
  13002. DebugMsg(SPeepholeOptimization + 'var8',p);
  13003. taicpu(p).opcode := A_MOV;
  13004. taicpu(p).changeopsize(S_W);
  13005. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13006. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13007. Result := True;
  13008. end;
  13009. end;
  13010. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13011. S_BL:
  13012. if not IsMOVZXAcceptable then
  13013. begin
  13014. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13015. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13016. begin
  13017. DebugMsg(SPeepholeOptimization + 'var9',p);
  13018. taicpu(p).opcode := A_AND;
  13019. taicpu(p).changeopsize(S_L);
  13020. taicpu(p).loadConst(0,$ff);
  13021. Result := True;
  13022. end
  13023. else if GetNextInstruction(p, hp1) and
  13024. (tai(hp1).typ = ait_instruction) and
  13025. (taicpu(hp1).opcode = A_AND) and
  13026. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13027. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13028. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13029. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13030. begin
  13031. DebugMsg(SPeepholeOptimization + 'var10',p);
  13032. taicpu(p).opcode := A_MOV;
  13033. taicpu(p).changeopsize(S_L);
  13034. { do not use R_SUBWHOLE
  13035. as movl %rdx,%eax
  13036. is invalid in assembler PM }
  13037. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13038. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13039. Result := True;
  13040. end;
  13041. end;
  13042. {$endif i8086}
  13043. S_WL:
  13044. if not IsMOVZXAcceptable then
  13045. begin
  13046. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13047. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13048. begin
  13049. DebugMsg(SPeepholeOptimization + 'var11',p);
  13050. taicpu(p).opcode := A_AND;
  13051. taicpu(p).changeopsize(S_L);
  13052. taicpu(p).loadConst(0,$ffff);
  13053. Result := True;
  13054. end
  13055. else if GetNextInstruction(p, hp1) and
  13056. (tai(hp1).typ = ait_instruction) and
  13057. (taicpu(hp1).opcode = A_AND) and
  13058. (taicpu(hp1).oper[0]^.typ = top_const) and
  13059. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13060. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13061. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13062. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13063. begin
  13064. DebugMsg(SPeepholeOptimization + 'var12',p);
  13065. taicpu(p).opcode := A_MOV;
  13066. taicpu(p).changeopsize(S_L);
  13067. { do not use R_SUBWHOLE
  13068. as movl %rdx,%eax
  13069. is invalid in assembler PM }
  13070. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13071. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13072. Result := True;
  13073. end;
  13074. end;
  13075. else
  13076. InternalError(2017050705);
  13077. end;
  13078. end
  13079. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13080. begin
  13081. if GetNextInstruction(p, hp1) and
  13082. (tai(hp1).typ = ait_instruction) and
  13083. (taicpu(hp1).opcode = A_AND) and
  13084. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13085. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13086. begin
  13087. //taicpu(p).opcode := A_MOV;
  13088. case taicpu(p).opsize Of
  13089. S_BL:
  13090. begin
  13091. DebugMsg(SPeepholeOptimization + 'var13',p);
  13092. taicpu(hp1).changeopsize(S_L);
  13093. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13094. end;
  13095. S_WL:
  13096. begin
  13097. DebugMsg(SPeepholeOptimization + 'var14',p);
  13098. taicpu(hp1).changeopsize(S_L);
  13099. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13100. end;
  13101. S_BW:
  13102. begin
  13103. DebugMsg(SPeepholeOptimization + 'var15',p);
  13104. taicpu(hp1).changeopsize(S_W);
  13105. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13106. end;
  13107. else
  13108. Internalerror(2017050704)
  13109. end;
  13110. Result := True;
  13111. end;
  13112. end;
  13113. end;
  13114. end;
  13115. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13116. var
  13117. hp1, hp2 : tai;
  13118. MaskLength : Cardinal;
  13119. MaskedBits : TCgInt;
  13120. ActiveReg : TRegister;
  13121. begin
  13122. Result:=false;
  13123. { There are no optimisations for reference targets }
  13124. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13125. Exit;
  13126. while GetNextInstruction(p, hp1) and
  13127. (hp1.typ = ait_instruction) do
  13128. begin
  13129. if (taicpu(p).oper[0]^.typ = top_const) then
  13130. begin
  13131. case taicpu(hp1).opcode of
  13132. A_AND:
  13133. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13134. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13135. { the second register must contain the first one, so compare their subreg types }
  13136. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13137. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13138. { change
  13139. and const1, reg
  13140. and const2, reg
  13141. to
  13142. and (const1 and const2), reg
  13143. }
  13144. begin
  13145. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13146. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13147. RemoveCurrentP(p, hp1);
  13148. Result:=true;
  13149. exit;
  13150. end;
  13151. A_CMP:
  13152. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13153. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13154. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13155. { Just check that the condition on the next instruction is compatible }
  13156. GetNextInstruction(hp1, hp2) and
  13157. (hp2.typ = ait_instruction) and
  13158. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13159. then
  13160. { change
  13161. and 2^n, reg
  13162. cmp 2^n, reg
  13163. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13164. to
  13165. and 2^n, reg
  13166. test reg, reg
  13167. j(~c) / set(~c) / cmov(~c)
  13168. }
  13169. begin
  13170. { Keep TEST instruction in, rather than remove it, because
  13171. it may trigger other optimisations such as MovAndTest2Test }
  13172. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13173. taicpu(hp1).opcode := A_TEST;
  13174. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13175. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13176. Result := True;
  13177. Exit;
  13178. end
  13179. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13180. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13181. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13182. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13183. { change
  13184. and $ff/$ff/$ffff, reg
  13185. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13186. dealloc reg
  13187. to
  13188. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13189. }
  13190. begin
  13191. TransferUsedRegs(TmpUsedRegs);
  13192. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13193. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13194. begin
  13195. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13196. case taicpu(p).oper[0]^.val of
  13197. $ff:
  13198. begin
  13199. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13200. taicpu(hp1).opsize:=S_B;
  13201. end;
  13202. $ffff:
  13203. begin
  13204. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13205. taicpu(hp1).opsize:=S_W;
  13206. end;
  13207. $ffffffff:
  13208. begin
  13209. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13210. taicpu(hp1).opsize:=S_L;
  13211. end;
  13212. else
  13213. Internalerror(2023030401);
  13214. end;
  13215. RemoveCurrentP(p);
  13216. Result := True;
  13217. Exit;
  13218. end;
  13219. end;
  13220. A_MOVZX:
  13221. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13222. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13223. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13224. (
  13225. (
  13226. (taicpu(p).opsize=S_W) and
  13227. (taicpu(hp1).opsize=S_BW)
  13228. ) or
  13229. (
  13230. (taicpu(p).opsize=S_L) and
  13231. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13232. )
  13233. {$ifdef x86_64}
  13234. or
  13235. (
  13236. (taicpu(p).opsize=S_Q) and
  13237. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13238. )
  13239. {$endif x86_64}
  13240. ) then
  13241. begin
  13242. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13243. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13244. ) or
  13245. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13246. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13247. then
  13248. begin
  13249. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13250. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13251. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13252. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13253. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13254. }
  13255. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13256. RemoveInstruction(hp1);
  13257. { See if there are other optimisations possible }
  13258. Continue;
  13259. end;
  13260. end;
  13261. A_SHL:
  13262. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13263. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13264. begin
  13265. {$ifopt R+}
  13266. {$define RANGE_WAS_ON}
  13267. {$R-}
  13268. {$endif}
  13269. { get length of potential and mask }
  13270. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13271. { really a mask? }
  13272. {$ifdef RANGE_WAS_ON}
  13273. {$R+}
  13274. {$endif}
  13275. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13276. { unmasked part shifted out? }
  13277. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13278. begin
  13279. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13280. RemoveCurrentP(p, hp1);
  13281. Result:=true;
  13282. exit;
  13283. end;
  13284. end;
  13285. A_SHR:
  13286. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13287. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13288. (taicpu(hp1).oper[0]^.val <= 63) then
  13289. begin
  13290. { Does SHR combined with the AND cover all the bits?
  13291. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13292. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13293. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13294. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13295. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13296. begin
  13297. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13298. RemoveCurrentP(p, hp1);
  13299. Result := True;
  13300. Exit;
  13301. end;
  13302. end;
  13303. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13304. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13305. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13306. begin
  13307. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13308. (
  13309. (
  13310. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13311. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  13312. ) or (
  13313. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13314. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  13315. {$ifdef x86_64}
  13316. ) or (
  13317. (taicpu(hp1).opsize = S_LQ) and
  13318. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  13319. {$endif x86_64}
  13320. )
  13321. ) then
  13322. begin
  13323. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  13324. begin
  13325. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  13326. RemoveInstruction(hp1);
  13327. { See if there are other optimisations possible }
  13328. Continue;
  13329. end;
  13330. { The super-registers are the same though.
  13331. Note that this change by itself doesn't improve
  13332. code speed, but it opens up other optimisations. }
  13333. {$ifdef x86_64}
  13334. { Convert 64-bit register to 32-bit }
  13335. case taicpu(hp1).opsize of
  13336. S_BQ:
  13337. begin
  13338. taicpu(hp1).opsize := S_BL;
  13339. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13340. end;
  13341. S_WQ:
  13342. begin
  13343. taicpu(hp1).opsize := S_WL;
  13344. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13345. end
  13346. else
  13347. ;
  13348. end;
  13349. {$endif x86_64}
  13350. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  13351. taicpu(hp1).opcode := A_MOVZX;
  13352. { See if there are other optimisations possible }
  13353. Continue;
  13354. end;
  13355. end;
  13356. else
  13357. ;
  13358. end;
  13359. end
  13360. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  13361. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13362. begin
  13363. {$ifdef x86_64}
  13364. if (taicpu(p).opsize = S_Q) then
  13365. begin
  13366. { Never necessary }
  13367. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  13368. RemoveCurrentP(p, hp1);
  13369. Result := True;
  13370. Exit;
  13371. end;
  13372. {$endif x86_64}
  13373. { Forward check to determine necessity of and %reg,%reg }
  13374. TransferUsedRegs(TmpUsedRegs);
  13375. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13376. { Saves on a bunch of dereferences }
  13377. ActiveReg := taicpu(p).oper[1]^.reg;
  13378. case taicpu(hp1).opcode of
  13379. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13380. if (
  13381. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13382. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13383. ) and
  13384. (
  13385. (taicpu(hp1).opcode <> A_MOV) or
  13386. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  13387. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  13388. ) and
  13389. not (
  13390. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  13391. (taicpu(hp1).opcode = A_MOV) and
  13392. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  13393. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  13394. ) and
  13395. (
  13396. (
  13397. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13398. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  13399. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  13400. ) or
  13401. (
  13402. {$ifdef x86_64}
  13403. (
  13404. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  13405. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  13406. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  13407. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  13408. ) and
  13409. {$endif x86_64}
  13410. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  13411. )
  13412. ) then
  13413. begin
  13414. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  13415. RemoveCurrentP(p, hp1);
  13416. Result := True;
  13417. Exit;
  13418. end;
  13419. A_ADD,
  13420. A_AND,
  13421. A_BSF,
  13422. A_BSR,
  13423. A_BTC,
  13424. A_BTR,
  13425. A_BTS,
  13426. A_OR,
  13427. A_SUB,
  13428. A_XOR:
  13429. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  13430. if (
  13431. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13432. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13433. ) and
  13434. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  13435. begin
  13436. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  13437. RemoveCurrentP(p, hp1);
  13438. Result := True;
  13439. Exit;
  13440. end;
  13441. A_CMP,
  13442. A_TEST:
  13443. if (
  13444. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13445. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13446. ) and
  13447. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  13448. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  13449. begin
  13450. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  13451. RemoveCurrentP(p, hp1);
  13452. Result := True;
  13453. Exit;
  13454. end;
  13455. A_BSWAP,
  13456. A_NEG,
  13457. A_NOT:
  13458. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  13459. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  13460. begin
  13461. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  13462. RemoveCurrentP(p, hp1);
  13463. Result := True;
  13464. Exit;
  13465. end;
  13466. else
  13467. ;
  13468. end;
  13469. end;
  13470. if (taicpu(hp1).is_jmp) and
  13471. (taicpu(hp1).opcode<>A_JMP) and
  13472. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  13473. begin
  13474. { change
  13475. and x, reg
  13476. jxx
  13477. to
  13478. test x, reg
  13479. jxx
  13480. if reg is deallocated before the
  13481. jump, but only if it's a conditional jump (PFV)
  13482. }
  13483. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  13484. taicpu(p).opcode := A_TEST;
  13485. Exit;
  13486. end;
  13487. Break;
  13488. end;
  13489. { Lone AND tests }
  13490. if (taicpu(p).oper[0]^.typ = top_const) then
  13491. begin
  13492. {
  13493. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  13494. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  13495. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  13496. }
  13497. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  13498. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  13499. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  13500. begin
  13501. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  13502. if taicpu(p).opsize = S_L then
  13503. begin
  13504. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  13505. Result := True;
  13506. end;
  13507. end;
  13508. end;
  13509. { Backward check to determine necessity of and %reg,%reg }
  13510. if (taicpu(p).oper[0]^.typ = top_reg) and
  13511. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13512. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13513. GetLastInstruction(p, hp2) and
  13514. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  13515. { Check size of adjacent instruction to determine if the AND is
  13516. effectively a null operation }
  13517. (
  13518. (taicpu(p).opsize = taicpu(hp2).opsize) or
  13519. { Note: Don't include S_Q }
  13520. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  13521. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  13522. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  13523. ) then
  13524. begin
  13525. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  13526. { If GetNextInstruction returned False, hp1 will be nil }
  13527. RemoveCurrentP(p, hp1);
  13528. Result := True;
  13529. Exit;
  13530. end;
  13531. end;
  13532. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  13533. var
  13534. hp1, hp2: tai;
  13535. NewRef: TReference;
  13536. Distance: Cardinal;
  13537. TempTracking: TAllUsedRegs;
  13538. { This entire nested function is used in an if-statement below, but we
  13539. want to avoid all the used reg transfers and GetNextInstruction calls
  13540. until we really have to check }
  13541. function MemRegisterNotUsedLater: Boolean; inline;
  13542. var
  13543. hp2: tai;
  13544. begin
  13545. TransferUsedRegs(TmpUsedRegs);
  13546. hp2 := p;
  13547. repeat
  13548. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13549. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13550. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  13551. end;
  13552. begin
  13553. Result := False;
  13554. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13555. (taicpu(p).oper[1]^.typ = top_reg) then
  13556. begin
  13557. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13558. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13559. (hp1.typ <> ait_instruction) or
  13560. not
  13561. (
  13562. (cs_opt_level3 in current_settings.optimizerswitches) or
  13563. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13564. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13565. ) then
  13566. Exit;
  13567. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13568. addq $x, %rax
  13569. movq %rax, %rdx
  13570. sarq $63, %rdx
  13571. (%rax still in use)
  13572. ...letting OptPass2ADD run its course (and without -Os) will produce:
  13573. leaq $x(%rax),%rdx
  13574. addq $x, %rax
  13575. sarq $63, %rdx
  13576. ...which is okay since it breaks the dependency chain between
  13577. addq and movq, but if OptPass2MOV is called first:
  13578. addq $x, %rax
  13579. cqto
  13580. ...which is better in all ways, taking only 2 cycles to execute
  13581. and much smaller in code size.
  13582. }
  13583. { The extra register tracking is quite strenuous }
  13584. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13585. MatchInstruction(hp1, A_MOV, []) then
  13586. begin
  13587. { Update the register tracking to the MOV instruction }
  13588. CopyUsedRegs(TempTracking);
  13589. hp2 := p;
  13590. repeat
  13591. UpdateUsedRegs(tai(hp2.Next));
  13592. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13593. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13594. OptPass2ADD get called again }
  13595. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13596. begin
  13597. { Reset the tracking to the current instruction }
  13598. RestoreUsedRegs(TempTracking);
  13599. ReleaseUsedRegs(TempTracking);
  13600. Result := True;
  13601. Exit;
  13602. end;
  13603. { Reset the tracking to the current instruction }
  13604. RestoreUsedRegs(TempTracking);
  13605. ReleaseUsedRegs(TempTracking);
  13606. { If OptPass2MOV returned True, we don't need to set Result to
  13607. True if hp1 didn't change because the ADD instruction didn't
  13608. get modified and we'll be evaluating hp1 again when the
  13609. peephole optimizer reaches it }
  13610. end;
  13611. { Change:
  13612. add %reg2,%reg1
  13613. (%reg2 not modified in between)
  13614. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  13615. To:
  13616. mov/s/z #(%reg1,%reg2),%reg1
  13617. }
  13618. if (taicpu(p).oper[0]^.typ = top_reg) and
  13619. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  13620. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  13621. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  13622. (
  13623. (
  13624. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  13625. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  13626. { r/esp cannot be an index }
  13627. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  13628. ) or (
  13629. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  13630. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  13631. )
  13632. ) and (
  13633. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  13634. (
  13635. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  13636. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13637. MemRegisterNotUsedLater
  13638. )
  13639. ) then
  13640. begin
  13641. if (
  13642. { Instructions are guaranteed to be adjacent on -O2 and under }
  13643. (cs_opt_level3 in current_settings.optimizerswitches) and
  13644. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  13645. ) then
  13646. begin
  13647. { If the other register is used in between, move the MOV
  13648. instruction to right after the ADD instruction so a
  13649. saving can still be made }
  13650. Asml.Remove(hp1);
  13651. Asml.InsertAfter(hp1, p);
  13652. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13653. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13654. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  13655. RemoveCurrentp(p, hp1);
  13656. end
  13657. else
  13658. begin
  13659. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  13660. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13661. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13662. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  13663. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13664. { hp1 may not be the immediate next instruction under -O3 }
  13665. RemoveCurrentp(p)
  13666. else
  13667. RemoveCurrentp(p, hp1);
  13668. end;
  13669. Result := True;
  13670. Exit;
  13671. end;
  13672. { Change:
  13673. addl/q $x,%reg1
  13674. movl/q %reg1,%reg2
  13675. To:
  13676. leal/q $x(%reg1),%reg2
  13677. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13678. Breaks the dependency chain.
  13679. }
  13680. if (taicpu(p).oper[0]^.typ = top_const) and
  13681. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13682. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13683. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13684. (
  13685. { Instructions are guaranteed to be adjacent on -O2 and under }
  13686. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13687. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13688. ) then
  13689. begin
  13690. TransferUsedRegs(TmpUsedRegs);
  13691. hp2 := p;
  13692. repeat
  13693. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13694. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13695. if (
  13696. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  13697. not (cs_opt_size in current_settings.optimizerswitches) or
  13698. (
  13699. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13700. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13701. )
  13702. ) then
  13703. begin
  13704. { Change the MOV instruction to a LEA instruction, and update the
  13705. first operand }
  13706. reference_reset(NewRef, 1, []);
  13707. NewRef.base := taicpu(p).oper[1]^.reg;
  13708. NewRef.scalefactor := 1;
  13709. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  13710. taicpu(hp1).opcode := A_LEA;
  13711. taicpu(hp1).loadref(0, NewRef);
  13712. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13713. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13714. begin
  13715. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13716. { Move what is now the LEA instruction to before the ADD instruction }
  13717. Asml.Remove(hp1);
  13718. Asml.InsertBefore(hp1, p);
  13719. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13720. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  13721. p := hp1;
  13722. end
  13723. else
  13724. begin
  13725. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13726. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  13727. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13728. { hp1 may not be the immediate next instruction under -O3 }
  13729. RemoveCurrentp(p)
  13730. else
  13731. RemoveCurrentp(p, hp1);
  13732. end;
  13733. Result := True;
  13734. end;
  13735. end;
  13736. end;
  13737. end;
  13738. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  13739. var
  13740. SubReg: TSubRegister;
  13741. hp1, hp2: tai;
  13742. CallJmp: Boolean;
  13743. begin
  13744. Result := False;
  13745. CallJmp := False;
  13746. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  13747. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13748. with taicpu(p).oper[0]^.ref^ do
  13749. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  13750. if (offset = 0) then
  13751. begin
  13752. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  13753. begin
  13754. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  13755. taicpu(p).opcode := A_ADD;
  13756. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  13757. Result := True;
  13758. end
  13759. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  13760. begin
  13761. if (base <> NR_NO) then
  13762. begin
  13763. if (scalefactor <= 1) then
  13764. begin
  13765. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  13766. taicpu(p).opcode := A_ADD;
  13767. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  13768. Result := True;
  13769. end;
  13770. end
  13771. else
  13772. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  13773. if (scalefactor in [2, 4, 8]) then
  13774. begin
  13775. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  13776. taicpu(p).loadconst(0, BsrByte(scalefactor));
  13777. taicpu(p).opcode := A_SHL;
  13778. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  13779. Result := True;
  13780. end;
  13781. end;
  13782. end
  13783. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  13784. lot of latency, so break off the offset if %reg3 is used soon
  13785. afterwards }
  13786. else if not (cs_opt_size in current_settings.optimizerswitches) and
  13787. { If 3-component addresses don't have additional latency, don't
  13788. perform this optimisation }
  13789. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  13790. GetNextInstruction(p, hp1) and
  13791. (
  13792. (
  13793. { Permit jumps and calls since they have a larger degree of overhead }
  13794. (
  13795. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  13796. (
  13797. { ... unless the register specifies the location }
  13798. (taicpu(hp1).ops > 0) and
  13799. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  13800. )
  13801. ) and
  13802. (
  13803. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  13804. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13805. )
  13806. )
  13807. or
  13808. (
  13809. { Check up to two instructions ahead }
  13810. GetNextInstruction(hp1, hp2) and
  13811. (
  13812. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  13813. (
  13814. { Same as above }
  13815. (taicpu(hp2).ops > 0) and
  13816. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  13817. )
  13818. ) and
  13819. (
  13820. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  13821. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  13822. )
  13823. )
  13824. ) then
  13825. begin
  13826. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  13827. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  13828. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  13829. offset := 0;
  13830. if Assigned(symbol) or Assigned(relsymbol) then
  13831. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  13832. else
  13833. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  13834. { Inserting before the next instruction rather than after the
  13835. current instruction gives more accurate register tracking }
  13836. asml.InsertBefore(hp2, hp1);
  13837. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  13838. Result := True;
  13839. end;
  13840. end;
  13841. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  13842. var
  13843. hp1, hp2: tai;
  13844. NewRef: TReference;
  13845. Distance: Cardinal;
  13846. TempTracking: TAllUsedRegs;
  13847. begin
  13848. Result := False;
  13849. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13850. MatchOpType(taicpu(p),top_const,top_reg) then
  13851. begin
  13852. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13853. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13854. (hp1.typ <> ait_instruction) or
  13855. not
  13856. (
  13857. (cs_opt_level3 in current_settings.optimizerswitches) or
  13858. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13859. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13860. ) then
  13861. Exit;
  13862. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13863. subq $x, %rax
  13864. movq %rax, %rdx
  13865. sarq $63, %rdx
  13866. (%rax still in use)
  13867. ...letting OptPass2SUB run its course (and without -Os) will produce:
  13868. leaq $-x(%rax),%rdx
  13869. movq $x, %rax
  13870. sarq $63, %rdx
  13871. ...which is okay since it breaks the dependency chain between
  13872. subq and movq, but if OptPass2MOV is called first:
  13873. subq $x, %rax
  13874. cqto
  13875. ...which is better in all ways, taking only 2 cycles to execute
  13876. and much smaller in code size.
  13877. }
  13878. { The extra register tracking is quite strenuous }
  13879. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13880. MatchInstruction(hp1, A_MOV, []) then
  13881. begin
  13882. { Update the register tracking to the MOV instruction }
  13883. CopyUsedRegs(TempTracking);
  13884. hp2 := p;
  13885. repeat
  13886. UpdateUsedRegs(tai(hp2.Next));
  13887. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13888. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13889. OptPass2SUB get called again }
  13890. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13891. begin
  13892. { Reset the tracking to the current instruction }
  13893. RestoreUsedRegs(TempTracking);
  13894. ReleaseUsedRegs(TempTracking);
  13895. Result := True;
  13896. Exit;
  13897. end;
  13898. { Reset the tracking to the current instruction }
  13899. RestoreUsedRegs(TempTracking);
  13900. ReleaseUsedRegs(TempTracking);
  13901. { If OptPass2MOV returned True, we don't need to set Result to
  13902. True if hp1 didn't change because the SUB instruction didn't
  13903. get modified and we'll be evaluating hp1 again when the
  13904. peephole optimizer reaches it }
  13905. end;
  13906. { Change:
  13907. subl/q $x,%reg1
  13908. movl/q %reg1,%reg2
  13909. To:
  13910. leal/q $-x(%reg1),%reg2
  13911. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13912. Breaks the dependency chain and potentially permits the removal of
  13913. a CMP instruction if one follows.
  13914. }
  13915. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13916. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13917. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13918. (
  13919. { Instructions are guaranteed to be adjacent on -O2 and under }
  13920. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13921. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13922. ) then
  13923. begin
  13924. TransferUsedRegs(TmpUsedRegs);
  13925. hp2 := p;
  13926. repeat
  13927. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13928. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13929. if (
  13930. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  13931. not (cs_opt_size in current_settings.optimizerswitches) or
  13932. (
  13933. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13934. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13935. )
  13936. ) then
  13937. begin
  13938. { Change the MOV instruction to a LEA instruction, and update the
  13939. first operand }
  13940. reference_reset(NewRef, 1, []);
  13941. NewRef.base := taicpu(p).oper[1]^.reg;
  13942. NewRef.scalefactor := 1;
  13943. NewRef.offset := -taicpu(p).oper[0]^.val;
  13944. taicpu(hp1).opcode := A_LEA;
  13945. taicpu(hp1).loadref(0, NewRef);
  13946. TransferUsedRegs(TmpUsedRegs);
  13947. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13948. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13949. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13950. begin
  13951. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13952. { Move what is now the LEA instruction to before the SUB instruction }
  13953. Asml.Remove(hp1);
  13954. Asml.InsertBefore(hp1, p);
  13955. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13956. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  13957. p := hp1;
  13958. end
  13959. else
  13960. begin
  13961. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13962. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  13963. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13964. { hp1 may not be the immediate next instruction under -O3 }
  13965. RemoveCurrentp(p)
  13966. else
  13967. RemoveCurrentp(p, hp1);
  13968. end;
  13969. Result := True;
  13970. end;
  13971. end;
  13972. end;
  13973. end;
  13974. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  13975. begin
  13976. { we can skip all instructions not messing with the stack pointer }
  13977. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  13978. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  13979. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  13980. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  13981. ({(taicpu(hp1).ops=0) or }
  13982. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  13983. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  13984. ) and }
  13985. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  13986. )
  13987. ) do
  13988. GetNextInstruction(hp1,hp1);
  13989. Result:=assigned(hp1);
  13990. end;
  13991. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  13992. var
  13993. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  13994. begin
  13995. Result:=false;
  13996. hp5:=nil;
  13997. hp6:=nil;
  13998. hp7:=nil;
  13999. hp8:=nil;
  14000. { replace
  14001. leal(q) x(<stackpointer>),<stackpointer>
  14002. <optional .seh_stackalloc ...>
  14003. <optional .seh_endprologue ...>
  14004. call procname
  14005. <optional NOP>
  14006. leal(q) -x(<stackpointer>),<stackpointer>
  14007. <optional VZEROUPPER>
  14008. ret
  14009. by
  14010. jmp procname
  14011. but do it only on level 4 because it destroys stack back traces
  14012. }
  14013. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14014. MatchOpType(taicpu(p),top_ref,top_reg) and
  14015. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14016. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14017. { the -8, -24, -40 are not required, but bail out early if possible,
  14018. higher values are unlikely }
  14019. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14020. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14021. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14022. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14023. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14024. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14025. GetNextInstruction(p, hp1) and
  14026. { Take a copy of hp1 }
  14027. SetAndTest(hp1, hp4) and
  14028. { trick to skip label }
  14029. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14030. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14031. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14032. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14033. SkipSimpleInstructions(hp1) and
  14034. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14035. GetNextInstruction(hp1, hp2) and
  14036. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14037. { skip nop instruction on win64 }
  14038. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14039. SetAndTest(hp2,hp6) and
  14040. GetNextInstruction(hp2,hp2) and
  14041. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14042. ) and
  14043. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14044. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14045. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14046. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14047. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14048. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14049. { Segment register will be NR_NO }
  14050. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14051. GetNextInstruction(hp2, hp3) and
  14052. { trick to skip label }
  14053. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14054. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14055. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14056. SetAndTest(hp3,hp5) and
  14057. GetNextInstruction(hp3,hp3) and
  14058. MatchInstruction(hp3,A_RET,[S_NO])
  14059. )
  14060. ) and
  14061. (taicpu(hp3).ops=0) then
  14062. begin
  14063. taicpu(hp1).opcode := A_JMP;
  14064. taicpu(hp1).is_jmp := true;
  14065. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14066. { search for the stackalloc directive and remove it }
  14067. hp7:=tai(p.next);
  14068. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14069. begin
  14070. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14071. begin
  14072. { sanity check }
  14073. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14074. Internalerror(2024012201);
  14075. hp8:=tai(hp7.next);
  14076. RemoveInstruction(tai(hp7));
  14077. hp7:=hp8;
  14078. break;
  14079. end
  14080. else
  14081. hp7:=tai(hp7.next);
  14082. end;
  14083. RemoveCurrentP(p, hp4);
  14084. RemoveInstruction(hp2);
  14085. RemoveInstruction(hp3);
  14086. { if there is a vzeroupper instruction then move it before the jmp }
  14087. if Assigned(hp5) then
  14088. begin
  14089. AsmL.Remove(hp5);
  14090. ASmL.InsertBefore(hp5,hp1)
  14091. end;
  14092. { remove nop on win64 }
  14093. if Assigned(hp6) then
  14094. RemoveInstruction(hp6);
  14095. Result:=true;
  14096. end;
  14097. end;
  14098. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14099. {$ifdef x86_64}
  14100. var
  14101. hp1, hp2, hp3, hp4, hp5: tai;
  14102. {$endif x86_64}
  14103. begin
  14104. Result:=false;
  14105. {$ifdef x86_64}
  14106. hp5:=nil;
  14107. { replace
  14108. push %rax
  14109. call procname
  14110. pop %rcx
  14111. ret
  14112. by
  14113. jmp procname
  14114. but do it only on level 4 because it destroys stack back traces
  14115. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14116. for all supported calling conventions
  14117. }
  14118. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14119. MatchOpType(taicpu(p),top_reg) and
  14120. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14121. GetNextInstruction(p, hp1) and
  14122. { Take a copy of hp1 }
  14123. SetAndTest(hp1, hp4) and
  14124. { trick to skip label }
  14125. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14126. SkipSimpleInstructions(hp1) and
  14127. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14128. GetNextInstruction(hp1, hp2) and
  14129. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14130. MatchOpType(taicpu(hp2),top_reg) and
  14131. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14132. GetNextInstruction(hp2, hp3) and
  14133. { trick to skip label }
  14134. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14135. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14136. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14137. SetAndTest(hp3,hp5) and
  14138. GetNextInstruction(hp3,hp3) and
  14139. MatchInstruction(hp3,A_RET,[S_NO])
  14140. )
  14141. ) and
  14142. (taicpu(hp3).ops=0) then
  14143. begin
  14144. taicpu(hp1).opcode := A_JMP;
  14145. taicpu(hp1).is_jmp := true;
  14146. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14147. RemoveCurrentP(p, hp4);
  14148. RemoveInstruction(hp2);
  14149. RemoveInstruction(hp3);
  14150. if Assigned(hp5) then
  14151. begin
  14152. AsmL.Remove(hp5);
  14153. ASmL.InsertBefore(hp5,hp1)
  14154. end;
  14155. Result:=true;
  14156. end;
  14157. {$endif x86_64}
  14158. end;
  14159. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14160. var
  14161. Value, RegName: string;
  14162. hp1: tai;
  14163. begin
  14164. Result:=false;
  14165. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14166. begin
  14167. case taicpu(p).oper[0]^.val of
  14168. 0:
  14169. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14170. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14171. (
  14172. { See if we can still convert the instruction }
  14173. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14174. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14175. ) then
  14176. begin
  14177. { change "mov $0,%reg" into "xor %reg,%reg" }
  14178. taicpu(p).opcode := A_XOR;
  14179. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14180. Result := True;
  14181. {$ifdef x86_64}
  14182. end
  14183. else if (taicpu(p).opsize = S_Q) then
  14184. begin
  14185. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14186. { The actual optimization }
  14187. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14188. taicpu(p).changeopsize(S_L);
  14189. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14190. Result := True;
  14191. end;
  14192. $1..$FFFFFFFF:
  14193. begin
  14194. { Code size reduction by J. Gareth "Kit" Moreton }
  14195. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14196. case taicpu(p).opsize of
  14197. S_Q:
  14198. begin
  14199. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14200. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14201. { The actual optimization }
  14202. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14203. taicpu(p).changeopsize(S_L);
  14204. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14205. Result := True;
  14206. end;
  14207. else
  14208. { Do nothing };
  14209. end;
  14210. {$endif x86_64}
  14211. end;
  14212. -1:
  14213. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14214. if (cs_opt_size in current_settings.optimizerswitches) and
  14215. (taicpu(p).opsize <> S_B) and
  14216. (
  14217. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14218. (
  14219. { See if we can still convert the instruction }
  14220. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14221. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14222. )
  14223. ) then
  14224. begin
  14225. { change "mov $-1,%reg" into "or $-1,%reg" }
  14226. { NOTES:
  14227. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14228. - This operation creates a false dependency on the register, so only do it when optimising for size
  14229. - 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
  14230. }
  14231. taicpu(p).opcode := A_OR;
  14232. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14233. Result := True;
  14234. end;
  14235. else
  14236. { Do nothing };
  14237. end;
  14238. end;
  14239. end;
  14240. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14241. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14242. begin
  14243. Result := False;
  14244. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14245. Exit;
  14246. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14247. so don't bother optimising }
  14248. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14249. Exit;
  14250. if (taicpu(p).oper[0]^.typ <> top_const) or
  14251. { If the value can fit into an 8-bit signed integer, a smaller
  14252. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14253. falls within this range }
  14254. (
  14255. (taicpu(p).oper[0]^.val > -128) and
  14256. (taicpu(p).oper[0]^.val <= 127)
  14257. ) then
  14258. Exit;
  14259. { If we're optimising for size, this is acceptable }
  14260. if (cs_opt_size in current_settings.optimizerswitches) then
  14261. Exit(True);
  14262. if (taicpu(p).oper[1]^.typ = top_reg) and
  14263. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14264. Exit(True);
  14265. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14266. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14267. Exit(True);
  14268. end;
  14269. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14270. var
  14271. hp1: tai;
  14272. Value: TCGInt;
  14273. begin
  14274. Result := False;
  14275. if MatchOpType(taicpu(p), top_const, top_reg) then
  14276. begin
  14277. { Detect:
  14278. andw x, %ax (0 <= x < $8000)
  14279. ...
  14280. movzwl %ax,%eax
  14281. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14282. }
  14283. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  14284. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  14285. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  14286. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  14287. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  14288. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  14289. begin
  14290. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  14291. taicpu(hp1).opcode := A_CWDE;
  14292. taicpu(hp1).clearop(0);
  14293. taicpu(hp1).clearop(1);
  14294. taicpu(hp1).ops := 0;
  14295. { A change was made, but not with p, so don't set Result, but
  14296. notify the compiler that a change was made }
  14297. Include(OptsToCheck, aoc_ForceNewIteration);
  14298. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  14299. end;
  14300. end;
  14301. { If "not x" is a power of 2 (popcnt = 1), change:
  14302. and $x, %reg/ref
  14303. To:
  14304. btr lb(x), %reg/ref
  14305. }
  14306. if IsBTXAcceptable(p) and
  14307. (
  14308. { Make sure a TEST doesn't follow that plays with the register }
  14309. not GetNextInstruction(p, hp1) or
  14310. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  14311. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  14312. ) then
  14313. begin
  14314. {$push}{$R-}{$Q-}
  14315. { Value is a sign-extended 32-bit integer - just correct it
  14316. if it's represented as an unsigned value. Also, IsBTXAcceptable
  14317. checks to see if this operand is an immediate. }
  14318. Value := not taicpu(p).oper[0]^.val;
  14319. {$pop}
  14320. {$ifdef x86_64}
  14321. if taicpu(p).opsize = S_L then
  14322. {$endif x86_64}
  14323. Value := Value and $FFFFFFFF;
  14324. if (PopCnt(QWord(Value)) = 1) then
  14325. begin
  14326. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  14327. taicpu(p).opcode := A_BTR;
  14328. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  14329. Result := True;
  14330. Exit;
  14331. end;
  14332. end;
  14333. end;
  14334. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  14335. begin
  14336. Result := False;
  14337. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  14338. Exit;
  14339. { Convert:
  14340. movswl %ax,%eax -> cwtl
  14341. movslq %eax,%rax -> cdqe
  14342. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  14343. refer to the same opcode and depends only on the assembler's
  14344. current operand-size attribute. [Kit]
  14345. }
  14346. with taicpu(p) do
  14347. case opsize of
  14348. S_WL:
  14349. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  14350. begin
  14351. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  14352. opcode := A_CWDE;
  14353. clearop(0);
  14354. clearop(1);
  14355. ops := 0;
  14356. Result := True;
  14357. end;
  14358. {$ifdef x86_64}
  14359. S_LQ:
  14360. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  14361. begin
  14362. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  14363. opcode := A_CDQE;
  14364. clearop(0);
  14365. clearop(1);
  14366. ops := 0;
  14367. Result := True;
  14368. end;
  14369. {$endif x86_64}
  14370. else
  14371. ;
  14372. end;
  14373. end;
  14374. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  14375. var
  14376. hp1, hp2: tai;
  14377. IdentityMask, Shift: TCGInt;
  14378. LimitSize: Topsize;
  14379. DoNotMerge: Boolean;
  14380. begin
  14381. Result := False;
  14382. { All these optimisations work on "shr const,%reg" }
  14383. if not MatchOpType(taicpu(p), top_const, top_reg) then
  14384. Exit;
  14385. DoNotMerge := False;
  14386. Shift := taicpu(p).oper[0]^.val;
  14387. LimitSize := taicpu(p).opsize;
  14388. hp1 := p;
  14389. repeat
  14390. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  14391. Break;
  14392. { Detect:
  14393. shr x, %reg
  14394. and y, %reg
  14395. If and y, %reg doesn't actually change the value of %reg (e.g. with
  14396. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  14397. }
  14398. case taicpu(hp1).opcode of
  14399. A_AND:
  14400. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  14401. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14402. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14403. begin
  14404. { Make sure the FLAGS register isn't in use }
  14405. TransferUsedRegs(TmpUsedRegs);
  14406. hp2 := p;
  14407. repeat
  14408. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14409. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14410. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14411. begin
  14412. { Generate the identity mask }
  14413. case taicpu(p).opsize of
  14414. S_B:
  14415. IdentityMask := $FF shr Shift;
  14416. S_W:
  14417. IdentityMask := $FFFF shr Shift;
  14418. S_L:
  14419. IdentityMask := $FFFFFFFF shr Shift;
  14420. {$ifdef x86_64}
  14421. S_Q:
  14422. { We need to force the operands to be unsigned 64-bit
  14423. integers otherwise the wrong value is generated }
  14424. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  14425. {$endif x86_64}
  14426. else
  14427. InternalError(2022081501);
  14428. end;
  14429. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  14430. begin
  14431. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  14432. { All the possible 1 bits are covered, so we can remove the AND }
  14433. hp2 := tai(hp1.Previous);
  14434. RemoveInstruction(hp1);
  14435. { p wasn't actually changed, so don't set Result to True,
  14436. but a change was nonetheless made elsewhere }
  14437. Include(OptsToCheck, aoc_ForceNewIteration);
  14438. { Do another pass in case other AND or MOVZX instructions
  14439. follow }
  14440. hp1 := hp2;
  14441. Continue;
  14442. end;
  14443. end;
  14444. end;
  14445. A_TEST, A_CMP, A_Jcc:
  14446. { Skip over conditional jumps and relevant comparisons }
  14447. Continue;
  14448. A_MOVZX:
  14449. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14450. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  14451. begin
  14452. { Since the original register is being read as is, subsequent
  14453. SHRs must not be merged at this point }
  14454. DoNotMerge := True;
  14455. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  14456. begin
  14457. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14458. begin
  14459. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  14460. { All the possible 1 bits are covered, so we can remove the AND }
  14461. hp2 := tai(hp1.Previous);
  14462. RemoveInstruction(hp1);
  14463. hp1 := hp2;
  14464. end
  14465. else { Different register target }
  14466. begin
  14467. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  14468. taicpu(hp1).opcode := A_MOV;
  14469. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  14470. case taicpu(hp1).opsize of
  14471. S_BW:
  14472. taicpu(hp1).opsize := S_W;
  14473. S_BL, S_WL:
  14474. taicpu(hp1).opsize := S_L;
  14475. else
  14476. InternalError(2022081503);
  14477. end;
  14478. end;
  14479. end
  14480. else if (Shift > 0) and
  14481. (taicpu(p).opsize = S_W) and
  14482. (taicpu(hp1).opsize = S_WL) and
  14483. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  14484. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  14485. begin
  14486. { Detect:
  14487. shr x, %ax (x > 0)
  14488. ...
  14489. movzwl %ax,%eax
  14490. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14491. }
  14492. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  14493. taicpu(hp1).opcode := A_CWDE;
  14494. taicpu(hp1).clearop(0);
  14495. taicpu(hp1).clearop(1);
  14496. taicpu(hp1).ops := 0;
  14497. end;
  14498. { Move onto the next instruction }
  14499. Continue;
  14500. end;
  14501. A_SHL, A_SAL, A_SHR:
  14502. if (taicpu(hp1).opsize <= LimitSize) and
  14503. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14504. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  14505. begin
  14506. { Make sure the sizes don't exceed the register size limit
  14507. (measured by the shift value falling below the limit) }
  14508. if taicpu(hp1).opsize < LimitSize then
  14509. LimitSize := taicpu(hp1).opsize;
  14510. if taicpu(hp1).opcode = A_SHR then
  14511. Inc(Shift, taicpu(hp1).oper[0]^.val)
  14512. else
  14513. begin
  14514. Dec(Shift, taicpu(hp1).oper[0]^.val);
  14515. DoNotMerge := True;
  14516. end;
  14517. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  14518. Break;
  14519. { Since we've established that the combined shift is within
  14520. limits, we can actually combine the adjacent SHR
  14521. instructions even if they're different sizes }
  14522. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  14523. begin
  14524. hp2 := tai(hp1.Previous);
  14525. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  14526. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  14527. RemoveInstruction(hp1);
  14528. hp1 := hp2;
  14529. end;
  14530. { Move onto the next instruction }
  14531. Continue;
  14532. end;
  14533. else
  14534. ;
  14535. end;
  14536. Break;
  14537. until False;
  14538. { Detect the following (looking backwards):
  14539. shr %cl,%reg
  14540. shr x, %reg
  14541. Swap the two SHR instructions to minimise a pipeline stall.
  14542. }
  14543. if GetLastInstruction(p, hp1) and
  14544. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  14545. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14546. { First operand will be %cl }
  14547. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  14548. { Just to be sure }
  14549. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  14550. begin
  14551. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  14552. { Moving the entries this way ensures the register tracking remains correct }
  14553. Asml.Remove(p);
  14554. Asml.InsertBefore(p, hp1);
  14555. p := hp1;
  14556. { Don't set Result to True because the current instruction is now
  14557. "shr %cl,%reg" and there's nothing more we can do with it }
  14558. end;
  14559. end;
  14560. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  14561. var
  14562. hp1, hp2: tai;
  14563. Opposite, SecondOpposite: TAsmOp;
  14564. NewCond: TAsmCond;
  14565. begin
  14566. Result := False;
  14567. { Change:
  14568. add/sub 128,(dest)
  14569. To:
  14570. sub/add -128,(dest)
  14571. This generaally takes fewer bytes to encode because -128 can be stored
  14572. in a signed byte, whereas +128 cannot.
  14573. }
  14574. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  14575. begin
  14576. if taicpu(p).opcode = A_ADD then
  14577. Opposite := A_SUB
  14578. else
  14579. Opposite := A_ADD;
  14580. { Be careful if the flags are in use, because the CF flag inverts
  14581. when changing from ADD to SUB and vice versa }
  14582. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  14583. GetNextInstruction(p, hp1) then
  14584. begin
  14585. TransferUsedRegs(TmpUsedRegs);
  14586. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  14587. hp2 := hp1;
  14588. { Scan ahead to check if everything's safe }
  14589. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  14590. begin
  14591. if (hp1.typ <> ait_instruction) then
  14592. { Probably unsafe since the flags are still in use }
  14593. Exit;
  14594. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  14595. { Stop searching at an unconditional jump }
  14596. Break;
  14597. if not
  14598. (
  14599. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  14600. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  14601. ) and
  14602. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  14603. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  14604. Exit;
  14605. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14606. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  14607. { Move to the next instruction }
  14608. GetNextInstruction(hp1, hp1);
  14609. end;
  14610. while Assigned(hp2) and (hp2 <> hp1) do
  14611. begin
  14612. NewCond := C_None;
  14613. case taicpu(hp2).condition of
  14614. C_A, C_NBE:
  14615. NewCond := C_BE;
  14616. C_B, C_C, C_NAE:
  14617. NewCond := C_AE;
  14618. C_AE, C_NB, C_NC:
  14619. NewCond := C_B;
  14620. C_BE, C_NA:
  14621. NewCond := C_A;
  14622. else
  14623. { No change needed };
  14624. end;
  14625. if NewCond <> C_None then
  14626. begin
  14627. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  14628. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  14629. taicpu(hp2).condition := NewCond;
  14630. end
  14631. else
  14632. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  14633. begin
  14634. { Because of the flipping of the carry bit, to ensure
  14635. the operation remains equivalent, ADC becomes SBB
  14636. and vice versa, and the constant is not-inverted.
  14637. If multiple ADCs or SBBs appear in a row, each one
  14638. changed causes the carry bit to invert, so they all
  14639. need to be flipped }
  14640. if taicpu(hp2).opcode = A_ADC then
  14641. SecondOpposite := A_SBB
  14642. else
  14643. SecondOpposite := A_ADC;
  14644. if taicpu(hp2).oper[0]^.typ <> top_const then
  14645. { Should have broken out of this optimisation already }
  14646. InternalError(2021112901);
  14647. 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]^) + ' -> ' +
  14648. 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);
  14649. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  14650. taicpu(hp2).opcode := SecondOpposite;
  14651. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  14652. end;
  14653. { Move to the next instruction }
  14654. GetNextInstruction(hp2, hp2);
  14655. end;
  14656. if (hp2 <> hp1) then
  14657. InternalError(2021111501);
  14658. end;
  14659. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  14660. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  14661. taicpu(p).opcode := Opposite;
  14662. taicpu(p).oper[0]^.val := -128;
  14663. { No further optimisations can be made on this instruction, so move
  14664. onto the next one to save time }
  14665. p := tai(p.Next);
  14666. UpdateUsedRegs(p);
  14667. Result := True;
  14668. Exit;
  14669. end;
  14670. { Detect:
  14671. add/sub %reg2,(dest)
  14672. add/sub x, (dest)
  14673. (dest can be a register or a reference)
  14674. Swap the instructions to minimise a pipeline stall. This reverses the
  14675. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  14676. optimisations could be made.
  14677. }
  14678. if (taicpu(p).oper[0]^.typ = top_reg) and
  14679. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  14680. (
  14681. (
  14682. (taicpu(p).oper[1]^.typ = top_reg) and
  14683. { We can try searching further ahead if we're writing to a register }
  14684. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  14685. ) or
  14686. (
  14687. (taicpu(p).oper[1]^.typ = top_ref) and
  14688. GetNextInstruction(p, hp1)
  14689. )
  14690. ) and
  14691. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  14692. (taicpu(hp1).oper[0]^.typ = top_const) and
  14693. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  14694. begin
  14695. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  14696. TransferUsedRegs(TmpUsedRegs);
  14697. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  14698. hp2 := p;
  14699. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  14700. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  14701. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  14702. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14703. begin
  14704. asml.remove(hp1);
  14705. asml.InsertBefore(hp1, p);
  14706. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  14707. Result := True;
  14708. end;
  14709. end;
  14710. end;
  14711. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  14712. var
  14713. hp1: tai;
  14714. begin
  14715. Result:=false;
  14716. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  14717. while GetNextInstruction(p, hp1) and
  14718. TrySwapMovCmp(p, hp1) do
  14719. begin
  14720. if MatchInstruction(hp1, A_MOV, []) then
  14721. begin
  14722. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14723. begin
  14724. { A little hacky, but since CMP doesn't read the flags, only
  14725. modify them, it's safe if they get scrambled by MOV -> XOR }
  14726. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14727. Result := PostPeepholeOptMov(hp1);
  14728. {$ifdef x86_64}
  14729. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14730. { Used to shrink instruction size }
  14731. PostPeepholeOptXor(hp1);
  14732. {$endif x86_64}
  14733. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14734. end
  14735. else
  14736. begin
  14737. Result := PostPeepholeOptMov(hp1);
  14738. {$ifdef x86_64}
  14739. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14740. { Used to shrink instruction size }
  14741. PostPeepholeOptXor(hp1);
  14742. {$endif x86_64}
  14743. end;
  14744. end;
  14745. { Enabling this flag is actually a null operation, but it marks
  14746. the code as 'modified' during this pass }
  14747. Include(OptsToCheck, aoc_ForceNewIteration);
  14748. end;
  14749. { change "cmp $0, %reg" to "test %reg, %reg" }
  14750. if MatchOpType(taicpu(p),top_const,top_reg) and
  14751. (taicpu(p).oper[0]^.val = 0) then
  14752. begin
  14753. taicpu(p).opcode := A_TEST;
  14754. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  14755. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  14756. Result:=true;
  14757. end;
  14758. end;
  14759. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  14760. var
  14761. IsTestConstX, IsValid : Boolean;
  14762. hp1,hp2 : tai;
  14763. begin
  14764. Result:=false;
  14765. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  14766. if (taicpu(p).opcode = A_TEST) then
  14767. while GetNextInstruction(p, hp1) and
  14768. TrySwapMovCmp(p, hp1) do
  14769. begin
  14770. if MatchInstruction(hp1, A_MOV, []) then
  14771. begin
  14772. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14773. begin
  14774. { A little hacky, but since TEST doesn't read the flags, only
  14775. modify them, it's safe if they get scrambled by MOV -> XOR }
  14776. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14777. Result := PostPeepholeOptMov(hp1);
  14778. {$ifdef x86_64}
  14779. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14780. { Used to shrink instruction size }
  14781. PostPeepholeOptXor(hp1);
  14782. {$endif x86_64}
  14783. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14784. end
  14785. else
  14786. begin
  14787. Result := PostPeepholeOptMov(hp1);
  14788. {$ifdef x86_64}
  14789. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14790. { Used to shrink instruction size }
  14791. PostPeepholeOptXor(hp1);
  14792. {$endif x86_64}
  14793. end;
  14794. end;
  14795. { Enabling this flag is actually a null operation, but it marks
  14796. the code as 'modified' during this pass }
  14797. Include(OptsToCheck, aoc_ForceNewIteration);
  14798. end;
  14799. { If x is a power of 2 (popcnt = 1), change:
  14800. or $x, %reg/ref
  14801. To:
  14802. bts lb(x), %reg/ref
  14803. }
  14804. if (taicpu(p).opcode = A_OR) and
  14805. IsBTXAcceptable(p) and
  14806. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14807. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14808. (
  14809. { Don't optimise if a test instruction follows }
  14810. not GetNextInstruction(p, hp1) or
  14811. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14812. ) then
  14813. begin
  14814. 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);
  14815. taicpu(p).opcode := A_BTS;
  14816. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14817. Result := True;
  14818. Exit;
  14819. end;
  14820. { If x is a power of 2 (popcnt = 1), change:
  14821. test $x, %reg/ref
  14822. je / sete / cmove (or jne / setne)
  14823. To:
  14824. bt lb(x), %reg/ref
  14825. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  14826. }
  14827. if (taicpu(p).opcode = A_TEST) and
  14828. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  14829. (taicpu(p).oper[0]^.typ = top_const) and
  14830. (
  14831. (cs_opt_size in current_settings.optimizerswitches) or
  14832. (
  14833. (taicpu(p).oper[1]^.typ = top_reg) and
  14834. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14835. ) or
  14836. (
  14837. (taicpu(p).oper[1]^.typ <> top_reg) and
  14838. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14839. )
  14840. ) and
  14841. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14842. { For sizes less than S_L, the byte size is equal or larger with BT,
  14843. so don't bother optimising }
  14844. (taicpu(p).opsize >= S_L) then
  14845. begin
  14846. IsValid := True;
  14847. { Check the next set of instructions, watching the FLAGS register
  14848. and the conditions used }
  14849. TransferUsedRegs(TmpUsedRegs);
  14850. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14851. hp1 := p;
  14852. hp2 := nil;
  14853. while GetNextInstruction(hp1, hp1) do
  14854. begin
  14855. if not Assigned(hp2) then
  14856. { The first instruction after TEST }
  14857. hp2 := hp1;
  14858. if (hp1.typ <> ait_instruction) then
  14859. begin
  14860. { If the flags are no longer in use, everything is fine }
  14861. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14862. IsValid := False;
  14863. Break;
  14864. end;
  14865. case taicpu(hp1).condition of
  14866. C_None:
  14867. begin
  14868. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14869. { Something is not quite normal, so play safe and don't change }
  14870. IsValid := False;
  14871. Break;
  14872. end;
  14873. C_E, C_Z, C_NE, C_NZ:
  14874. { This is fine };
  14875. else
  14876. begin
  14877. { Unsupported condition }
  14878. IsValid := False;
  14879. Break;
  14880. end;
  14881. end;
  14882. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  14883. end;
  14884. if IsValid then
  14885. begin
  14886. while hp2 <> hp1 do
  14887. begin
  14888. case taicpu(hp2).condition of
  14889. C_Z, C_E:
  14890. taicpu(hp2).condition := C_NC;
  14891. C_NZ, C_NE:
  14892. taicpu(hp2).condition := C_C;
  14893. else
  14894. { Should not get this by this point }
  14895. InternalError(2022110701);
  14896. end;
  14897. GetNextInstruction(hp2, hp2);
  14898. end;
  14899. 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);
  14900. taicpu(p).opcode := A_BT;
  14901. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14902. Result := True;
  14903. Exit;
  14904. end;
  14905. end;
  14906. { removes the line marked with (x) from the sequence
  14907. and/or/xor/add/sub/... $x, %y
  14908. test/or %y, %y | test $-1, %y (x)
  14909. j(n)z _Label
  14910. as the first instruction already adjusts the ZF
  14911. %y operand may also be a reference }
  14912. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  14913. MatchOperand(taicpu(p).oper[0]^,-1);
  14914. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  14915. GetLastInstruction(p, hp1) and
  14916. (tai(hp1).typ = ait_instruction) and
  14917. GetNextInstruction(p,hp2) and
  14918. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  14919. case taicpu(hp1).opcode Of
  14920. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  14921. { These two instructions set the zero flag if the result is zero }
  14922. A_POPCNT, A_LZCNT:
  14923. begin
  14924. if (
  14925. { With POPCNT, an input of zero will set the zero flag
  14926. because the population count of zero is zero }
  14927. (taicpu(hp1).opcode = A_POPCNT) and
  14928. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  14929. (
  14930. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  14931. { Faster than going through the second half of the 'or'
  14932. condition below }
  14933. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  14934. )
  14935. ) or (
  14936. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  14937. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14938. { and in case of carry for A(E)/B(E)/C/NC }
  14939. (
  14940. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  14941. (
  14942. (taicpu(hp1).opcode <> A_ADD) and
  14943. (taicpu(hp1).opcode <> A_SUB) and
  14944. (taicpu(hp1).opcode <> A_LZCNT)
  14945. )
  14946. )
  14947. ) then
  14948. begin
  14949. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  14950. RemoveCurrentP(p, hp2);
  14951. Result:=true;
  14952. Exit;
  14953. end;
  14954. end;
  14955. A_SHL, A_SAL, A_SHR, A_SAR:
  14956. begin
  14957. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  14958. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  14959. { therefore, it's only safe to do this optimization for }
  14960. { shifts by a (nonzero) constant }
  14961. (taicpu(hp1).oper[0]^.typ = top_const) and
  14962. (taicpu(hp1).oper[0]^.val <> 0) and
  14963. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14964. { and in case of carry for A(E)/B(E)/C/NC }
  14965. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14966. begin
  14967. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  14968. RemoveCurrentP(p, hp2);
  14969. Result:=true;
  14970. Exit;
  14971. end;
  14972. end;
  14973. A_DEC, A_INC, A_NEG:
  14974. begin
  14975. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  14976. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14977. { and in case of carry for A(E)/B(E)/C/NC }
  14978. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14979. begin
  14980. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  14981. RemoveCurrentP(p, hp2);
  14982. Result:=true;
  14983. Exit;
  14984. end;
  14985. end;
  14986. A_ANDN, A_BZHI:
  14987. begin
  14988. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14989. { Only the zero and sign flags are consistent with what the result is }
  14990. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  14991. begin
  14992. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  14993. RemoveCurrentP(p, hp2);
  14994. Result:=true;
  14995. Exit;
  14996. end;
  14997. end;
  14998. A_BEXTR:
  14999. begin
  15000. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15001. { Only the zero flag is set }
  15002. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15003. begin
  15004. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15005. RemoveCurrentP(p, hp2);
  15006. Result:=true;
  15007. Exit;
  15008. end;
  15009. end;
  15010. else
  15011. ;
  15012. end; { case }
  15013. { change "test $-1,%reg" into "test %reg,%reg" }
  15014. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15015. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15016. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15017. if MatchInstruction(p, A_OR, []) and
  15018. { Can only match if they're both registers }
  15019. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15020. begin
  15021. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15022. taicpu(p).opcode := A_TEST;
  15023. { No need to set Result to True, as we've done all the optimisations we can }
  15024. end;
  15025. end;
  15026. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15027. var
  15028. hp1,hp3 : tai;
  15029. {$ifndef x86_64}
  15030. hp2 : taicpu;
  15031. {$endif x86_64}
  15032. begin
  15033. Result:=false;
  15034. hp3:=nil;
  15035. {$ifndef x86_64}
  15036. { don't do this on modern CPUs, this really hurts them due to
  15037. broken call/ret pairing }
  15038. if (current_settings.optimizecputype < cpu_Pentium2) and
  15039. not(cs_create_pic in current_settings.moduleswitches) and
  15040. GetNextInstruction(p, hp1) and
  15041. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15042. MatchOpType(taicpu(hp1),top_ref) and
  15043. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15044. begin
  15045. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15046. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15047. InsertLLItem(p.previous, p, hp2);
  15048. taicpu(p).opcode := A_JMP;
  15049. taicpu(p).is_jmp := true;
  15050. RemoveInstruction(hp1);
  15051. Result:=true;
  15052. end
  15053. else
  15054. {$endif x86_64}
  15055. { replace
  15056. call procname
  15057. ret
  15058. by
  15059. jmp procname
  15060. but do it only on level 4 because it destroys stack back traces
  15061. else if the subroutine is marked as no return, remove the ret
  15062. }
  15063. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15064. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15065. GetNextInstruction(p, hp1) and
  15066. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15067. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15068. SetAndTest(hp1,hp3) and
  15069. GetNextInstruction(hp1,hp1) and
  15070. MatchInstruction(hp1,A_RET,[S_NO])
  15071. )
  15072. ) and
  15073. (taicpu(hp1).ops=0) then
  15074. begin
  15075. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15076. { we might destroy stack alignment here if we do not do a call }
  15077. (target_info.stackalign<=sizeof(SizeUInt)) then
  15078. begin
  15079. taicpu(p).opcode := A_JMP;
  15080. taicpu(p).is_jmp := true;
  15081. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15082. end
  15083. else
  15084. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15085. RemoveInstruction(hp1);
  15086. if Assigned(hp3) then
  15087. begin
  15088. AsmL.Remove(hp3);
  15089. AsmL.InsertBefore(hp3,p)
  15090. end;
  15091. Result:=true;
  15092. end;
  15093. end;
  15094. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15095. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15096. begin
  15097. case OpSize of
  15098. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15099. Result := (Val <= $FF) and (Val >= -128);
  15100. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15101. Result := (Val <= $FFFF) and (Val >= -32768);
  15102. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15103. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15104. else
  15105. Result := True;
  15106. end;
  15107. end;
  15108. var
  15109. hp1, hp2 : tai;
  15110. SizeChange: Boolean;
  15111. PreMessage: string;
  15112. begin
  15113. Result := False;
  15114. if (taicpu(p).oper[0]^.typ = top_reg) and
  15115. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15116. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15117. begin
  15118. { Change (using movzbl %al,%eax as an example):
  15119. movzbl %al, %eax movzbl %al, %eax
  15120. cmpl x, %eax testl %eax,%eax
  15121. To:
  15122. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15123. movzbl %al, %eax movzbl %al, %eax
  15124. Smaller instruction and minimises pipeline stall as the CPU
  15125. doesn't have to wait for the register to get zero-extended. [Kit]
  15126. Also allow if the smaller of the two registers is being checked,
  15127. as this still removes the false dependency.
  15128. }
  15129. if
  15130. (
  15131. (
  15132. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15133. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15134. ) or (
  15135. { If MatchOperand returns True, they must both be registers }
  15136. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15137. )
  15138. ) and
  15139. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15140. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15141. begin
  15142. 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);
  15143. asml.Remove(hp1);
  15144. asml.InsertBefore(hp1, p);
  15145. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15146. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15147. begin
  15148. taicpu(hp1).opcode := A_TEST;
  15149. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15150. end;
  15151. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15152. case taicpu(p).opsize of
  15153. S_BW, S_BL:
  15154. begin
  15155. SizeChange := taicpu(hp1).opsize <> S_B;
  15156. taicpu(hp1).changeopsize(S_B);
  15157. end;
  15158. S_WL:
  15159. begin
  15160. SizeChange := taicpu(hp1).opsize <> S_W;
  15161. taicpu(hp1).changeopsize(S_W);
  15162. end
  15163. else
  15164. InternalError(2020112701);
  15165. end;
  15166. UpdateUsedRegs(tai(p.Next));
  15167. { Check if the register is used aferwards - if not, we can
  15168. remove the movzx instruction completely }
  15169. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15170. begin
  15171. { Hp1 is a better position than p for debugging purposes }
  15172. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15173. RemoveCurrentp(p, hp1);
  15174. Result := True;
  15175. end;
  15176. if SizeChange then
  15177. DebugMsg(SPeepholeOptimization + PreMessage +
  15178. 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)
  15179. else
  15180. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15181. Exit;
  15182. end;
  15183. { Change (using movzwl %ax,%eax as an example):
  15184. movzwl %ax, %eax
  15185. movb %al, (dest) (Register is smaller than read register in movz)
  15186. To:
  15187. movb %al, (dest) (Move one back to avoid a false dependency)
  15188. movzwl %ax, %eax
  15189. }
  15190. if (taicpu(hp1).opcode = A_MOV) and
  15191. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15192. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15193. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15194. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15195. begin
  15196. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15197. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15198. asml.Remove(hp1);
  15199. asml.InsertBefore(hp1, p);
  15200. if taicpu(hp1).oper[1]^.typ = top_reg then
  15201. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15202. { Check if the register is used aferwards - if not, we can
  15203. remove the movzx instruction completely }
  15204. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15205. begin
  15206. { Hp1 is a better position than p for debugging purposes }
  15207. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15208. RemoveCurrentp(p, hp1);
  15209. Result := True;
  15210. end;
  15211. Exit;
  15212. end;
  15213. end;
  15214. end;
  15215. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15216. var
  15217. hp1: tai;
  15218. {$ifdef x86_64}
  15219. PreMessage, RegName: string;
  15220. {$endif x86_64}
  15221. begin
  15222. Result := False;
  15223. { If x is a power of 2 (popcnt = 1), change:
  15224. xor $x, %reg/ref
  15225. To:
  15226. btc lb(x), %reg/ref
  15227. }
  15228. if IsBTXAcceptable(p) and
  15229. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15230. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15231. (
  15232. { Don't optimise if a test instruction follows }
  15233. not GetNextInstruction(p, hp1) or
  15234. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15235. ) then
  15236. begin
  15237. 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);
  15238. taicpu(p).opcode := A_BTC;
  15239. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15240. Result := True;
  15241. Exit;
  15242. end;
  15243. {$ifdef x86_64}
  15244. { Code size reduction by J. Gareth "Kit" Moreton }
  15245. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15246. as this removes the REX prefix }
  15247. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15248. Exit;
  15249. if taicpu(p).oper[0]^.typ <> top_reg then
  15250. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15251. InternalError(2018011500);
  15252. case taicpu(p).opsize of
  15253. S_Q:
  15254. begin
  15255. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15256. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15257. { The actual optimization }
  15258. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15259. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15260. taicpu(p).changeopsize(S_L);
  15261. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15262. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15263. end;
  15264. else
  15265. ;
  15266. end;
  15267. {$endif x86_64}
  15268. end;
  15269. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15270. var
  15271. XReg: TRegister;
  15272. begin
  15273. Result := False;
  15274. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15275. Smaller encoding and slightly faster on some platforms (also works for
  15276. ZMM-sized registers) }
  15277. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15278. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15279. begin
  15280. XReg := taicpu(p).oper[0]^.reg;
  15281. if (taicpu(p).oper[1]^.reg = XReg) then
  15282. begin
  15283. taicpu(p).changeopsize(S_XMM);
  15284. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15285. if (cs_opt_size in current_settings.optimizerswitches) then
  15286. begin
  15287. { Change input registers to %xmm0 to reduce size. Note that
  15288. there's a risk of a false dependency doing this, so only
  15289. optimise for size here }
  15290. XReg := NR_XMM0;
  15291. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15292. end
  15293. else
  15294. begin
  15295. setsubreg(XReg, R_SUBMMX);
  15296. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15297. end;
  15298. taicpu(p).oper[0]^.reg := XReg;
  15299. taicpu(p).oper[1]^.reg := XReg;
  15300. Result := True;
  15301. end;
  15302. end;
  15303. end;
  15304. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15305. var
  15306. OperIdx: Integer;
  15307. begin
  15308. for OperIdx := 0 to p.ops - 1 do
  15309. if p.oper[OperIdx]^.typ = top_ref then
  15310. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15311. end;
  15312. end.