aoptx86.pas 748 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration,
  34. aoc_DoPass2JccOpts
  35. );
  36. TX86AsmOptimizer = class(TAsmOptimizer)
  37. { some optimizations are very expensive to check, so the
  38. pre opt pass can be used to set some flags, depending on the found
  39. instructions if it is worth to check a certain optimization }
  40. OptsToCheck : set of TOptsToCheck;
  41. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  42. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  43. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  44. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  45. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  46. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  47. how many instructions away that Next is from Current is.
  48. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  49. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  50. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  51. potentially allowing further optimisation (although it might need to know if
  52. it crossed a conditional jump. }
  53. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  54. {
  55. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  56. the use of a register by allocs/dealloc, so it can ignore calls.
  57. In the following example, GetNextInstructionUsingReg will return the second movq,
  58. GetNextInstructionUsingRegTrackingUse won't.
  59. movq %rdi,%rax
  60. # Register rdi released
  61. # Register rdi allocated
  62. movq %rax,%rdi
  63. While in this example:
  64. movq %rdi,%rax
  65. call proc
  66. movq %rdi,%rax
  67. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  68. won't.
  69. }
  70. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  71. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  72. { returns true if any of the registers in ref are modified by any
  73. instruction between p1 and p2, or if those instructions write to the
  74. reference }
  75. function RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  76. private
  77. function SkipSimpleInstructions(var hp1: tai): Boolean;
  78. protected
  79. class function IsMOVZXAcceptable: Boolean; static; inline;
  80. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  81. { Attempts to allocate a volatile integer register for use between p and hp,
  82. using AUsedRegs for the current register usage information. Returns NR_NO
  83. if no free register could be found }
  84. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  85. { Attempts to allocate a volatile MM register for use between p and hp,
  86. using AUsedRegs for the current register usage information. Returns NR_NO
  87. if no free register could be found }
  88. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  89. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  90. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  91. { checks whether reading the value in reg1 depends on the value of reg2. This
  92. is very similar to SuperRegisterEquals, except it takes into account that
  93. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  94. depend on the value in AH). }
  95. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  96. { Replaces all references to AOldReg in a memory reference to ANewReg }
  97. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  98. { Replaces all references to AOldReg in an operand to ANewReg }
  99. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  100. { Replaces all references to AOldReg in an instruction to ANewReg,
  101. except where the register is being written }
  102. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  103. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  104. or writes to a global symbol }
  105. class function IsRefSafe(const ref: PReference): Boolean; static;
  106. { Returns true if the given MOV instruction can be safely converted to CMOV }
  107. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  108. { Like UpdateUsedRegs, but ignores deallocations }
  109. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  110. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  111. class function IsBTXAcceptable(p : tai) : boolean; static;
  112. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  113. conversion was successful }
  114. function ConvertLEA(const p : taicpu): Boolean;
  115. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  116. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  117. procedure DebugMsg(const s : string; p : tai);inline;
  118. class function IsExitCode(p : tai) : boolean; static;
  119. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  120. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  121. procedure RemoveLastDeallocForFuncRes(p : tai);
  122. function DoArithCombineOpt(var p : tai) : Boolean;
  123. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  124. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  125. function PrePeepholeOptSxx(var p : tai) : boolean;
  126. function PrePeepholeOptIMUL(var p : tai) : boolean;
  127. function PrePeepholeOptAND(var p : tai) : boolean;
  128. function OptPass1Test(var p: tai): boolean;
  129. function OptPass1Add(var p: tai): boolean;
  130. function OptPass1AND(var p : tai) : boolean;
  131. function OptPass1CMOVcc(var p: tai): Boolean;
  132. function OptPass1_V_MOVAP(var p : tai) : boolean;
  133. function OptPass1VOP(var p : tai) : boolean;
  134. function OptPass1MOV(var p : tai) : boolean;
  135. function OptPass1Movx(var p : tai) : boolean;
  136. function OptPass1MOVXX(var p : tai) : boolean;
  137. function OptPass1OP(var p : tai) : boolean;
  138. function OptPass1LEA(var p : tai) : boolean;
  139. function OptPass1Sub(var p : tai) : boolean;
  140. function OptPass1SHLSAL(var p : tai) : boolean;
  141. function OptPass1SHR(var p : tai) : boolean;
  142. function OptPass1FSTP(var p : tai) : boolean;
  143. function OptPass1FLD(var p : tai) : boolean;
  144. function OptPass1Cmp(var p : tai) : boolean;
  145. function OptPass1PXor(var p : tai) : boolean;
  146. function OptPass1VPXor(var p: tai): boolean;
  147. function OptPass1Imul(var p : tai) : boolean;
  148. function OptPass1Jcc(var p : tai) : boolean;
  149. function OptPass1SHXX(var p: tai): boolean;
  150. function OptPass1VMOVDQ(var p: tai): Boolean;
  151. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  152. function OptPass1STCCLC(var p: tai): Boolean;
  153. function OptPass2STCCLC(var p: tai): Boolean;
  154. function OptPass2CMOVcc(var p: tai): Boolean;
  155. function OptPass2Movx(var p : tai): Boolean;
  156. function OptPass2MOV(var p : tai) : boolean;
  157. function OptPass2Imul(var p : tai) : boolean;
  158. function OptPass2Jmp(var p : tai) : boolean;
  159. function OptPass2Jcc(var p : tai) : boolean;
  160. function OptPass2Lea(var p: tai): Boolean;
  161. function OptPass2SUB(var p: tai): Boolean;
  162. function OptPass2ADD(var p : tai): Boolean;
  163. function OptPass2SETcc(var p : tai) : boolean;
  164. function OptPass2Cmp(var p: tai): Boolean;
  165. function OptPass2Test(var p: tai): Boolean;
  166. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  167. function PostPeepholeOptMov(var p : tai) : Boolean;
  168. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  169. function PostPeepholeOptXor(var p : tai) : Boolean;
  170. function PostPeepholeOptAnd(var p : tai) : boolean;
  171. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  172. function PostPeepholeOptCmp(var p : tai) : Boolean;
  173. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  174. function PostPeepholeOptCall(var p : tai) : Boolean;
  175. function PostPeepholeOptLea(var p : tai) : Boolean;
  176. function PostPeepholeOptPush(var p: tai): Boolean;
  177. function PostPeepholeOptShr(var p : tai) : boolean;
  178. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  179. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  180. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  181. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  182. function TrySwapMovOp(var p, hp1: tai): Boolean;
  183. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  184. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  185. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  186. { Processor-dependent reference optimisation }
  187. class procedure OptimizeRefs(var p: taicpu); static;
  188. end;
  189. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  190. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  191. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  192. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  193. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  194. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  195. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  196. {$if max_operands>2}
  197. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  198. {$endif max_operands>2}
  199. function RefsEqual(const r1, r2: treference): boolean;
  200. { Like RefsEqual, but doesn't compare the offsets }
  201. function RefsAlmostEqual(const r1, r2: treference): boolean;
  202. { Note that Result is set to True if the references COULD overlap but the
  203. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  204. might still overlap because %reg2 could be equal to %reg1-4 }
  205. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  206. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  207. { returns true, if ref is a reference using only the registers passed as base and index
  208. and having an offset }
  209. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  210. implementation
  211. uses
  212. cutils,verbose,
  213. systems,
  214. globals,
  215. cpuinfo,
  216. procinfo,
  217. paramgr,
  218. aasmbase,
  219. aoptbase,aoptutils,
  220. symconst,symsym,
  221. cgx86,
  222. itcpugas;
  223. {$ifndef 8086}
  224. const
  225. MAX_CMOV_INSTRUCTIONS = 4;
  226. MAX_CMOV_REGISTERS = 8;
  227. type
  228. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  229. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  230. tsProcessed);
  231. { For OptPass2Jcc }
  232. TCMOVTracking = object
  233. private
  234. CMOVScore, ConstCount: LongInt;
  235. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  236. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  237. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  238. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  239. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  240. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  241. fOptimizer: TX86AsmOptimizer;
  242. fLabel: TAsmSymbol;
  243. fInsertionPoint,
  244. fCondition,
  245. fInitialJump,
  246. fFirstMovBlock,
  247. fFirstMovBlockStop,
  248. fSecondJump,
  249. fThirdJump,
  250. fSecondMovBlock,
  251. fSecondMovBlockStop,
  252. fMidLabel,
  253. fEndLabel,
  254. fAllocationRange: tai;
  255. fState: TCMovTrackingState;
  256. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  257. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  258. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  259. public
  260. RegisterTracking: TAllUsedRegs;
  261. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  262. destructor Done;
  263. procedure Process(out new_p: tai);
  264. property State: TCMovTrackingState read fState;
  265. end;
  266. PCMOVTracking = ^TCMOVTracking;
  267. {$endif 8086}
  268. {$ifdef DEBUG_AOPTCPU}
  269. const
  270. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  271. {$else DEBUG_AOPTCPU}
  272. { Empty strings help the optimizer to remove string concatenations that won't
  273. ever appear to the user on release builds. [Kit] }
  274. const
  275. SPeepholeOptimization = '';
  276. {$endif DEBUG_AOPTCPU}
  277. LIST_STEP_SIZE = 4;
  278. type
  279. TJumpTrackingItem = class(TLinkedListItem)
  280. private
  281. FSymbol: TAsmSymbol;
  282. FRefs: LongInt;
  283. public
  284. constructor Create(ASymbol: TAsmSymbol);
  285. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  286. property Symbol: TAsmSymbol read FSymbol;
  287. property Refs: LongInt read FRefs;
  288. end;
  289. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  290. begin
  291. inherited Create;
  292. FSymbol := ASymbol;
  293. FRefs := 0;
  294. end;
  295. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  296. begin
  297. Inc(FRefs);
  298. end;
  299. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  300. begin
  301. result :=
  302. (instr.typ = ait_instruction) and
  303. (taicpu(instr).opcode = op) and
  304. ((opsize = []) or (taicpu(instr).opsize in opsize));
  305. end;
  306. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  307. begin
  308. result :=
  309. (instr.typ = ait_instruction) and
  310. ((taicpu(instr).opcode = op1) or
  311. (taicpu(instr).opcode = op2)
  312. ) and
  313. ((opsize = []) or (taicpu(instr).opsize in opsize));
  314. end;
  315. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  316. begin
  317. result :=
  318. (instr.typ = ait_instruction) and
  319. ((taicpu(instr).opcode = op1) or
  320. (taicpu(instr).opcode = op2) or
  321. (taicpu(instr).opcode = op3)
  322. ) and
  323. ((opsize = []) or (taicpu(instr).opsize in opsize));
  324. end;
  325. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  326. const opsize : topsizes) : boolean;
  327. var
  328. op : TAsmOp;
  329. begin
  330. result:=false;
  331. if (instr.typ <> ait_instruction) or
  332. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  333. exit;
  334. for op in ops do
  335. begin
  336. if taicpu(instr).opcode = op then
  337. begin
  338. result:=true;
  339. exit;
  340. end;
  341. end;
  342. end;
  343. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  344. begin
  345. result := (oper.typ = top_reg) and (oper.reg = reg);
  346. end;
  347. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  348. begin
  349. result := (oper.typ = top_const) and (oper.val = a);
  350. end;
  351. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  352. begin
  353. result := oper1.typ = oper2.typ;
  354. if result then
  355. case oper1.typ of
  356. top_const:
  357. Result:=oper1.val = oper2.val;
  358. top_reg:
  359. Result:=oper1.reg = oper2.reg;
  360. top_ref:
  361. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  362. else
  363. internalerror(2013102801);
  364. end
  365. end;
  366. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  367. begin
  368. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  369. if result then
  370. case oper1.typ of
  371. top_const:
  372. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  373. top_reg:
  374. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  375. top_ref:
  376. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  377. else
  378. internalerror(2020052401);
  379. end
  380. end;
  381. function RefsEqual(const r1, r2: treference): boolean;
  382. begin
  383. RefsEqual :=
  384. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  385. (r1.relsymbol = r2.relsymbol) and
  386. (r1.segment = r2.segment) and (r1.base = r2.base) and
  387. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  388. (r1.offset = r2.offset) and
  389. (r1.volatility + r2.volatility = []);
  390. end;
  391. function RefsAlmostEqual(const r1, r2: treference): boolean;
  392. begin
  393. RefsAlmostEqual :=
  394. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  395. (r1.relsymbol = r2.relsymbol) and
  396. (r1.segment = r2.segment) and (r1.base = r2.base) and
  397. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  398. { Don't compare the offsets }
  399. (r1.volatility + r2.volatility = []);
  400. end;
  401. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  402. begin
  403. if (r1.symbol<>r2.symbol) then
  404. { If the index registers are different, there's a chance one could
  405. be set so it equals the other symbol }
  406. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  407. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  408. (r1.relsymbol = r2.relsymbol) and
  409. (r1.segment = r2.segment) and (r1.base = r2.base) and
  410. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  411. (r1.volatility + r2.volatility = []) then
  412. { In this case, it all depends on the offsets }
  413. Exit(abs(r1.offset - r2.offset) < Range);
  414. { There's a chance things MIGHT overlap, so take no chances }
  415. Result := True;
  416. end;
  417. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  418. begin
  419. Result:=(ref.offset=0) and
  420. (ref.scalefactor in [0,1]) and
  421. (ref.segment=NR_NO) and
  422. (ref.symbol=nil) and
  423. (ref.relsymbol=nil) and
  424. ((base=NR_INVALID) or
  425. (ref.base=base)) and
  426. ((index=NR_INVALID) or
  427. (ref.index=index)) and
  428. (ref.volatility=[]);
  429. end;
  430. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  431. begin
  432. Result:=(ref.scalefactor in [0,1]) and
  433. (ref.segment=NR_NO) and
  434. (ref.symbol=nil) and
  435. (ref.relsymbol=nil) and
  436. ((base=NR_INVALID) or
  437. (ref.base=base)) and
  438. ((index=NR_INVALID) or
  439. (ref.index=index)) and
  440. (ref.volatility=[]);
  441. end;
  442. function InstrReadsFlags(p: tai): boolean;
  443. begin
  444. InstrReadsFlags := true;
  445. case p.typ of
  446. ait_instruction:
  447. if InsProp[taicpu(p).opcode].Ch*
  448. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  449. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  450. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  451. exit;
  452. ait_label:
  453. exit;
  454. else
  455. ;
  456. end;
  457. InstrReadsFlags := false;
  458. end;
  459. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  460. begin
  461. Next:=Current;
  462. repeat
  463. Result:=GetNextInstruction(Next,Next);
  464. until not (Result) or
  465. not(cs_opt_level3 in current_settings.optimizerswitches) or
  466. (Next.typ<>ait_instruction) or
  467. RegInInstruction(reg,Next) or
  468. is_calljmp(taicpu(Next).opcode);
  469. end;
  470. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  471. var
  472. GetNextResult: Boolean;
  473. begin
  474. Result:=0;
  475. Next:=Current;
  476. repeat
  477. GetNextResult := GetNextInstruction(Next,Next);
  478. if GetNextResult then
  479. Inc(Result)
  480. else
  481. { Must return zero upon hitting the end of the linked list without a match }
  482. Result := 0;
  483. until not (GetNextResult) or
  484. not(cs_opt_level3 in current_settings.optimizerswitches) or
  485. (Next.typ<>ait_instruction) or
  486. RegInInstruction(reg,Next) or
  487. is_calljmp(taicpu(Next).opcode);
  488. end;
  489. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  490. procedure TrackJump(Symbol: TAsmSymbol);
  491. var
  492. Search: TJumpTrackingItem;
  493. begin
  494. { See if an entry already exists in our jump tracking list
  495. (faster to search backwards due to the higher chance of
  496. matching destinations) }
  497. Search := TJumpTrackingItem(JumpTracking.Last);
  498. while Assigned(Search) do
  499. begin
  500. if Search.Symbol = Symbol then
  501. begin
  502. { Found it - remove it so it can be pushed to the front }
  503. JumpTracking.Remove(Search);
  504. Break;
  505. end;
  506. Search := TJumpTrackingItem(Search.Previous);
  507. end;
  508. if not Assigned(Search) then
  509. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  510. JumpTracking.Concat(Search);
  511. Search.IncRefs;
  512. end;
  513. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  514. var
  515. Search: TJumpTrackingItem;
  516. begin
  517. Result := False;
  518. { See if this label appears in the tracking list }
  519. Search := TJumpTrackingItem(JumpTracking.Last);
  520. while Assigned(Search) do
  521. begin
  522. if Search.Symbol = Symbol then
  523. begin
  524. { Found it - let's see what we can discover }
  525. if Search.Symbol.getrefs = Search.Refs then
  526. begin
  527. { Success - all the references are accounted for }
  528. JumpTracking.Remove(Search);
  529. Search.Free;
  530. { It is logically impossible for CrossJump to be false here
  531. because we must have run into a conditional jump for
  532. this label at some point }
  533. if not CrossJump then
  534. InternalError(2022041710);
  535. if JumpTracking.First = nil then
  536. { Tracking list is now empty - no more cross jumps }
  537. CrossJump := False;
  538. Result := True;
  539. Exit;
  540. end;
  541. { If the references don't match, it's possible to enter
  542. this label through other means, so drop out }
  543. Exit;
  544. end;
  545. Search := TJumpTrackingItem(Search.Previous);
  546. end;
  547. end;
  548. var
  549. Next_Label: tai;
  550. begin
  551. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  552. Next := Current;
  553. repeat
  554. Result := GetNextInstruction(Next,Next);
  555. if not Result then
  556. Break;
  557. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  558. if is_calljmpuncondret(taicpu(Next).opcode) then
  559. begin
  560. if (taicpu(Next).opcode = A_JMP) and
  561. { Remove dead code now to save time }
  562. RemoveDeadCodeAfterJump(taicpu(Next)) then
  563. { A jump was removed, but not the current instruction, and
  564. Result doesn't necessarily translate into an optimisation
  565. routine's Result, so use the "Force New Iteration" flag so
  566. mark a new pass }
  567. Include(OptsToCheck, aoc_ForceNewIteration);
  568. if not Assigned(JumpTracking) then
  569. begin
  570. { Cross-label optimisations often causes other optimisations
  571. to perform worse because they're not given the chance to
  572. optimise locally. In this case, don't do the cross-label
  573. optimisations yet, but flag them as a potential possibility
  574. for the next iteration of Pass 1 }
  575. if not NotFirstIteration then
  576. Include(OptsToCheck, aoc_ForceNewIteration);
  577. end
  578. else if IsJumpToLabel(taicpu(Next)) and
  579. GetNextInstruction(Next, Next_Label) then
  580. begin
  581. { If we have JMP .lbl, and the label after it has all of its
  582. references tracked, then this is probably an if-else style of
  583. block and we can keep tracking. If the label for this jump
  584. then appears later and is fully tracked, then it's the end
  585. of the if-else blocks and the code paths converge (thus
  586. marking the end of the cross-jump) }
  587. if (Next_Label.typ = ait_label) then
  588. begin
  589. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  590. begin
  591. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  592. Next := Next_Label;
  593. { CrossJump gets set to false by LabelAccountedFor if the
  594. list is completely emptied (as it indicates that all
  595. code paths have converged). We could avoid this nuance
  596. by moving the TrackJump call to before the
  597. LabelAccountedFor call, but this is slower in situations
  598. where LabelAccountedFor would return False due to the
  599. creation of a new object that is not used and destroyed
  600. soon after. }
  601. CrossJump := True;
  602. Continue;
  603. end;
  604. end
  605. else if (Next_Label.typ <> ait_marker) then
  606. { We just did a RemoveDeadCodeAfterJump, so either we find
  607. a label, the end of the procedure or some kind of marker}
  608. InternalError(2022041720);
  609. end;
  610. Result := False;
  611. Exit;
  612. end
  613. else
  614. begin
  615. if not Assigned(JumpTracking) then
  616. begin
  617. { Cross-label optimisations often causes other optimisations
  618. to perform worse because they're not given the chance to
  619. optimise locally. In this case, don't do the cross-label
  620. optimisations yet, but flag them as a potential possibility
  621. for the next iteration of Pass 1 }
  622. if not NotFirstIteration then
  623. Include(OptsToCheck, aoc_ForceNewIteration);
  624. end
  625. else if IsJumpToLabel(taicpu(Next)) then
  626. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  627. else
  628. { Conditional jumps should always be a jump to label }
  629. InternalError(2022041701);
  630. CrossJump := True;
  631. Continue;
  632. end;
  633. if Next.typ = ait_label then
  634. begin
  635. if not Assigned(JumpTracking) then
  636. begin
  637. { Cross-label optimisations often causes other optimisations
  638. to perform worse because they're not given the chance to
  639. optimise locally. In this case, don't do the cross-label
  640. optimisations yet, but flag them as a potential possibility
  641. for the next iteration of Pass 1 }
  642. if not NotFirstIteration then
  643. Include(OptsToCheck, aoc_ForceNewIteration);
  644. end
  645. else if LabelAccountedFor(tai_label(Next).labsym) then
  646. Continue;
  647. { If we reach here, we're at a label that hasn't been seen before
  648. (or JumpTracking was nil) }
  649. Break;
  650. end;
  651. until not Result or
  652. not (cs_opt_level3 in current_settings.optimizerswitches) or
  653. not (Next.typ in [ait_label, ait_instruction]) or
  654. RegInInstruction(reg,Next);
  655. end;
  656. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  657. begin
  658. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  659. begin
  660. Result:=GetNextInstruction(Current,Next);
  661. exit;
  662. end;
  663. Next:=tai(Current.Next);
  664. Result:=false;
  665. while assigned(Next) do
  666. begin
  667. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  668. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  669. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  670. exit
  671. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  672. begin
  673. Result:=true;
  674. exit;
  675. end;
  676. Next:=tai(Next.Next);
  677. end;
  678. end;
  679. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  680. begin
  681. Result:=RegReadByInstruction(reg,hp);
  682. end;
  683. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  684. var
  685. p: taicpu;
  686. opcount: longint;
  687. begin
  688. RegReadByInstruction := false;
  689. if hp.typ <> ait_instruction then
  690. exit;
  691. p := taicpu(hp);
  692. case p.opcode of
  693. A_CALL:
  694. regreadbyinstruction := true;
  695. A_IMUL:
  696. case p.ops of
  697. 1:
  698. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  699. (
  700. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  701. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  702. );
  703. 2,3:
  704. regReadByInstruction :=
  705. reginop(reg,p.oper[0]^) or
  706. reginop(reg,p.oper[1]^);
  707. else
  708. InternalError(2019112801);
  709. end;
  710. A_MUL:
  711. begin
  712. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  713. (
  714. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  715. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  716. );
  717. end;
  718. A_IDIV,A_DIV:
  719. begin
  720. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  721. (
  722. (getregtype(reg)=R_INTREGISTER) and
  723. (
  724. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  725. )
  726. );
  727. end;
  728. else
  729. begin
  730. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  731. begin
  732. RegReadByInstruction := false;
  733. exit;
  734. end;
  735. for opcount := 0 to p.ops-1 do
  736. if (p.oper[opCount]^.typ = top_ref) and
  737. RegInRef(reg,p.oper[opcount]^.ref^) then
  738. begin
  739. RegReadByInstruction := true;
  740. exit
  741. end;
  742. { special handling for SSE MOVSD }
  743. if (p.opcode=A_MOVSD) and (p.ops>0) then
  744. begin
  745. if p.ops<>2 then
  746. internalerror(2017042702);
  747. regReadByInstruction := reginop(reg,p.oper[0]^) or
  748. (
  749. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  750. );
  751. exit;
  752. end;
  753. with insprop[p.opcode] do
  754. begin
  755. case getregtype(reg) of
  756. R_INTREGISTER:
  757. begin
  758. case getsupreg(reg) of
  759. RS_EAX:
  760. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  761. begin
  762. RegReadByInstruction := true;
  763. exit
  764. end;
  765. RS_ECX:
  766. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  767. begin
  768. RegReadByInstruction := true;
  769. exit
  770. end;
  771. RS_EDX:
  772. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  773. begin
  774. RegReadByInstruction := true;
  775. exit
  776. end;
  777. RS_EBX:
  778. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  779. begin
  780. RegReadByInstruction := true;
  781. exit
  782. end;
  783. RS_ESP:
  784. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  785. begin
  786. RegReadByInstruction := true;
  787. exit
  788. end;
  789. RS_EBP:
  790. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  791. begin
  792. RegReadByInstruction := true;
  793. exit
  794. end;
  795. RS_ESI:
  796. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  797. begin
  798. RegReadByInstruction := true;
  799. exit
  800. end;
  801. RS_EDI:
  802. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  803. begin
  804. RegReadByInstruction := true;
  805. exit
  806. end;
  807. end;
  808. end;
  809. R_MMREGISTER:
  810. begin
  811. case getsupreg(reg) of
  812. RS_XMM0:
  813. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  814. begin
  815. RegReadByInstruction := true;
  816. exit
  817. end;
  818. end;
  819. end;
  820. else
  821. ;
  822. end;
  823. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  824. begin
  825. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  826. begin
  827. case p.condition of
  828. C_A,C_NBE, { CF=0 and ZF=0 }
  829. C_BE,C_NA: { CF=1 or ZF=1 }
  830. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  831. C_AE,C_NB,C_NC, { CF=0 }
  832. C_B,C_NAE,C_C: { CF=1 }
  833. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  834. C_NE,C_NZ, { ZF=0 }
  835. C_E,C_Z: { ZF=1 }
  836. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  837. C_G,C_NLE, { ZF=0 and SF=OF }
  838. C_LE,C_NG: { ZF=1 or SF<>OF }
  839. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  840. C_GE,C_NL, { SF=OF }
  841. C_L,C_NGE: { SF<>OF }
  842. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  843. C_NO, { OF=0 }
  844. C_O: { OF=1 }
  845. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  846. C_NP,C_PO, { PF=0 }
  847. C_P,C_PE: { PF=1 }
  848. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  849. C_NS, { SF=0 }
  850. C_S: { SF=1 }
  851. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  852. else
  853. internalerror(2017042701);
  854. end;
  855. if RegReadByInstruction then
  856. exit;
  857. end;
  858. case getsubreg(reg) of
  859. R_SUBW,R_SUBD,R_SUBQ:
  860. RegReadByInstruction :=
  861. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  862. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  863. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  864. R_SUBFLAGCARRY:
  865. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  866. R_SUBFLAGPARITY:
  867. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  868. R_SUBFLAGAUXILIARY:
  869. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  870. R_SUBFLAGZERO:
  871. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  872. R_SUBFLAGSIGN:
  873. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  874. R_SUBFLAGOVERFLOW:
  875. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  876. R_SUBFLAGINTERRUPT:
  877. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  878. R_SUBFLAGDIRECTION:
  879. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  880. else
  881. internalerror(2017042601);
  882. end;
  883. exit;
  884. end;
  885. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  886. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  887. (p.oper[0]^.reg=p.oper[1]^.reg) then
  888. exit;
  889. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  890. begin
  891. RegReadByInstruction := true;
  892. exit
  893. end;
  894. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  895. begin
  896. RegReadByInstruction := true;
  897. exit
  898. end;
  899. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  900. begin
  901. RegReadByInstruction := true;
  902. exit
  903. end;
  904. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  905. begin
  906. RegReadByInstruction := true;
  907. exit
  908. end;
  909. end;
  910. end;
  911. end;
  912. end;
  913. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  914. begin
  915. result:=false;
  916. if p1.typ<>ait_instruction then
  917. exit;
  918. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  919. exit(true);
  920. if (getregtype(reg)=R_INTREGISTER) and
  921. { change information for xmm movsd are not correct }
  922. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  923. begin
  924. { Handle instructions that behave differently depending on the size and operand count }
  925. case taicpu(p1).opcode of
  926. A_MUL, A_DIV, A_IDIV:
  927. if taicpu(p1).opsize = S_B then
  928. Result := (getsupreg(Reg) = RS_EAX)
  929. else
  930. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  931. A_IMUL:
  932. if taicpu(p1).ops = 1 then
  933. begin
  934. if taicpu(p1).opsize = S_B then
  935. Result := (getsupreg(Reg) = RS_EAX)
  936. else
  937. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  938. end;
  939. { If ops are greater than 1, call inherited method }
  940. else
  941. case getsupreg(reg) of
  942. { RS_EAX = RS_RAX on x86-64 }
  943. RS_EAX:
  944. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  945. RS_ECX:
  946. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  947. RS_EDX:
  948. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  949. RS_EBX:
  950. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  951. RS_ESP:
  952. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  953. RS_EBP:
  954. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  955. RS_ESI:
  956. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  957. RS_EDI:
  958. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  959. else
  960. ;
  961. end;
  962. end;
  963. if result then
  964. exit;
  965. end
  966. else if getregtype(reg)=R_MMREGISTER then
  967. begin
  968. case getsupreg(reg) of
  969. RS_XMM0:
  970. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  971. else
  972. ;
  973. end;
  974. if result then
  975. exit;
  976. end
  977. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  978. begin
  979. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  980. exit(true);
  981. case getsubreg(reg) of
  982. R_SUBFLAGCARRY:
  983. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  984. R_SUBFLAGPARITY:
  985. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  986. R_SUBFLAGAUXILIARY:
  987. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  988. R_SUBFLAGZERO:
  989. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  990. R_SUBFLAGSIGN:
  991. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  992. R_SUBFLAGOVERFLOW:
  993. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  994. R_SUBFLAGINTERRUPT:
  995. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  996. R_SUBFLAGDIRECTION:
  997. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  998. R_SUBW,R_SUBD,R_SUBQ:
  999. { Everything except the direction bits }
  1000. Result:=
  1001. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  1002. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1003. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1004. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1005. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1006. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  1007. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  1008. else
  1009. ;
  1010. end;
  1011. if result then
  1012. exit;
  1013. end
  1014. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  1015. exit(true);
  1016. Result:=inherited RegInInstruction(Reg, p1);
  1017. end;
  1018. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1019. const
  1020. WriteOps: array[0..3] of set of TInsChange =
  1021. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1022. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1023. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1024. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1025. var
  1026. OperIdx: Integer;
  1027. begin
  1028. Result := False;
  1029. if p1.typ <> ait_instruction then
  1030. exit;
  1031. with insprop[taicpu(p1).opcode] do
  1032. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1033. begin
  1034. case getsubreg(reg) of
  1035. R_SUBW,R_SUBD,R_SUBQ:
  1036. Result :=
  1037. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1038. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1039. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1040. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1041. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1042. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1043. R_SUBFLAGCARRY:
  1044. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1045. R_SUBFLAGPARITY:
  1046. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1047. R_SUBFLAGAUXILIARY:
  1048. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1049. R_SUBFLAGZERO:
  1050. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1051. R_SUBFLAGSIGN:
  1052. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1053. R_SUBFLAGOVERFLOW:
  1054. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1055. R_SUBFLAGINTERRUPT:
  1056. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1057. R_SUBFLAGDIRECTION:
  1058. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1059. else
  1060. internalerror(2017042602);
  1061. end;
  1062. exit;
  1063. end;
  1064. case taicpu(p1).opcode of
  1065. A_CALL:
  1066. { We could potentially set Result to False if the register in
  1067. question is non-volatile for the subroutine's calling convention,
  1068. but this would require detecting the calling convention in use and
  1069. also assuming that the routine doesn't contain malformed assembly
  1070. language, for example... so it could only be done under -O4 as it
  1071. would be considered a side-effect. [Kit] }
  1072. Result := True;
  1073. A_MOVSD:
  1074. { special handling for SSE MOVSD }
  1075. if (taicpu(p1).ops>0) then
  1076. begin
  1077. if taicpu(p1).ops<>2 then
  1078. internalerror(2017042703);
  1079. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1080. end;
  1081. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1082. so fix it here (FK)
  1083. }
  1084. A_VMOVSS,
  1085. A_VMOVSD:
  1086. begin
  1087. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1088. exit;
  1089. end;
  1090. A_MUL, A_DIV, A_IDIV:
  1091. begin
  1092. if taicpu(p1).opsize = S_B then
  1093. Result := (getsupreg(Reg) = RS_EAX)
  1094. else
  1095. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1096. end;
  1097. A_IMUL:
  1098. begin
  1099. if taicpu(p1).ops = 1 then
  1100. begin
  1101. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1102. end
  1103. else
  1104. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1105. Exit;
  1106. end;
  1107. else
  1108. ;
  1109. end;
  1110. if Result then
  1111. exit;
  1112. with insprop[taicpu(p1).opcode] do
  1113. begin
  1114. if getregtype(reg)=R_INTREGISTER then
  1115. begin
  1116. case getsupreg(reg) of
  1117. RS_EAX:
  1118. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1119. begin
  1120. Result := True;
  1121. exit
  1122. end;
  1123. RS_ECX:
  1124. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1125. begin
  1126. Result := True;
  1127. exit
  1128. end;
  1129. RS_EDX:
  1130. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1131. begin
  1132. Result := True;
  1133. exit
  1134. end;
  1135. RS_EBX:
  1136. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1137. begin
  1138. Result := True;
  1139. exit
  1140. end;
  1141. RS_ESP:
  1142. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1143. begin
  1144. Result := True;
  1145. exit
  1146. end;
  1147. RS_EBP:
  1148. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1149. begin
  1150. Result := True;
  1151. exit
  1152. end;
  1153. RS_ESI:
  1154. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1155. begin
  1156. Result := True;
  1157. exit
  1158. end;
  1159. RS_EDI:
  1160. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1161. begin
  1162. Result := True;
  1163. exit
  1164. end;
  1165. end;
  1166. end;
  1167. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1168. if (WriteOps[OperIdx]*Ch<>[]) and
  1169. { The register doesn't get modified inside a reference }
  1170. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1171. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1172. begin
  1173. Result := true;
  1174. exit
  1175. end;
  1176. end;
  1177. end;
  1178. function TX86AsmOptimizer.RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  1179. const
  1180. WriteOps: array[0..3] of set of TInsChange =
  1181. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1182. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1183. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1184. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1185. var
  1186. X: Integer;
  1187. CurrentP1Size: asizeint;
  1188. begin
  1189. Result := (
  1190. (Ref.base <> NR_NO) and
  1191. {$ifdef x86_64}
  1192. (Ref.base <> NR_RIP) and
  1193. {$endif x86_64}
  1194. RegModifiedBetween(Ref.base, p1, p2)
  1195. ) or
  1196. (
  1197. (Ref.index <> NR_NO) and
  1198. (Ref.index <> Ref.base) and
  1199. RegModifiedBetween(Ref.index, p1, p2)
  1200. );
  1201. { Now check to see if the memory itself is written to }
  1202. if not Result then
  1203. begin
  1204. while assigned(p1) and assigned(p2) and GetNextInstruction(p1,p1) and (p1<>p2) do
  1205. if p1.typ = ait_instruction then
  1206. begin
  1207. CurrentP1Size := topsize2memsize[taicpu(p1).opsize] shr 3; { Convert to bytes }
  1208. with insprop[taicpu(p1).opcode] do
  1209. for X := 0 to taicpu(p1).ops - 1 do
  1210. if (taicpu(p1).oper[X]^.typ = top_ref) and
  1211. RefsAlmostEqual(Ref, taicpu(p1).oper[X]^.ref^) and
  1212. { Catch any potential overlaps }
  1213. (
  1214. (RefSize = 0) or
  1215. ((taicpu(p1).oper[X]^.ref^.offset - Ref.offset) < RefSize)
  1216. ) and
  1217. (
  1218. (CurrentP1Size = 0) or
  1219. ((Ref.offset - taicpu(p1).oper[X]^.ref^.offset) < CurrentP1Size)
  1220. ) and
  1221. { Reference is used, but does the instruction write to it? }
  1222. (
  1223. (Ch_All in Ch) or
  1224. ((WriteOps[X] * Ch) <> [])
  1225. ) then
  1226. begin
  1227. Result := True;
  1228. Break;
  1229. end;
  1230. end;
  1231. end;
  1232. end;
  1233. {$ifdef DEBUG_AOPTCPU}
  1234. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1235. begin
  1236. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1237. end;
  1238. function debug_tostr(i: tcgint): string; inline;
  1239. begin
  1240. Result := tostr(i);
  1241. end;
  1242. function debug_hexstr(i: tcgint): string;
  1243. begin
  1244. Result := '0x';
  1245. case i of
  1246. 0..$FF:
  1247. Result := Result + hexstr(i, 2);
  1248. $100..$FFFF:
  1249. Result := Result + hexstr(i, 4);
  1250. $10000..$FFFFFF:
  1251. Result := Result + hexstr(i, 6);
  1252. $1000000..$FFFFFFFF:
  1253. Result := Result + hexstr(i, 8);
  1254. else
  1255. Result := Result + hexstr(i, 16);
  1256. end;
  1257. end;
  1258. function debug_regname(r: TRegister): string; inline;
  1259. begin
  1260. Result := '%' + std_regname(r);
  1261. end;
  1262. { Debug output function - creates a string representation of an operator }
  1263. function debug_operstr(oper: TOper): string;
  1264. begin
  1265. case oper.typ of
  1266. top_const:
  1267. Result := '$' + debug_tostr(oper.val);
  1268. top_reg:
  1269. Result := debug_regname(oper.reg);
  1270. top_ref:
  1271. begin
  1272. if oper.ref^.offset <> 0 then
  1273. Result := debug_tostr(oper.ref^.offset) + '('
  1274. else
  1275. Result := '(';
  1276. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1277. begin
  1278. Result := Result + debug_regname(oper.ref^.base);
  1279. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1280. Result := Result + ',' + debug_regname(oper.ref^.index);
  1281. end
  1282. else
  1283. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1284. Result := Result + debug_regname(oper.ref^.index);
  1285. if (oper.ref^.scalefactor > 1) then
  1286. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1287. else
  1288. Result := Result + ')';
  1289. end;
  1290. else
  1291. Result := '[UNKNOWN]';
  1292. end;
  1293. end;
  1294. function debug_op2str(opcode: tasmop): string; inline;
  1295. begin
  1296. Result := std_op2str[opcode];
  1297. end;
  1298. function debug_opsize2str(opsize: topsize): string; inline;
  1299. begin
  1300. Result := gas_opsize2str[opsize];
  1301. end;
  1302. {$else DEBUG_AOPTCPU}
  1303. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1304. begin
  1305. end;
  1306. function debug_tostr(i: tcgint): string; inline;
  1307. begin
  1308. Result := '';
  1309. end;
  1310. function debug_hexstr(i: tcgint): string; inline;
  1311. begin
  1312. Result := '';
  1313. end;
  1314. function debug_regname(r: TRegister): string; inline;
  1315. begin
  1316. Result := '';
  1317. end;
  1318. function debug_operstr(oper: TOper): string; inline;
  1319. begin
  1320. Result := '';
  1321. end;
  1322. function debug_op2str(opcode: tasmop): string; inline;
  1323. begin
  1324. Result := '';
  1325. end;
  1326. function debug_opsize2str(opsize: topsize): string; inline;
  1327. begin
  1328. Result := '';
  1329. end;
  1330. {$endif DEBUG_AOPTCPU}
  1331. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1332. begin
  1333. {$ifdef x86_64}
  1334. { Always fine on x86-64 }
  1335. Result := True;
  1336. {$else x86_64}
  1337. Result :=
  1338. {$ifdef i8086}
  1339. (current_settings.cputype >= cpu_386) and
  1340. {$endif i8086}
  1341. (
  1342. { Always accept if optimising for size }
  1343. (cs_opt_size in current_settings.optimizerswitches) or
  1344. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1345. (current_settings.optimizecputype >= cpu_Pentium2)
  1346. );
  1347. {$endif x86_64}
  1348. end;
  1349. { Attempts to allocate a volatile integer 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.GetIntRegisterBetween(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_int(current_procinfo.procdef.proccalloption) +
  1363. current_procinfo.saved_regs_int;
  1364. (*
  1365. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1366. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1367. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1368. *)
  1369. for CurrentSuperReg in RegSet do
  1370. begin
  1371. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1372. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1373. {$if defined(i386) or defined(i8086)}
  1374. { If the target size is 8-bit, make sure we can actually encode it }
  1375. and (
  1376. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1377. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1378. )
  1379. {$endif i386 or i8086}
  1380. then
  1381. begin
  1382. Currentp := p;
  1383. Breakout := False;
  1384. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1385. begin
  1386. case Currentp.typ of
  1387. ait_instruction:
  1388. begin
  1389. if RegInInstruction(CurrentReg, Currentp) then
  1390. begin
  1391. Breakout := True;
  1392. Break;
  1393. end;
  1394. { Cannot allocate across an unconditional jump }
  1395. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1396. Exit;
  1397. end;
  1398. ait_marker:
  1399. { Don't try anything more if a marker is hit }
  1400. Exit;
  1401. ait_regalloc:
  1402. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1403. begin
  1404. Breakout := True;
  1405. Break;
  1406. end;
  1407. else
  1408. ;
  1409. end;
  1410. end;
  1411. if Breakout then
  1412. { Try the next register }
  1413. Continue;
  1414. { We have a free register available }
  1415. Result := CurrentReg;
  1416. if not DontAlloc then
  1417. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1418. Exit;
  1419. end;
  1420. end;
  1421. end;
  1422. { Attempts to allocate a volatile MM register for use between p and hp,
  1423. using AUsedRegs for the current register usage information. Returns NR_NO
  1424. if no free register could be found }
  1425. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1426. var
  1427. RegSet: TCPURegisterSet;
  1428. CurrentSuperReg: Integer;
  1429. CurrentReg: TRegister;
  1430. Currentp: tai;
  1431. Breakout: Boolean;
  1432. begin
  1433. Result := NR_NO;
  1434. RegSet :=
  1435. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1436. current_procinfo.saved_regs_mm;
  1437. for CurrentSuperReg in RegSet do
  1438. begin
  1439. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1440. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1441. begin
  1442. Currentp := p;
  1443. Breakout := False;
  1444. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1445. begin
  1446. case Currentp.typ of
  1447. ait_instruction:
  1448. begin
  1449. if RegInInstruction(CurrentReg, Currentp) then
  1450. begin
  1451. Breakout := True;
  1452. Break;
  1453. end;
  1454. { Cannot allocate across an unconditional jump }
  1455. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1456. Exit;
  1457. end;
  1458. ait_marker:
  1459. { Don't try anything more if a marker is hit }
  1460. Exit;
  1461. ait_regalloc:
  1462. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1463. begin
  1464. Breakout := True;
  1465. Break;
  1466. end;
  1467. else
  1468. ;
  1469. end;
  1470. end;
  1471. if Breakout then
  1472. { Try the next register }
  1473. Continue;
  1474. { We have a free register available }
  1475. Result := CurrentReg;
  1476. if not DontAlloc then
  1477. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1478. Exit;
  1479. end;
  1480. end;
  1481. end;
  1482. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1483. begin
  1484. if not SuperRegistersEqual(reg1,reg2) then
  1485. exit(false);
  1486. if getregtype(reg1)<>R_INTREGISTER then
  1487. exit(true); {because SuperRegisterEqual is true}
  1488. case getsubreg(reg1) of
  1489. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1490. higher, it preserves the high bits, so the new value depends on
  1491. reg2's previous value. In other words, it is equivalent to doing:
  1492. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1493. R_SUBL:
  1494. exit(getsubreg(reg2)=R_SUBL);
  1495. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1496. higher, it actually does a:
  1497. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1498. R_SUBH:
  1499. exit(getsubreg(reg2)=R_SUBH);
  1500. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1501. bits of reg2:
  1502. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1503. R_SUBW:
  1504. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1505. { a write to R_SUBD always overwrites every other subregister,
  1506. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1507. R_SUBD,
  1508. R_SUBQ:
  1509. exit(true);
  1510. else
  1511. internalerror(2017042801);
  1512. end;
  1513. end;
  1514. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1515. begin
  1516. if not SuperRegistersEqual(reg1,reg2) then
  1517. exit(false);
  1518. if getregtype(reg1)<>R_INTREGISTER then
  1519. exit(true); {because SuperRegisterEqual is true}
  1520. case getsubreg(reg1) of
  1521. R_SUBL:
  1522. exit(getsubreg(reg2)<>R_SUBH);
  1523. R_SUBH:
  1524. exit(getsubreg(reg2)<>R_SUBL);
  1525. R_SUBW,
  1526. R_SUBD,
  1527. R_SUBQ:
  1528. exit(true);
  1529. else
  1530. internalerror(2017042802);
  1531. end;
  1532. end;
  1533. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1534. var
  1535. hp1 : tai;
  1536. l : TCGInt;
  1537. begin
  1538. result:=false;
  1539. if not(GetNextInstruction(p, hp1)) then
  1540. exit;
  1541. { changes the code sequence
  1542. shr/sar const1, x
  1543. shl const2, x
  1544. to
  1545. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1546. if (taicpu(p).oper[0]^.typ = top_const) and
  1547. MatchInstruction(hp1,A_SHL,[]) and
  1548. (taicpu(hp1).oper[0]^.typ = top_const) and
  1549. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1550. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1551. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1552. begin
  1553. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1554. not(cs_opt_size in current_settings.optimizerswitches) then
  1555. begin
  1556. { shr/sar const1, %reg
  1557. shl const2, %reg
  1558. with const1 > const2 }
  1559. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1560. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1561. taicpu(hp1).opcode := A_AND;
  1562. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1563. case taicpu(p).opsize Of
  1564. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1565. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1566. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1567. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1568. else
  1569. Internalerror(2017050703)
  1570. end;
  1571. end
  1572. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1573. not(cs_opt_size in current_settings.optimizerswitches) then
  1574. begin
  1575. { shr/sar const1, %reg
  1576. shl const2, %reg
  1577. with const1 < const2 }
  1578. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1579. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1580. taicpu(p).opcode := A_AND;
  1581. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1582. case taicpu(p).opsize Of
  1583. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1584. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1585. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1586. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1587. else
  1588. Internalerror(2017050702)
  1589. end;
  1590. end
  1591. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1592. begin
  1593. { shr/sar const1, %reg
  1594. shl const2, %reg
  1595. with const1 = const2 }
  1596. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1597. taicpu(p).opcode := A_AND;
  1598. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1599. case taicpu(p).opsize Of
  1600. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1601. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1602. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1603. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1604. else
  1605. Internalerror(2017050701)
  1606. end;
  1607. RemoveInstruction(hp1);
  1608. end;
  1609. end;
  1610. end;
  1611. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1612. var
  1613. opsize : topsize;
  1614. hp1, hp2 : tai;
  1615. tmpref : treference;
  1616. ShiftValue : Cardinal;
  1617. BaseValue : TCGInt;
  1618. begin
  1619. result:=false;
  1620. opsize:=taicpu(p).opsize;
  1621. { changes certain "imul const, %reg"'s to lea sequences }
  1622. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1623. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1624. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1625. if (taicpu(p).oper[0]^.val = 1) then
  1626. if (taicpu(p).ops = 2) then
  1627. { remove "imul $1, reg" }
  1628. begin
  1629. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1630. Result := RemoveCurrentP(p);
  1631. end
  1632. else
  1633. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1634. begin
  1635. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1636. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1637. asml.InsertAfter(hp1, p);
  1638. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1639. RemoveCurrentP(p, hp1);
  1640. Result := True;
  1641. end
  1642. else if ((taicpu(p).ops <= 2) or
  1643. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1644. not(cs_opt_size in current_settings.optimizerswitches) and
  1645. (not(GetNextInstruction(p, hp1)) or
  1646. not((tai(hp1).typ = ait_instruction) and
  1647. ((taicpu(hp1).opcode=A_Jcc) and
  1648. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1649. begin
  1650. {
  1651. imul X, reg1, reg2 to
  1652. lea (reg1,reg1,Y), reg2
  1653. shl ZZ,reg2
  1654. imul XX, reg1 to
  1655. lea (reg1,reg1,YY), reg1
  1656. shl ZZ,reg2
  1657. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1658. it does not exist as a separate optimization target in FPC though.
  1659. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1660. at most two zeros
  1661. }
  1662. reference_reset(tmpref,1,[]);
  1663. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1664. begin
  1665. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1666. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1667. TmpRef.base := taicpu(p).oper[1]^.reg;
  1668. TmpRef.index := taicpu(p).oper[1]^.reg;
  1669. if not(BaseValue in [3,5,9]) then
  1670. Internalerror(2018110101);
  1671. TmpRef.ScaleFactor := BaseValue-1;
  1672. if (taicpu(p).ops = 2) then
  1673. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1674. else
  1675. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1676. AsmL.InsertAfter(hp1,p);
  1677. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1678. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1679. RemoveCurrentP(p, hp1);
  1680. if ShiftValue>0 then
  1681. begin
  1682. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1683. AsmL.InsertAfter(hp2,hp1);
  1684. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1685. end;
  1686. Result := True;
  1687. end;
  1688. end;
  1689. end;
  1690. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1691. begin
  1692. Result := False;
  1693. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1694. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1695. begin
  1696. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1697. taicpu(p).opcode := A_MOV;
  1698. Result := True;
  1699. end;
  1700. end;
  1701. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1702. var
  1703. p: taicpu absolute hp; { Implicit typecast }
  1704. i: Integer;
  1705. begin
  1706. Result := False;
  1707. if not assigned(hp) or
  1708. (hp.typ <> ait_instruction) then
  1709. Exit;
  1710. Prefetch(insprop[p.opcode]);
  1711. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1712. with insprop[p.opcode] do
  1713. begin
  1714. case getsubreg(reg) of
  1715. R_SUBW,R_SUBD,R_SUBQ:
  1716. Result:=
  1717. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1718. uncommon flags are checked first }
  1719. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1720. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1721. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1722. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1723. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1724. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1725. R_SUBFLAGCARRY:
  1726. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1727. R_SUBFLAGPARITY:
  1728. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1729. R_SUBFLAGAUXILIARY:
  1730. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1731. R_SUBFLAGZERO:
  1732. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1733. R_SUBFLAGSIGN:
  1734. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1735. R_SUBFLAGOVERFLOW:
  1736. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1737. R_SUBFLAGINTERRUPT:
  1738. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1739. R_SUBFLAGDIRECTION:
  1740. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1741. else
  1742. internalerror(2017050501);
  1743. end;
  1744. exit;
  1745. end;
  1746. { Handle special cases first }
  1747. case p.opcode of
  1748. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1749. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1750. begin
  1751. Result :=
  1752. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1753. (p.oper[1]^.typ = top_reg) and
  1754. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1755. (
  1756. (p.oper[0]^.typ = top_const) or
  1757. (
  1758. (p.oper[0]^.typ = top_reg) and
  1759. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1760. ) or (
  1761. (p.oper[0]^.typ = top_ref) and
  1762. not RegInRef(reg,p.oper[0]^.ref^)
  1763. )
  1764. );
  1765. end;
  1766. A_MUL, A_IMUL:
  1767. Result :=
  1768. (
  1769. (p.ops=3) and { IMUL only }
  1770. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1771. (
  1772. (
  1773. (p.oper[1]^.typ=top_reg) and
  1774. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1775. ) or (
  1776. (p.oper[1]^.typ=top_ref) and
  1777. not RegInRef(reg,p.oper[1]^.ref^)
  1778. )
  1779. )
  1780. ) or (
  1781. (
  1782. (p.ops=1) and
  1783. (
  1784. (
  1785. (
  1786. (p.oper[0]^.typ=top_reg) and
  1787. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1788. )
  1789. ) or (
  1790. (p.oper[0]^.typ=top_ref) and
  1791. not RegInRef(reg,p.oper[0]^.ref^)
  1792. )
  1793. ) and (
  1794. (
  1795. (p.opsize=S_B) and
  1796. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1797. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1798. ) or (
  1799. (p.opsize=S_W) and
  1800. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1801. ) or (
  1802. (p.opsize=S_L) and
  1803. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1804. {$ifdef x86_64}
  1805. ) or (
  1806. (p.opsize=S_Q) and
  1807. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1808. {$endif x86_64}
  1809. )
  1810. )
  1811. )
  1812. );
  1813. A_CBW:
  1814. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1815. {$ifndef x86_64}
  1816. A_LDS:
  1817. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1818. A_LES:
  1819. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1820. {$endif not x86_64}
  1821. A_LFS:
  1822. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1823. A_LGS:
  1824. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1825. A_LSS:
  1826. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1827. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1828. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1829. A_LODSB:
  1830. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1831. A_LODSW:
  1832. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1833. {$ifdef x86_64}
  1834. A_LODSQ:
  1835. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1836. {$endif x86_64}
  1837. A_LODSD:
  1838. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1839. A_FSTSW, A_FNSTSW:
  1840. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1841. else
  1842. begin
  1843. with insprop[p.opcode] do
  1844. begin
  1845. if (
  1846. { xor %reg,%reg etc. is classed as a new value }
  1847. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1848. MatchOpType(p, top_reg, top_reg) and
  1849. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1850. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1851. ) then
  1852. begin
  1853. Result := True;
  1854. Exit;
  1855. end;
  1856. { Make sure the entire register is overwritten }
  1857. if (getregtype(reg) = R_INTREGISTER) then
  1858. begin
  1859. if (p.ops > 0) then
  1860. begin
  1861. if RegInOp(reg, p.oper[0]^) then
  1862. begin
  1863. if (p.oper[0]^.typ = top_ref) then
  1864. begin
  1865. if RegInRef(reg, p.oper[0]^.ref^) then
  1866. begin
  1867. Result := False;
  1868. Exit;
  1869. end;
  1870. end
  1871. else if (p.oper[0]^.typ = top_reg) then
  1872. begin
  1873. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1874. begin
  1875. Result := False;
  1876. Exit;
  1877. end
  1878. else if ([Ch_WOp1]*Ch<>[]) then
  1879. begin
  1880. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1881. Result := True
  1882. else
  1883. begin
  1884. Result := False;
  1885. Exit;
  1886. end;
  1887. end;
  1888. end;
  1889. end;
  1890. if (p.ops > 1) then
  1891. begin
  1892. if RegInOp(reg, p.oper[1]^) then
  1893. begin
  1894. if (p.oper[1]^.typ = top_ref) then
  1895. begin
  1896. if RegInRef(reg, p.oper[1]^.ref^) then
  1897. begin
  1898. Result := False;
  1899. Exit;
  1900. end;
  1901. end
  1902. else if (p.oper[1]^.typ = top_reg) then
  1903. begin
  1904. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1905. begin
  1906. Result := False;
  1907. Exit;
  1908. end
  1909. else if ([Ch_WOp2]*Ch<>[]) then
  1910. begin
  1911. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1912. Result := True
  1913. else
  1914. begin
  1915. Result := False;
  1916. Exit;
  1917. end;
  1918. end;
  1919. end;
  1920. end;
  1921. if (p.ops > 2) then
  1922. begin
  1923. if RegInOp(reg, p.oper[2]^) then
  1924. begin
  1925. if (p.oper[2]^.typ = top_ref) then
  1926. begin
  1927. if RegInRef(reg, p.oper[2]^.ref^) then
  1928. begin
  1929. Result := False;
  1930. Exit;
  1931. end;
  1932. end
  1933. else if (p.oper[2]^.typ = top_reg) then
  1934. begin
  1935. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1936. begin
  1937. Result := False;
  1938. Exit;
  1939. end
  1940. else if ([Ch_WOp3]*Ch<>[]) then
  1941. begin
  1942. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1943. Result := True
  1944. else
  1945. begin
  1946. Result := False;
  1947. Exit;
  1948. end;
  1949. end;
  1950. end;
  1951. end;
  1952. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1953. begin
  1954. if (p.oper[3]^.typ = top_ref) then
  1955. begin
  1956. if RegInRef(reg, p.oper[3]^.ref^) then
  1957. begin
  1958. Result := False;
  1959. Exit;
  1960. end;
  1961. end
  1962. else if (p.oper[3]^.typ = top_reg) then
  1963. begin
  1964. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1965. begin
  1966. Result := False;
  1967. Exit;
  1968. end
  1969. else if ([Ch_WOp4]*Ch<>[]) then
  1970. begin
  1971. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1972. Result := True
  1973. else
  1974. begin
  1975. Result := False;
  1976. Exit;
  1977. end;
  1978. end;
  1979. end;
  1980. end;
  1981. end;
  1982. end;
  1983. end;
  1984. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1985. case getsupreg(reg) of
  1986. RS_EAX:
  1987. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1988. begin
  1989. Result := True;
  1990. Exit;
  1991. end;
  1992. RS_ECX:
  1993. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1994. begin
  1995. Result := True;
  1996. Exit;
  1997. end;
  1998. RS_EDX:
  1999. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  2000. begin
  2001. Result := True;
  2002. Exit;
  2003. end;
  2004. RS_EBX:
  2005. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  2006. begin
  2007. Result := True;
  2008. Exit;
  2009. end;
  2010. RS_ESP:
  2011. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  2012. begin
  2013. Result := True;
  2014. Exit;
  2015. end;
  2016. RS_EBP:
  2017. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  2018. begin
  2019. Result := True;
  2020. Exit;
  2021. end;
  2022. RS_ESI:
  2023. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  2024. begin
  2025. Result := True;
  2026. Exit;
  2027. end;
  2028. RS_EDI:
  2029. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  2030. begin
  2031. Result := True;
  2032. Exit;
  2033. end;
  2034. else
  2035. ;
  2036. end;
  2037. end;
  2038. end;
  2039. end;
  2040. end;
  2041. end;
  2042. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  2043. var
  2044. hp2,hp3 : tai;
  2045. begin
  2046. { some x86-64 issue a NOP before the real exit code }
  2047. if MatchInstruction(p,A_NOP,[]) then
  2048. GetNextInstruction(p,p);
  2049. result:=assigned(p) and (p.typ=ait_instruction) and
  2050. ((taicpu(p).opcode = A_RET) or
  2051. ((taicpu(p).opcode=A_LEAVE) and
  2052. GetNextInstruction(p,hp2) and
  2053. MatchInstruction(hp2,A_RET,[S_NO])
  2054. ) or
  2055. (((taicpu(p).opcode=A_LEA) and
  2056. MatchOpType(taicpu(p),top_ref,top_reg) and
  2057. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  2058. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2059. ) and
  2060. GetNextInstruction(p,hp2) and
  2061. MatchInstruction(hp2,A_RET,[S_NO])
  2062. ) or
  2063. ((((taicpu(p).opcode=A_MOV) and
  2064. MatchOpType(taicpu(p),top_reg,top_reg) and
  2065. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  2066. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  2067. ((taicpu(p).opcode=A_LEA) and
  2068. MatchOpType(taicpu(p),top_ref,top_reg) and
  2069. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  2070. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2071. )
  2072. ) and
  2073. GetNextInstruction(p,hp2) and
  2074. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2075. MatchOpType(taicpu(hp2),top_reg) and
  2076. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2077. GetNextInstruction(hp2,hp3) and
  2078. MatchInstruction(hp3,A_RET,[S_NO])
  2079. )
  2080. );
  2081. end;
  2082. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2083. begin
  2084. isFoldableArithOp := False;
  2085. case hp1.opcode of
  2086. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2087. isFoldableArithOp :=
  2088. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2089. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2090. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2091. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2092. (taicpu(hp1).oper[1]^.reg = reg);
  2093. A_INC,A_DEC,A_NEG,A_NOT:
  2094. isFoldableArithOp :=
  2095. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2096. (taicpu(hp1).oper[0]^.reg = reg);
  2097. else
  2098. ;
  2099. end;
  2100. end;
  2101. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2102. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2103. var
  2104. hp2: tai;
  2105. begin
  2106. hp2 := p;
  2107. repeat
  2108. hp2 := tai(hp2.previous);
  2109. if assigned(hp2) and
  2110. (hp2.typ = ait_regalloc) and
  2111. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2112. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2113. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2114. begin
  2115. RemoveInstruction(hp2);
  2116. break;
  2117. end;
  2118. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2119. end;
  2120. begin
  2121. case current_procinfo.procdef.returndef.typ of
  2122. arraydef,recorddef,pointerdef,
  2123. stringdef,enumdef,procdef,objectdef,errordef,
  2124. filedef,setdef,procvardef,
  2125. classrefdef,forwarddef:
  2126. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2127. orddef:
  2128. if current_procinfo.procdef.returndef.size <> 0 then
  2129. begin
  2130. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2131. { for int64/qword }
  2132. if current_procinfo.procdef.returndef.size = 8 then
  2133. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2134. end;
  2135. else
  2136. ;
  2137. end;
  2138. end;
  2139. function TX86AsmOptimizer.OptPass1CMOVcc(var p: tai): Boolean;
  2140. var
  2141. hp1: tai;
  2142. operswap: poper;
  2143. begin
  2144. Result := False;
  2145. { Optimise:
  2146. cmov(c) %reg1,%reg2
  2147. mov %reg2,%reg1
  2148. (%reg2 dealloc.)
  2149. To:
  2150. cmov(~c) %reg2,%reg1
  2151. }
  2152. if (taicpu(p).oper[0]^.typ = top_reg) then
  2153. while GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) and
  2154. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  2155. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  2156. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[0]^.reg) do
  2157. begin
  2158. TransferUsedRegs(TmpUsedRegs);
  2159. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2160. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2161. begin
  2162. DebugMsg(SPeepholeOptimization + 'CMOV(c) %reg1,%reg2; MOV %reg2,%reg1 -> CMOV(~c) %reg2,%reg1 (CMovMov2CMov)', p);
  2163. { Save time by swapping the pointers (they're both registers, so
  2164. we don't need to worry about reference counts) }
  2165. operswap := taicpu(p).oper[0];
  2166. taicpu(p).oper[0] := taicpu(p).oper[1];
  2167. taicpu(p).oper[1] := operswap;
  2168. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  2169. RemoveInstruction(hp1);
  2170. { It's still a CMOV, so we can look further ahead }
  2171. Include(OptsToCheck, aoc_ForceNewIteration);
  2172. { But first, let's see if this will get optimised again
  2173. (probably won't happen, but best to be sure) }
  2174. Continue;
  2175. end;
  2176. Break;
  2177. end;
  2178. end;
  2179. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2180. var
  2181. hp1,hp2 : tai;
  2182. begin
  2183. result:=false;
  2184. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2185. begin
  2186. { vmova* reg1,reg1
  2187. =>
  2188. <nop> }
  2189. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2190. begin
  2191. RemoveCurrentP(p);
  2192. result:=true;
  2193. exit;
  2194. end;
  2195. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2196. (hp1.typ = ait_instruction) and
  2197. (
  2198. { Under -O2 and below, the instructions are always adjacent }
  2199. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2200. (taicpu(hp1).ops <= 1) or
  2201. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2202. { If reg1 = reg3, reg1 must not be modified in between }
  2203. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2204. ) then
  2205. begin
  2206. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2207. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2208. begin
  2209. { vmova* reg1,reg2
  2210. ...
  2211. vmova* reg2,reg3
  2212. dealloc reg2
  2213. =>
  2214. vmova* reg1,reg3 }
  2215. TransferUsedRegs(TmpUsedRegs);
  2216. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2217. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2218. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2219. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2220. begin
  2221. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2222. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2223. TransferUsedRegs(TmpUsedRegs);
  2224. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2225. RemoveInstruction(hp1);
  2226. result:=true;
  2227. exit;
  2228. end;
  2229. { special case:
  2230. vmova* reg1,<op>
  2231. ...
  2232. vmova* <op>,reg1
  2233. =>
  2234. vmova* reg1,<op> }
  2235. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2236. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2237. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2238. ) then
  2239. begin
  2240. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2241. RemoveInstruction(hp1);
  2242. result:=true;
  2243. exit;
  2244. end
  2245. end
  2246. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2247. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2248. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2249. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2250. ) and
  2251. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2252. begin
  2253. { vmova* reg1,reg2
  2254. ...
  2255. vmovs* reg2,<op>
  2256. dealloc reg2
  2257. =>
  2258. vmovs* reg1,<op> }
  2259. TransferUsedRegs(TmpUsedRegs);
  2260. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2261. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2262. begin
  2263. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2264. taicpu(p).opcode:=taicpu(hp1).opcode;
  2265. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2266. TransferUsedRegs(TmpUsedRegs);
  2267. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2268. RemoveInstruction(hp1);
  2269. result:=true;
  2270. exit;
  2271. end
  2272. end;
  2273. if MatchInstruction(hp1,[A_VFMADDPD,
  2274. A_VFMADD132PD,
  2275. A_VFMADD132PS,
  2276. A_VFMADD132SD,
  2277. A_VFMADD132SS,
  2278. A_VFMADD213PD,
  2279. A_VFMADD213PS,
  2280. A_VFMADD213SD,
  2281. A_VFMADD213SS,
  2282. A_VFMADD231PD,
  2283. A_VFMADD231PS,
  2284. A_VFMADD231SD,
  2285. A_VFMADD231SS,
  2286. A_VFMADDSUB132PD,
  2287. A_VFMADDSUB132PS,
  2288. A_VFMADDSUB213PD,
  2289. A_VFMADDSUB213PS,
  2290. A_VFMADDSUB231PD,
  2291. A_VFMADDSUB231PS,
  2292. A_VFMSUB132PD,
  2293. A_VFMSUB132PS,
  2294. A_VFMSUB132SD,
  2295. A_VFMSUB132SS,
  2296. A_VFMSUB213PD,
  2297. A_VFMSUB213PS,
  2298. A_VFMSUB213SD,
  2299. A_VFMSUB213SS,
  2300. A_VFMSUB231PD,
  2301. A_VFMSUB231PS,
  2302. A_VFMSUB231SD,
  2303. A_VFMSUB231SS,
  2304. A_VFMSUBADD132PD,
  2305. A_VFMSUBADD132PS,
  2306. A_VFMSUBADD213PD,
  2307. A_VFMSUBADD213PS,
  2308. A_VFMSUBADD231PD,
  2309. A_VFMSUBADD231PS,
  2310. A_VFNMADD132PD,
  2311. A_VFNMADD132PS,
  2312. A_VFNMADD132SD,
  2313. A_VFNMADD132SS,
  2314. A_VFNMADD213PD,
  2315. A_VFNMADD213PS,
  2316. A_VFNMADD213SD,
  2317. A_VFNMADD213SS,
  2318. A_VFNMADD231PD,
  2319. A_VFNMADD231PS,
  2320. A_VFNMADD231SD,
  2321. A_VFNMADD231SS,
  2322. A_VFNMSUB132PD,
  2323. A_VFNMSUB132PS,
  2324. A_VFNMSUB132SD,
  2325. A_VFNMSUB132SS,
  2326. A_VFNMSUB213PD,
  2327. A_VFNMSUB213PS,
  2328. A_VFNMSUB213SD,
  2329. A_VFNMSUB213SS,
  2330. A_VFNMSUB231PD,
  2331. A_VFNMSUB231PS,
  2332. A_VFNMSUB231SD,
  2333. A_VFNMSUB231SS],[S_NO]) and
  2334. { we mix single and double opperations here because we assume that the compiler
  2335. generates vmovapd only after double operations and vmovaps only after single operations }
  2336. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2337. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2338. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2339. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2340. begin
  2341. TransferUsedRegs(TmpUsedRegs);
  2342. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2343. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2344. begin
  2345. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2346. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2347. RemoveCurrentP(p)
  2348. else
  2349. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2350. RemoveInstruction(hp2);
  2351. end;
  2352. end
  2353. else if (hp1.typ = ait_instruction) and
  2354. (((taicpu(p).opcode=A_MOVAPS) and
  2355. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2356. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2357. ((taicpu(p).opcode=A_MOVAPD) and
  2358. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2359. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2360. ) and
  2361. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2362. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2363. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2364. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2365. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2366. { change
  2367. movapX reg,reg2
  2368. addsX/subsX/... reg3, reg2
  2369. movapX reg2,reg
  2370. to
  2371. addsX/subsX/... reg3,reg
  2372. }
  2373. begin
  2374. TransferUsedRegs(TmpUsedRegs);
  2375. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2376. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2377. begin
  2378. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2379. debug_op2str(taicpu(p).opcode)+' '+
  2380. debug_op2str(taicpu(hp1).opcode)+' '+
  2381. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2382. { we cannot eliminate the first move if
  2383. the operations uses the same register for source and dest }
  2384. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2385. { Remember that hp1 is not necessarily the immediate
  2386. next instruction }
  2387. RemoveCurrentP(p);
  2388. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2389. RemoveInstruction(hp2);
  2390. result:=true;
  2391. end;
  2392. end
  2393. else if (hp1.typ = ait_instruction) and
  2394. (((taicpu(p).opcode=A_VMOVAPD) and
  2395. (taicpu(hp1).opcode=A_VCOMISD)) or
  2396. ((taicpu(p).opcode=A_VMOVAPS) and
  2397. ((taicpu(hp1).opcode=A_VCOMISS))
  2398. )
  2399. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2400. { change
  2401. movapX reg,reg1
  2402. vcomisX reg1,reg1
  2403. to
  2404. vcomisX reg,reg
  2405. }
  2406. begin
  2407. TransferUsedRegs(TmpUsedRegs);
  2408. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2409. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2410. begin
  2411. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2412. debug_op2str(taicpu(p).opcode)+' '+
  2413. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2414. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2415. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2416. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2417. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2418. RemoveCurrentP(p);
  2419. result:=true;
  2420. exit;
  2421. end;
  2422. end
  2423. end;
  2424. end;
  2425. end;
  2426. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2427. var
  2428. hp1 : tai;
  2429. begin
  2430. result:=false;
  2431. { replace
  2432. V<Op>X %mreg1,%mreg2,%mreg3
  2433. VMovX %mreg3,%mreg4
  2434. dealloc %mreg3
  2435. by
  2436. V<Op>X %mreg1,%mreg2,%mreg4
  2437. ?
  2438. }
  2439. if GetNextInstruction(p,hp1) and
  2440. { we mix single and double operations here because we assume that the compiler
  2441. generates vmovapd only after double operations and vmovaps only after single operations }
  2442. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2443. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2444. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2445. begin
  2446. TransferUsedRegs(TmpUsedRegs);
  2447. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2448. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2449. begin
  2450. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2451. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2452. RemoveInstruction(hp1);
  2453. result:=true;
  2454. end;
  2455. end;
  2456. end;
  2457. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2458. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2459. begin
  2460. Result := False;
  2461. { For safety reasons, only check for exact register matches }
  2462. { Check base register }
  2463. if (ref.base = AOldReg) then
  2464. begin
  2465. ref.base := ANewReg;
  2466. Result := True;
  2467. end;
  2468. { Check index register }
  2469. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2470. begin
  2471. ref.index := ANewReg;
  2472. Result := True;
  2473. end;
  2474. end;
  2475. { Replaces all references to AOldReg in an operand to ANewReg }
  2476. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2477. var
  2478. OldSupReg, NewSupReg: TSuperRegister;
  2479. OldSubReg, NewSubReg: TSubRegister;
  2480. OldRegType: TRegisterType;
  2481. ThisOper: POper;
  2482. begin
  2483. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2484. Result := False;
  2485. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2486. InternalError(2020011801);
  2487. OldSupReg := getsupreg(AOldReg);
  2488. OldSubReg := getsubreg(AOldReg);
  2489. OldRegType := getregtype(AOldReg);
  2490. NewSupReg := getsupreg(ANewReg);
  2491. NewSubReg := getsubreg(ANewReg);
  2492. if OldRegType <> getregtype(ANewReg) then
  2493. InternalError(2020011802);
  2494. if OldSubReg <> NewSubReg then
  2495. InternalError(2020011803);
  2496. case ThisOper^.typ of
  2497. top_reg:
  2498. if (
  2499. (ThisOper^.reg = AOldReg) or
  2500. (
  2501. (OldRegType = R_INTREGISTER) and
  2502. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2503. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2504. (
  2505. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2506. {$ifndef x86_64}
  2507. and (
  2508. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2509. don't have an 8-bit representation }
  2510. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2511. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2512. )
  2513. {$endif x86_64}
  2514. )
  2515. )
  2516. ) then
  2517. begin
  2518. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2519. Result := True;
  2520. end;
  2521. top_ref:
  2522. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2523. Result := True;
  2524. else
  2525. ;
  2526. end;
  2527. end;
  2528. { Replaces all references to AOldReg in an instruction to ANewReg }
  2529. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2530. const
  2531. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2532. var
  2533. OperIdx: Integer;
  2534. begin
  2535. Result := False;
  2536. for OperIdx := 0 to p.ops - 1 do
  2537. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2538. begin
  2539. { The shift and rotate instructions can only use CL }
  2540. if not (
  2541. (OperIdx = 0) and
  2542. { This second condition just helps to avoid unnecessarily
  2543. calling MatchInstruction for 10 different opcodes }
  2544. (p.oper[0]^.reg = NR_CL) and
  2545. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2546. ) then
  2547. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2548. end
  2549. else if p.oper[OperIdx]^.typ = top_ref then
  2550. { It's okay to replace registers in references that get written to }
  2551. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2552. end;
  2553. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2554. begin
  2555. Result :=
  2556. (ref^.index = NR_NO) and
  2557. (
  2558. {$ifdef x86_64}
  2559. (
  2560. (ref^.base = NR_RIP) and
  2561. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2562. ) or
  2563. {$endif x86_64}
  2564. (ref^.refaddr = addr_full) or
  2565. (ref^.base = NR_STACK_POINTER_REG) or
  2566. (ref^.base = current_procinfo.framepointer)
  2567. );
  2568. end;
  2569. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2570. var
  2571. l: asizeint;
  2572. begin
  2573. Result := False;
  2574. { Should have been checked previously }
  2575. if p.opcode <> A_LEA then
  2576. InternalError(2020072501);
  2577. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2578. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2579. not(cs_opt_size in current_settings.optimizerswitches) then
  2580. exit;
  2581. with p.oper[0]^.ref^ do
  2582. begin
  2583. if (base <> p.oper[1]^.reg) or
  2584. (index <> NR_NO) or
  2585. assigned(symbol) then
  2586. exit;
  2587. l:=offset;
  2588. if (l=1) and UseIncDec then
  2589. begin
  2590. p.opcode:=A_INC;
  2591. p.loadreg(0,p.oper[1]^.reg);
  2592. p.ops:=1;
  2593. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2594. end
  2595. else if (l=-1) and UseIncDec then
  2596. begin
  2597. p.opcode:=A_DEC;
  2598. p.loadreg(0,p.oper[1]^.reg);
  2599. p.ops:=1;
  2600. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2601. end
  2602. else
  2603. begin
  2604. if (l<0) and (l<>-2147483648) then
  2605. begin
  2606. p.opcode:=A_SUB;
  2607. p.loadConst(0,-l);
  2608. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2609. end
  2610. else
  2611. begin
  2612. p.opcode:=A_ADD;
  2613. p.loadConst(0,l);
  2614. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2615. end;
  2616. end;
  2617. end;
  2618. Result := True;
  2619. end;
  2620. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2621. var
  2622. CurrentReg, ReplaceReg: TRegister;
  2623. begin
  2624. Result := False;
  2625. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2626. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2627. case hp.opcode of
  2628. A_FSTSW, A_FNSTSW,
  2629. A_IN, A_INS, A_OUT, A_OUTS,
  2630. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2631. { These routines have explicit operands, but they are restricted in
  2632. what they can be (e.g. IN and OUT can only read from AL, AX or
  2633. EAX. }
  2634. Exit;
  2635. A_IMUL:
  2636. begin
  2637. { The 1-operand version writes to implicit registers
  2638. The 2-operand version reads from the first operator, and reads
  2639. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2640. the 3-operand version reads from a register that it doesn't write to
  2641. }
  2642. case hp.ops of
  2643. 1:
  2644. if (
  2645. (
  2646. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2647. ) or
  2648. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2649. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2650. begin
  2651. Result := True;
  2652. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2653. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2654. end;
  2655. 2:
  2656. { Only modify the first parameter }
  2657. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2658. begin
  2659. Result := True;
  2660. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2661. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2662. end;
  2663. 3:
  2664. { Only modify the second parameter }
  2665. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2666. begin
  2667. Result := True;
  2668. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2669. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2670. end;
  2671. else
  2672. InternalError(2020012901);
  2673. end;
  2674. end;
  2675. else
  2676. if (hp.ops > 0) and
  2677. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2678. begin
  2679. Result := True;
  2680. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2681. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2682. end;
  2683. end;
  2684. end;
  2685. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2686. var
  2687. hp2, hp_regalloc: tai;
  2688. p_SourceReg, p_TargetReg: TRegister;
  2689. begin
  2690. Result := False;
  2691. { Backward optimisation. If we have:
  2692. func. %reg1,%reg2
  2693. mov %reg2,%reg3
  2694. (dealloc %reg2)
  2695. Change to:
  2696. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2697. Perform similar optimisations with 1, 3 and 4-operand instructions
  2698. that only have one output.
  2699. }
  2700. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2701. begin
  2702. p_SourceReg := taicpu(p).oper[0]^.reg;
  2703. p_TargetReg := taicpu(p).oper[1]^.reg;
  2704. TransferUsedRegs(TmpUsedRegs);
  2705. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2706. GetLastInstruction(p, hp2) and
  2707. (hp2.typ = ait_instruction) and
  2708. { Have to make sure it's an instruction that only reads from
  2709. the first operands and only writes (not reads or modifies) to
  2710. the last one; in essence, a pure function such as BSR, POPCNT
  2711. or ANDN }
  2712. (
  2713. (
  2714. (taicpu(hp2).ops = 1) and
  2715. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2716. ) or
  2717. (
  2718. (taicpu(hp2).ops = 2) and
  2719. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2720. ) or
  2721. (
  2722. (taicpu(hp2).ops = 3) and
  2723. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2724. ) or
  2725. (
  2726. (taicpu(hp2).ops = 4) and
  2727. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2728. )
  2729. ) and
  2730. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2731. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2732. begin
  2733. case taicpu(hp2).opcode of
  2734. A_FSTSW, A_FNSTSW,
  2735. A_IN, A_INS, A_OUT, A_OUTS,
  2736. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2737. { These routines have explicit operands, but they are restricted in
  2738. what they can be (e.g. IN and OUT can only read from AL, AX or
  2739. EAX. }
  2740. ;
  2741. else
  2742. begin
  2743. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2744. { if %reg2 (p_SourceReg) is allocated before func., remove it completely }
  2745. hp_regalloc := FindRegAllocBackward(p_SourceReg, hp2);
  2746. if Assigned(hp_regalloc) then
  2747. begin
  2748. Asml.Remove(hp_regalloc);
  2749. if Assigned(FindRegDealloc(p_SourceReg, p)) then
  2750. begin
  2751. ExcludeRegFromUsedRegs(p_SourceReg, UsedRegs);
  2752. hp_regalloc.Free;
  2753. end
  2754. else
  2755. { If the register is not explicitly deallocated, it's
  2756. being reused, so move the allocation to after func. }
  2757. AsmL.InsertAfter(hp_regalloc, hp2);
  2758. end;
  2759. if not RegInInstruction(p_TargetReg, hp2) then
  2760. begin
  2761. TransferUsedRegs(TmpUsedRegs);
  2762. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2763. end;
  2764. { Actually make the changes }
  2765. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2766. RemoveCurrentp(p, hp1);
  2767. { If the Func was another MOV instruction, we might get
  2768. "mov %reg,%reg" that doesn't get removed in Pass 2
  2769. otherwise, so deal with it here (also do something
  2770. similar with lea (%reg),%reg}
  2771. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2772. begin
  2773. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2774. if p = hp2 then
  2775. RemoveCurrentp(p)
  2776. else
  2777. RemoveInstruction(hp2);
  2778. end;
  2779. Result := True;
  2780. Exit;
  2781. end;
  2782. end;
  2783. end;
  2784. end;
  2785. end;
  2786. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2787. begin
  2788. Result := False;
  2789. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2790. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2791. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2792. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2793. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2794. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2795. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2796. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2797. begin
  2798. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2799. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2800. Result := True;
  2801. Include(OptsToCheck, aoc_ForceNewIteration);
  2802. end;
  2803. end;
  2804. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2805. var
  2806. hp1, hp2, hp3, hp4: tai;
  2807. DoOptimisation, TempBool: Boolean;
  2808. {$ifdef x86_64}
  2809. NewConst: TCGInt;
  2810. {$endif x86_64}
  2811. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2812. begin
  2813. if taicpu(hp1).opcode = signed_movop then
  2814. begin
  2815. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2816. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2817. end
  2818. else
  2819. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2820. end;
  2821. function TryConstMerge(var p1, p2: tai): Boolean;
  2822. var
  2823. ThisRef: TReference;
  2824. begin
  2825. Result := False;
  2826. ThisRef := taicpu(p2).oper[1]^.ref^;
  2827. { Only permit writes to the stack, since we can guarantee alignment with that }
  2828. if (ThisRef.index = NR_NO) and
  2829. (
  2830. (ThisRef.base = NR_STACK_POINTER_REG) or
  2831. (ThisRef.base = current_procinfo.framepointer)
  2832. ) then
  2833. begin
  2834. case taicpu(p).opsize of
  2835. S_B:
  2836. begin
  2837. { Word writes must be on a 2-byte boundary }
  2838. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2839. begin
  2840. { Reduce offset of second reference to see if it is sequential with the first }
  2841. Dec(ThisRef.offset, 1);
  2842. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2843. begin
  2844. { Make sure the constants aren't represented as a
  2845. negative number, as these won't merge properly }
  2846. taicpu(p1).opsize := S_W;
  2847. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2848. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2849. RemoveInstruction(p2);
  2850. Result := True;
  2851. end;
  2852. end;
  2853. end;
  2854. S_W:
  2855. begin
  2856. { Longword writes must be on a 4-byte boundary }
  2857. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2858. begin
  2859. { Reduce offset of second reference to see if it is sequential with the first }
  2860. Dec(ThisRef.offset, 2);
  2861. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2862. begin
  2863. { Make sure the constants aren't represented as a
  2864. negative number, as these won't merge properly }
  2865. taicpu(p1).opsize := S_L;
  2866. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2867. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2868. RemoveInstruction(p2);
  2869. Result := True;
  2870. end;
  2871. end;
  2872. end;
  2873. {$ifdef x86_64}
  2874. S_L:
  2875. begin
  2876. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2877. see if the constants can be encoded this way. }
  2878. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2879. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2880. { Quadword writes must be on an 8-byte boundary }
  2881. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2882. begin
  2883. { Reduce offset of second reference to see if it is sequential with the first }
  2884. Dec(ThisRef.offset, 4);
  2885. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2886. begin
  2887. { Make sure the constants aren't represented as a
  2888. negative number, as these won't merge properly }
  2889. taicpu(p1).opsize := S_Q;
  2890. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2891. taicpu(p1).oper[0]^.val := NewConst;
  2892. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2893. RemoveInstruction(p2);
  2894. Result := True;
  2895. end;
  2896. end;
  2897. end;
  2898. {$endif x86_64}
  2899. else
  2900. ;
  2901. end;
  2902. end;
  2903. end;
  2904. var
  2905. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2906. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2907. NewSize: topsize; NewOffset: asizeint;
  2908. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2909. SourceRef, TargetRef: TReference;
  2910. MovAligned, MovUnaligned: TAsmOp;
  2911. ThisRef: TReference;
  2912. JumpTracking: TLinkedList;
  2913. begin
  2914. Result:=false;
  2915. { remove mov reg1,reg1? }
  2916. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2917. then
  2918. begin
  2919. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2920. { take care of the register (de)allocs following p }
  2921. RemoveCurrentP(p);
  2922. Result := True;
  2923. exit;
  2924. end;
  2925. { Prevent compiler warnings }
  2926. p_SourceReg := NR_NO;
  2927. p_TargetReg := NR_NO;
  2928. if taicpu(p).oper[1]^.typ = top_reg then
  2929. begin
  2930. { Saves on a large number of dereferences }
  2931. p_TargetReg := taicpu(p).oper[1]^.reg;
  2932. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  2933. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_TargetReg)
  2934. else
  2935. GetNextInstruction_p := GetNextInstruction(p, hp1);
  2936. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  2937. begin
  2938. if (taicpu(hp1).opcode = A_AND) and
  2939. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2940. begin
  2941. if MatchOperand(taicpu(hp1).oper[1]^, p_TargetReg) then
  2942. begin
  2943. case taicpu(p).opsize of
  2944. S_L:
  2945. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2946. begin
  2947. { Optimize out:
  2948. mov x, %reg
  2949. and ffffffffh, %reg
  2950. }
  2951. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2952. RemoveInstruction(hp1);
  2953. Result:=true;
  2954. exit;
  2955. end;
  2956. S_Q: { TODO: Confirm if this is even possible }
  2957. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2958. begin
  2959. { Optimize out:
  2960. mov x, %reg
  2961. and ffffffffffffffffh, %reg
  2962. }
  2963. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2964. RemoveInstruction(hp1);
  2965. Result:=true;
  2966. exit;
  2967. end;
  2968. else
  2969. ;
  2970. end;
  2971. if (
  2972. { Make sure that if a reference is used, its registers
  2973. are not modified in between }
  2974. (
  2975. (taicpu(p).oper[0]^.typ = top_reg) and
  2976. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2977. ) or
  2978. (
  2979. (taicpu(p).oper[0]^.typ = top_ref) and
  2980. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  2981. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1)
  2982. )
  2983. ) and
  2984. GetNextInstruction(hp1,hp2) and
  2985. MatchInstruction(hp2,A_TEST,[]) and
  2986. (
  2987. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2988. (
  2989. { If the register being tested is smaller than the one
  2990. that received a bitwise AND, permit it if the constant
  2991. fits into the smaller size }
  2992. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2993. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2994. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2995. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2996. (
  2997. (
  2998. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2999. (taicpu(hp1).oper[0]^.val <= $FF)
  3000. ) or
  3001. (
  3002. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3003. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3004. {$ifdef x86_64}
  3005. ) or
  3006. (
  3007. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3008. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3009. {$endif x86_64}
  3010. )
  3011. )
  3012. )
  3013. ) and
  3014. (
  3015. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3016. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3017. ) and
  3018. GetNextInstruction(hp2,hp3) and
  3019. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3020. (taicpu(hp3).condition in [C_E,C_NE]) then
  3021. begin
  3022. TransferUsedRegs(TmpUsedRegs);
  3023. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3024. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3025. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3026. begin
  3027. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3028. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3029. taicpu(hp1).opcode:=A_TEST;
  3030. { Shrink the TEST instruction down to the smallest possible size }
  3031. case taicpu(hp1).oper[0]^.val of
  3032. 0..255:
  3033. if (taicpu(hp1).opsize <> S_B)
  3034. {$ifndef x86_64}
  3035. and (
  3036. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3037. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3038. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3039. )
  3040. {$endif x86_64}
  3041. then
  3042. begin
  3043. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3044. { Only print debug message if the TEST instruction
  3045. is a different size before and after }
  3046. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3047. taicpu(hp1).opsize := S_B;
  3048. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3049. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3050. end;
  3051. 256..65535:
  3052. if (taicpu(hp1).opsize <> S_W) then
  3053. begin
  3054. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3055. { Only print debug message if the TEST instruction
  3056. is a different size before and after }
  3057. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3058. taicpu(hp1).opsize := S_W;
  3059. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3060. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3061. end;
  3062. {$ifdef x86_64}
  3063. 65536..$7FFFFFFF:
  3064. if (taicpu(hp1).opsize <> S_L) then
  3065. begin
  3066. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3067. { Only print debug message if the TEST instruction
  3068. is a different size before and after }
  3069. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3070. taicpu(hp1).opsize := S_L;
  3071. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3072. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3073. end;
  3074. {$endif x86_64}
  3075. else
  3076. ;
  3077. end;
  3078. RemoveInstruction(hp2);
  3079. RemoveCurrentP(p);
  3080. Result:=true;
  3081. exit;
  3082. end;
  3083. end;
  3084. end;
  3085. if IsMOVZXAcceptable and
  3086. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3087. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3088. (getsupreg(p_TargetReg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3089. then
  3090. begin
  3091. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3092. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3093. case taicpu(p).opsize of
  3094. S_B:
  3095. if (taicpu(hp1).oper[0]^.val = $ff) then
  3096. begin
  3097. { Convert:
  3098. movb x, %regl movb x, %regl
  3099. andw ffh, %regw andl ffh, %regd
  3100. To:
  3101. movzbw x, %regd movzbl x, %regd
  3102. (Identical registers, just different sizes)
  3103. }
  3104. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3105. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3106. case taicpu(hp1).opsize of
  3107. S_W: NewSize := S_BW;
  3108. S_L: NewSize := S_BL;
  3109. {$ifdef x86_64}
  3110. S_Q: NewSize := S_BQ;
  3111. {$endif x86_64}
  3112. else
  3113. InternalError(2018011510);
  3114. end;
  3115. end
  3116. else
  3117. NewSize := S_NO;
  3118. S_W:
  3119. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3120. begin
  3121. { Convert:
  3122. movw x, %regw
  3123. andl ffffh, %regd
  3124. To:
  3125. movzwl x, %regd
  3126. (Identical registers, just different sizes)
  3127. }
  3128. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3129. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3130. case taicpu(hp1).opsize of
  3131. S_L: NewSize := S_WL;
  3132. {$ifdef x86_64}
  3133. S_Q: NewSize := S_WQ;
  3134. {$endif x86_64}
  3135. else
  3136. InternalError(2018011511);
  3137. end;
  3138. end
  3139. else
  3140. NewSize := S_NO;
  3141. else
  3142. NewSize := S_NO;
  3143. end;
  3144. if NewSize <> S_NO then
  3145. begin
  3146. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3147. { The actual optimization }
  3148. taicpu(p).opcode := A_MOVZX;
  3149. taicpu(p).changeopsize(NewSize);
  3150. taicpu(p).loadoper(1, taicpu(hp1).oper[1]^);
  3151. { Make sure we deal with any reference counts that were increased }
  3152. if taicpu(hp1).oper[1]^.typ = top_ref then
  3153. begin
  3154. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  3155. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  3156. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  3157. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  3158. end;
  3159. { Safeguard if "and" is followed by a conditional command }
  3160. TransferUsedRegs(TmpUsedRegs);
  3161. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  3162. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3163. begin
  3164. { At this point, the "and" command is effectively equivalent to
  3165. "test %reg,%reg". This will be handled separately by the
  3166. Peephole Optimizer. [Kit] }
  3167. DebugMsg(SPeepholeOptimization + PreMessage +
  3168. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3169. end
  3170. else
  3171. begin
  3172. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3173. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3174. RemoveInstruction(hp1);
  3175. end;
  3176. Result := True;
  3177. Exit;
  3178. end;
  3179. end;
  3180. end;
  3181. if taicpu(p).oper[0]^.typ = top_reg then
  3182. begin
  3183. p_SourceReg := taicpu(p).oper[0]^.reg;
  3184. { Look for:
  3185. mov %reg1,%reg2
  3186. ??? %reg2,r/m
  3187. Change to:
  3188. mov %reg1,%reg2
  3189. ??? %reg1,r/m
  3190. }
  3191. if RegReadByInstruction(p_TargetReg, hp1) and
  3192. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3193. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  3194. begin
  3195. { A change has occurred, just not in p }
  3196. Include(OptsToCheck, aoc_ForceNewIteration);
  3197. TransferUsedRegs(TmpUsedRegs);
  3198. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3199. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3200. { Just in case something didn't get modified (e.g. an
  3201. implicit register) }
  3202. not RegReadByInstruction(p_TargetReg, hp1) then
  3203. begin
  3204. { We can remove the original MOV }
  3205. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  3206. RemoveCurrentP(p);
  3207. { UsedRegs got updated by RemoveCurrentp }
  3208. Result := True;
  3209. Exit;
  3210. end;
  3211. { If we know a MOV instruction has become a null operation, we might as well
  3212. get rid of it now to save time. }
  3213. if (taicpu(hp1).opcode = A_MOV) and
  3214. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3215. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  3216. { Just being a register is enough to confirm it's a null operation }
  3217. (taicpu(hp1).oper[0]^.typ = top_reg) then
  3218. begin
  3219. Result := True;
  3220. { Speed-up to reduce a pipeline stall... if we had something like...
  3221. movl %eax,%edx
  3222. movw %dx,%ax
  3223. ... the second instruction would change to movw %ax,%ax, but
  3224. given that it is now %ax that's active rather than %eax,
  3225. penalties might occur due to a partial register write, so instead,
  3226. change it to a MOVZX instruction when optimising for speed.
  3227. }
  3228. if not (cs_opt_size in current_settings.optimizerswitches) and
  3229. IsMOVZXAcceptable and
  3230. (taicpu(hp1).opsize < taicpu(p).opsize)
  3231. {$ifdef x86_64}
  3232. { operations already implicitly set the upper 64 bits to zero }
  3233. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  3234. {$endif x86_64}
  3235. then
  3236. begin
  3237. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  3238. case taicpu(p).opsize of
  3239. S_W:
  3240. if taicpu(hp1).opsize = S_B then
  3241. taicpu(hp1).opsize := S_BL
  3242. else
  3243. InternalError(2020012911);
  3244. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  3245. case taicpu(hp1).opsize of
  3246. S_B:
  3247. taicpu(hp1).opsize := S_BL;
  3248. S_W:
  3249. taicpu(hp1).opsize := S_WL;
  3250. else
  3251. InternalError(2020012912);
  3252. end;
  3253. else
  3254. InternalError(2020012910);
  3255. end;
  3256. taicpu(hp1).opcode := A_MOVZX;
  3257. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3258. end
  3259. else
  3260. begin
  3261. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  3262. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  3263. RemoveInstruction(hp1);
  3264. { The instruction after what was hp1 is now the immediate next instruction,
  3265. so we can continue to make optimisations if it's present }
  3266. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  3267. Exit;
  3268. hp1 := hp2;
  3269. end;
  3270. end;
  3271. end;
  3272. end
  3273. else if taicpu(p).oper[0]^.typ = top_const then
  3274. begin
  3275. if (taicpu(hp1).opcode = A_OR) and
  3276. (taicpu(p).oper[1]^.typ = top_reg) and
  3277. MatchOperand(taicpu(p).oper[0]^, 0) and
  3278. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3279. begin
  3280. { mov 0, %reg
  3281. or ###,%reg
  3282. Change to (only if the flags are not used):
  3283. mov ###,%reg
  3284. }
  3285. TransferUsedRegs(TmpUsedRegs);
  3286. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3287. DoOptimisation := True;
  3288. { Even if the flags are used, we might be able to do the optimisation
  3289. if the conditions are predictable }
  3290. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3291. begin
  3292. { Only perform if ### = %reg (the same register) or equal to 0,
  3293. so %reg is guaranteed to still have a value of zero }
  3294. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3295. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3296. begin
  3297. hp2 := hp1;
  3298. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3299. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3300. GetNextInstruction(hp2, hp3) do
  3301. begin
  3302. { Don't continue modifying if the flags state is getting changed }
  3303. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3304. Break;
  3305. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3306. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3307. begin
  3308. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3309. begin
  3310. { Condition is always true }
  3311. case taicpu(hp3).opcode of
  3312. A_Jcc:
  3313. begin
  3314. { Check for jump shortcuts before we destroy the condition }
  3315. hp4 := hp3;
  3316. DoJumpOptimizations(hp3, TempBool);
  3317. { Make sure hp3 hasn't changed }
  3318. if (hp4 = hp3) then
  3319. begin
  3320. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3321. MakeUnconditional(taicpu(hp3));
  3322. end;
  3323. Result := True;
  3324. end;
  3325. A_CMOVcc:
  3326. begin
  3327. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3328. taicpu(hp3).opcode := A_MOV;
  3329. taicpu(hp3).condition := C_None;
  3330. Result := True;
  3331. end;
  3332. A_SETcc:
  3333. begin
  3334. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3335. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3336. taicpu(hp3).opcode := A_MOV;
  3337. taicpu(hp3).ops := 2;
  3338. taicpu(hp3).condition := C_None;
  3339. taicpu(hp3).opsize := S_B;
  3340. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3341. taicpu(hp3).loadconst(0, 1);
  3342. Result := True;
  3343. end;
  3344. else
  3345. InternalError(2021090701);
  3346. end;
  3347. end
  3348. 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
  3349. begin
  3350. { Condition is always false }
  3351. case taicpu(hp3).opcode of
  3352. A_Jcc:
  3353. begin
  3354. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3355. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3356. RemoveInstruction(hp3);
  3357. Result := True;
  3358. { Since hp3 was deleted, hp2 must not be updated }
  3359. Continue;
  3360. end;
  3361. A_CMOVcc:
  3362. begin
  3363. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3364. RemoveInstruction(hp3);
  3365. Result := True;
  3366. { Since hp3 was deleted, hp2 must not be updated }
  3367. Continue;
  3368. end;
  3369. A_SETcc:
  3370. begin
  3371. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3372. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3373. taicpu(hp3).opcode := A_MOV;
  3374. taicpu(hp3).ops := 2;
  3375. taicpu(hp3).condition := C_None;
  3376. taicpu(hp3).opsize := S_B;
  3377. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3378. taicpu(hp3).loadconst(0, 0);
  3379. Result := True;
  3380. end;
  3381. else
  3382. InternalError(2021090702);
  3383. end;
  3384. end
  3385. else
  3386. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3387. DoOptimisation := False;
  3388. end;
  3389. hp2 := hp3;
  3390. end;
  3391. if DoOptimisation then
  3392. begin
  3393. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3394. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3395. { Flags are still in use - don't optimise }
  3396. DoOptimisation := False;
  3397. end;
  3398. end
  3399. else
  3400. DoOptimisation := False;
  3401. end;
  3402. if DoOptimisation then
  3403. begin
  3404. {$ifdef x86_64}
  3405. { OR only supports 32-bit sign-extended constants for 64-bit
  3406. instructions, so compensate for this if the constant is
  3407. encoded as a value greater than or equal to 2^31 }
  3408. if (taicpu(hp1).opsize = S_Q) and
  3409. (taicpu(hp1).oper[0]^.typ = top_const) and
  3410. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3411. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3412. {$endif x86_64}
  3413. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3414. taicpu(hp1).opcode := A_MOV;
  3415. RemoveCurrentP(p);
  3416. Result := True;
  3417. Exit;
  3418. end;
  3419. end;
  3420. end;
  3421. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  3422. overwrites the original destination register. e.g.
  3423. movl ###,%reg2d
  3424. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  3425. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  3426. }
  3427. if MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  3428. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3429. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  3430. begin
  3431. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  3432. begin
  3433. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  3434. case taicpu(p).oper[0]^.typ of
  3435. top_const:
  3436. { We have something like:
  3437. movb $x, %regb
  3438. movzbl %regb,%regd
  3439. Change to:
  3440. movl $x, %regd
  3441. }
  3442. begin
  3443. case taicpu(hp1).opsize of
  3444. S_BW:
  3445. begin
  3446. convert_mov_value(A_MOVSX, $FF);
  3447. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  3448. taicpu(p).opsize := S_W;
  3449. end;
  3450. S_BL:
  3451. begin
  3452. convert_mov_value(A_MOVSX, $FF);
  3453. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3454. taicpu(p).opsize := S_L;
  3455. end;
  3456. S_WL:
  3457. begin
  3458. convert_mov_value(A_MOVSX, $FFFF);
  3459. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3460. taicpu(p).opsize := S_L;
  3461. end;
  3462. {$ifdef x86_64}
  3463. S_BQ:
  3464. begin
  3465. convert_mov_value(A_MOVSX, $FF);
  3466. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3467. taicpu(p).opsize := S_Q;
  3468. end;
  3469. S_WQ:
  3470. begin
  3471. convert_mov_value(A_MOVSX, $FFFF);
  3472. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3473. taicpu(p).opsize := S_Q;
  3474. end;
  3475. S_LQ:
  3476. begin
  3477. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  3478. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3479. taicpu(p).opsize := S_Q;
  3480. end;
  3481. {$endif x86_64}
  3482. else
  3483. { If hp1 was a MOV instruction, it should have been
  3484. optimised already }
  3485. InternalError(2020021001);
  3486. end;
  3487. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  3488. RemoveInstruction(hp1);
  3489. Result := True;
  3490. Exit;
  3491. end;
  3492. top_ref:
  3493. begin
  3494. { We have something like:
  3495. movb mem, %regb
  3496. movzbl %regb,%regd
  3497. Change to:
  3498. movzbl mem, %regd
  3499. }
  3500. if (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  3501. begin
  3502. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  3503. taicpu(p).opcode := taicpu(hp1).opcode;
  3504. taicpu(p).opsize := taicpu(hp1).opsize;
  3505. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  3506. RemoveInstruction(hp1);
  3507. Result := True;
  3508. Exit;
  3509. end;
  3510. end;
  3511. else
  3512. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  3513. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  3514. Exit;
  3515. end;
  3516. end
  3517. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3518. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3519. optimised }
  3520. else
  3521. begin
  3522. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3523. RemoveCurrentP(p);
  3524. Result := True;
  3525. Exit;
  3526. end;
  3527. end;
  3528. if (taicpu(hp1).opcode = A_MOV) and
  3529. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3530. begin
  3531. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3532. TransferUsedRegs(TmpUsedRegs);
  3533. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3534. { we have
  3535. mov x, %treg
  3536. mov %treg, y
  3537. }
  3538. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3539. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3540. begin
  3541. { we've got
  3542. mov x, %treg
  3543. mov %treg, y
  3544. with %treg is not used after }
  3545. case taicpu(p).oper[0]^.typ Of
  3546. { top_reg is covered by DeepMOVOpt }
  3547. top_const:
  3548. begin
  3549. { change
  3550. mov const, %treg
  3551. mov %treg, y
  3552. to
  3553. mov const, y
  3554. }
  3555. {$ifdef x86_64}
  3556. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3557. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3558. {$endif x86_64}
  3559. begin
  3560. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3561. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done', hp1);
  3562. RemoveCurrentP(p);
  3563. Result := True;
  3564. Exit;
  3565. end;
  3566. end;
  3567. top_ref:
  3568. case taicpu(hp1).oper[1]^.typ of
  3569. top_reg:
  3570. { change
  3571. mov mem, %treg
  3572. mov %treg, %reg
  3573. to
  3574. mov mem, %reg"
  3575. }
  3576. if not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) then
  3577. begin
  3578. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3579. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3a done', p);
  3580. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  3581. RemoveInstruction(hp1);
  3582. Result := True;
  3583. Exit;
  3584. end
  3585. else if
  3586. { Make sure that if a reference is used, its
  3587. registers are not modified in between }
  3588. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3589. begin
  3590. if (taicpu(p).oper[0]^.ref^.base <> NR_NO){$ifdef x86_64} and (taicpu(p).oper[0]^.ref^.base <> NR_RIP){$endif x86_64} then
  3591. AllocRegBetween(taicpu(p).oper[0]^.ref^.base, p, hp1, UsedRegs);
  3592. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and (taicpu(p).oper[0]^.ref^.index <> taicpu(p).oper[0]^.ref^.base) then
  3593. AllocRegBetween(taicpu(p).oper[0]^.ref^.index, p, hp1, UsedRegs);
  3594. taicpu(hp1).loadref(0, taicpu(p).oper[0]^.ref^);
  3595. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3596. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3597. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3598. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3599. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done', hp1);
  3600. RemoveCurrentP(p);
  3601. Result := True;
  3602. Exit;
  3603. end;
  3604. top_ref:
  3605. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3606. begin
  3607. {$ifdef x86_64}
  3608. { Look for the following to simplify:
  3609. mov x(mem1), %reg
  3610. mov %reg, y(mem2)
  3611. mov x+8(mem1), %reg
  3612. mov %reg, y+8(mem2)
  3613. Change to:
  3614. movdqu x(mem1), %xmmreg
  3615. movdqu %xmmreg, y(mem2)
  3616. ...but only as long as the memory blocks don't overlap
  3617. }
  3618. SourceRef := taicpu(p).oper[0]^.ref^;
  3619. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3620. if (taicpu(p).opsize = S_Q) and
  3621. not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3622. GetNextInstruction(hp1, hp2) and
  3623. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3624. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3625. begin
  3626. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3627. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3628. Inc(SourceRef.offset, 8);
  3629. if UseAVX then
  3630. begin
  3631. MovAligned := A_VMOVDQA;
  3632. MovUnaligned := A_VMOVDQU;
  3633. end
  3634. else
  3635. begin
  3636. MovAligned := A_MOVDQA;
  3637. MovUnaligned := A_MOVDQU;
  3638. end;
  3639. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3640. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3641. begin
  3642. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3643. Inc(TargetRef.offset, 8);
  3644. if GetNextInstruction(hp2, hp3) and
  3645. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3646. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3647. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3648. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3649. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3650. begin
  3651. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3652. if NewMMReg <> NR_NO then
  3653. begin
  3654. { Remember that the offsets are 8 ahead }
  3655. if ((SourceRef.offset mod 16) = 8) and
  3656. (
  3657. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3658. (SourceRef.base = current_procinfo.framepointer) or
  3659. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3660. ) then
  3661. taicpu(p).opcode := MovAligned
  3662. else
  3663. taicpu(p).opcode := MovUnaligned;
  3664. taicpu(p).opsize := S_XMM;
  3665. taicpu(p).oper[1]^.reg := NewMMReg;
  3666. if ((TargetRef.offset mod 16) = 8) and
  3667. (
  3668. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3669. (TargetRef.base = current_procinfo.framepointer) or
  3670. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3671. ) then
  3672. taicpu(hp1).opcode := MovAligned
  3673. else
  3674. taicpu(hp1).opcode := MovUnaligned;
  3675. taicpu(hp1).opsize := S_XMM;
  3676. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3677. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3678. RemoveInstruction(hp2);
  3679. RemoveInstruction(hp3);
  3680. Result := True;
  3681. Exit;
  3682. end;
  3683. end;
  3684. end
  3685. else
  3686. begin
  3687. { See if the next references are 8 less rather than 8 greater }
  3688. Dec(SourceRef.offset, 16); { -8 the other way }
  3689. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3690. begin
  3691. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3692. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3693. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3694. GetNextInstruction(hp2, hp3) and
  3695. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3696. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3697. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3698. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3699. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3700. begin
  3701. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3702. if NewMMReg <> NR_NO then
  3703. begin
  3704. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3705. if ((SourceRef.offset mod 16) = 0) and
  3706. (
  3707. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3708. (SourceRef.base = current_procinfo.framepointer) or
  3709. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3710. ) then
  3711. taicpu(hp2).opcode := MovAligned
  3712. else
  3713. taicpu(hp2).opcode := MovUnaligned;
  3714. taicpu(hp2).opsize := S_XMM;
  3715. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3716. if ((TargetRef.offset mod 16) = 0) and
  3717. (
  3718. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3719. (TargetRef.base = current_procinfo.framepointer) or
  3720. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3721. ) then
  3722. taicpu(hp3).opcode := MovAligned
  3723. else
  3724. taicpu(hp3).opcode := MovUnaligned;
  3725. taicpu(hp3).opsize := S_XMM;
  3726. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3727. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3728. RemoveInstruction(hp1);
  3729. RemoveCurrentP(p);
  3730. Result := True;
  3731. Exit;
  3732. end;
  3733. end;
  3734. end;
  3735. end;
  3736. end;
  3737. {$endif x86_64}
  3738. end;
  3739. else
  3740. { The write target should be a reg or a ref }
  3741. InternalError(2021091601);
  3742. end;
  3743. else
  3744. ;
  3745. end;
  3746. end
  3747. else if (taicpu(p).oper[0]^.typ = top_const) and
  3748. { %treg is used afterwards, but all eventualities other
  3749. than the first MOV instruction being a constant are
  3750. covered by DeepMOVOpt, so only check for that }
  3751. (
  3752. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3753. not (cs_opt_size in current_settings.optimizerswitches) or
  3754. (taicpu(hp1).opsize = S_B)
  3755. ) and
  3756. (
  3757. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3758. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3759. ) then
  3760. begin
  3761. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3762. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3763. Include(OptsToCheck, aoc_ForceNewIteration);
  3764. end;
  3765. end;
  3766. end;
  3767. end;
  3768. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  3769. { All the next optimisations require a next instruction }
  3770. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  3771. Exit;
  3772. { Next instruction is also a MOV ? }
  3773. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3774. begin
  3775. if MatchOpType(taicpu(p), top_const, top_ref) and
  3776. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3777. TryConstMerge(p, hp1) then
  3778. begin
  3779. Result := True;
  3780. { In case we have four byte writes in a row, check for 2 more
  3781. right now so we don't have to wait for another iteration of
  3782. pass 1
  3783. }
  3784. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3785. case taicpu(p).opsize of
  3786. S_W:
  3787. begin
  3788. if GetNextInstruction(p, hp1) and
  3789. MatchInstruction(hp1, A_MOV, [S_B]) and
  3790. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3791. GetNextInstruction(hp1, hp2) and
  3792. MatchInstruction(hp2, A_MOV, [S_B]) and
  3793. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3794. { Try to merge the two bytes }
  3795. TryConstMerge(hp1, hp2) then
  3796. { Now try to merge the two words (hp2 will get deleted) }
  3797. TryConstMerge(p, hp1);
  3798. end;
  3799. S_L:
  3800. begin
  3801. { Though this only really benefits x86_64 and not i386, it
  3802. gets a potential optimisation done faster and hence
  3803. reduces the number of times OptPass1MOV is entered }
  3804. if GetNextInstruction(p, hp1) and
  3805. MatchInstruction(hp1, A_MOV, [S_W]) and
  3806. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3807. GetNextInstruction(hp1, hp2) and
  3808. MatchInstruction(hp2, A_MOV, [S_W]) and
  3809. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3810. { Try to merge the two words }
  3811. TryConstMerge(hp1, hp2) then
  3812. { This will always fail on i386, so don't bother
  3813. calling it unless we're doing x86_64 }
  3814. {$ifdef x86_64}
  3815. { Now try to merge the two longwords (hp2 will get deleted) }
  3816. TryConstMerge(p, hp1)
  3817. {$endif x86_64}
  3818. ;
  3819. end;
  3820. else
  3821. ;
  3822. end;
  3823. Exit;
  3824. end;
  3825. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3826. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3827. { mov reg1, mem1 or mov mem1, reg1
  3828. mov mem2, reg2 mov reg2, mem2}
  3829. begin
  3830. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3831. { mov reg1, mem1 or mov mem1, reg1
  3832. mov mem2, reg1 mov reg2, mem1}
  3833. begin
  3834. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3835. { Removes the second statement from
  3836. mov reg1, mem1/reg2
  3837. mov mem1/reg2, reg1 }
  3838. begin
  3839. if taicpu(p).oper[0]^.typ=top_reg then
  3840. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3841. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3842. RemoveInstruction(hp1);
  3843. Result:=true;
  3844. exit;
  3845. end
  3846. else
  3847. begin
  3848. TransferUsedRegs(TmpUsedRegs);
  3849. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3850. if (taicpu(p).oper[1]^.typ = top_ref) and
  3851. { mov reg1, mem1
  3852. mov mem2, reg1 }
  3853. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3854. GetNextInstruction(hp1, hp2) and
  3855. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3856. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3857. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3858. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3859. { change to
  3860. mov reg1, mem1 mov reg1, mem1
  3861. mov mem2, reg1 cmp reg1, mem2
  3862. cmp mem1, reg1
  3863. }
  3864. begin
  3865. RemoveInstruction(hp2);
  3866. taicpu(hp1).opcode := A_CMP;
  3867. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3868. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3869. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3870. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3871. end;
  3872. end;
  3873. end
  3874. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3875. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3876. begin
  3877. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3878. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3879. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3880. end
  3881. else
  3882. begin
  3883. TransferUsedRegs(TmpUsedRegs);
  3884. if GetNextInstruction(hp1, hp2) and
  3885. MatchOpType(taicpu(p),top_ref,top_reg) and
  3886. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3887. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3888. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3889. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3890. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3891. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3892. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3893. { mov mem1, %reg1
  3894. mov %reg1, mem2
  3895. mov mem2, reg2
  3896. to:
  3897. mov mem1, reg2
  3898. mov reg2, mem2}
  3899. begin
  3900. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3901. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3902. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3903. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3904. RemoveInstruction(hp2);
  3905. Result := True;
  3906. end
  3907. {$ifdef i386}
  3908. { this is enabled for i386 only, as the rules to create the reg sets below
  3909. are too complicated for x86-64, so this makes this code too error prone
  3910. on x86-64
  3911. }
  3912. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3913. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3914. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3915. { mov mem1, reg1 mov mem1, reg1
  3916. mov reg1, mem2 mov reg1, mem2
  3917. mov mem2, reg2 mov mem2, reg1
  3918. to: to:
  3919. mov mem1, reg1 mov mem1, reg1
  3920. mov mem1, reg2 mov reg1, mem2
  3921. mov reg1, mem2
  3922. or (if mem1 depends on reg1
  3923. and/or if mem2 depends on reg2)
  3924. to:
  3925. mov mem1, reg1
  3926. mov reg1, mem2
  3927. mov reg1, reg2
  3928. }
  3929. begin
  3930. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3931. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3932. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3933. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3934. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3935. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3936. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3937. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3938. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3939. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3940. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3941. end
  3942. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3943. begin
  3944. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3945. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3946. end
  3947. else
  3948. begin
  3949. RemoveInstruction(hp2);
  3950. end
  3951. {$endif i386}
  3952. ;
  3953. end;
  3954. end
  3955. { movl [mem1],reg1
  3956. movl [mem1],reg2
  3957. to
  3958. movl [mem1],reg1
  3959. movl reg1,reg2
  3960. }
  3961. else if not CheckMovMov2MovMov2(p, hp1) and
  3962. { movl const1,[mem1]
  3963. movl [mem1],reg1
  3964. to
  3965. movl const1,reg1
  3966. movl reg1,[mem1]
  3967. }
  3968. MatchOpType(Taicpu(p),top_const,top_ref) and
  3969. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3970. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3971. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3972. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3973. begin
  3974. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3975. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3976. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3977. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3978. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3979. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3980. Result:=true;
  3981. exit;
  3982. end;
  3983. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3984. { Change:
  3985. movl %reg1,%reg2
  3986. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3987. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3988. To:
  3989. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3990. movl x(%reg1),%reg1
  3991. movl %reg1,%regX
  3992. }
  3993. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3994. begin
  3995. p_SourceReg := taicpu(p).oper[0]^.reg;
  3996. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3997. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3998. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3999. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  4000. GetNextInstruction(hp1, hp2) and
  4001. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  4002. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  4003. begin
  4004. SourceRef := taicpu(hp2).oper[0]^.ref^;
  4005. if RegInRef(p_TargetReg, SourceRef) and
  4006. { If %reg1 also appears in the second reference, then it will
  4007. not refer to the same memory block as the first reference }
  4008. not RegInRef(p_SourceReg, SourceRef) then
  4009. begin
  4010. { Check to see if the references match if %reg2 is changed to %reg1 }
  4011. if SourceRef.base = p_TargetReg then
  4012. SourceRef.base := p_SourceReg;
  4013. if SourceRef.index = p_TargetReg then
  4014. SourceRef.index := p_SourceReg;
  4015. { RefsEqual also checks to ensure both references are non-volatile }
  4016. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  4017. begin
  4018. taicpu(hp2).loadreg(0, p_SourceReg);
  4019. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  4020. Result := True;
  4021. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  4022. begin
  4023. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  4024. RemoveCurrentP(p, hp1);
  4025. Exit;
  4026. end
  4027. else
  4028. begin
  4029. { Check to see if %reg2 is no longer in use }
  4030. TransferUsedRegs(TmpUsedRegs);
  4031. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4032. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4033. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  4034. begin
  4035. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  4036. RemoveCurrentP(p, hp1);
  4037. Exit;
  4038. end;
  4039. end;
  4040. { If we reach this point, p and hp1 weren't actually modified,
  4041. so we can do a bit more work on this pass }
  4042. end;
  4043. end;
  4044. end;
  4045. end;
  4046. end;
  4047. {$ifdef x86_64}
  4048. { Change:
  4049. movl %reg1l,%reg2l
  4050. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4051. To:
  4052. movl %reg1l,%reg2l
  4053. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4054. If %reg1 = %reg3, convert to:
  4055. movl %reg1l,%reg2l
  4056. andl %reg1l,%reg1l
  4057. }
  4058. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  4059. MatchOpType(taicpu(p), top_reg, top_reg) and
  4060. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  4061. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  4062. begin
  4063. TransferUsedRegs(TmpUsedRegs);
  4064. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4065. taicpu(hp1).opsize := S_L;
  4066. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  4067. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4068. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  4069. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  4070. begin
  4071. { %reg1 = %reg3 }
  4072. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  4073. taicpu(hp1).opcode := A_AND;
  4074. end
  4075. else
  4076. begin
  4077. { %reg1 <> %reg3 }
  4078. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  4079. end;
  4080. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  4081. begin
  4082. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  4083. RemoveCurrentP(p, hp1);
  4084. Result := True;
  4085. Exit;
  4086. end
  4087. else
  4088. begin
  4089. { Initial instruction wasn't actually changed }
  4090. Include(OptsToCheck, aoc_ForceNewIteration);
  4091. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4092. appears below since %reg1 has technically changed }
  4093. if taicpu(hp1).opcode = A_AND then
  4094. Exit;
  4095. end;
  4096. end;
  4097. {$endif x86_64}
  4098. { search further than the next instruction for a mov (as long as it's not a jump) }
  4099. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  4100. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  4101. (taicpu(p).oper[1]^.typ = top_reg) and
  4102. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  4103. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  4104. begin
  4105. { we work with hp2 here, so hp1 can be still used later on when
  4106. checking for GetNextInstruction_p }
  4107. hp3 := hp1;
  4108. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  4109. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  4110. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4111. TransferUsedRegs(TmpUsedRegs);
  4112. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4113. if NotFirstIteration then
  4114. JumpTracking := TLinkedList.Create
  4115. else
  4116. JumpTracking := nil;
  4117. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  4118. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  4119. (hp2.typ=ait_instruction) do
  4120. begin
  4121. case taicpu(hp2).opcode of
  4122. A_POP:
  4123. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4124. begin
  4125. if not CrossJump and
  4126. not RegUsedBetween(p_TargetReg, p, hp2) then
  4127. begin
  4128. { We can remove the original MOV since the register
  4129. wasn't used between it and its popping from the stack }
  4130. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4131. RemoveCurrentp(p, hp1);
  4132. Result := True;
  4133. JumpTracking.Free;
  4134. Exit;
  4135. end;
  4136. { Can't go any further }
  4137. Break;
  4138. end;
  4139. A_MOV:
  4140. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4141. ((taicpu(p).oper[0]^.typ=top_const) or
  4142. ((taicpu(p).oper[0]^.typ=top_reg) and
  4143. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4144. )
  4145. ) then
  4146. begin
  4147. { we have
  4148. mov x, %treg
  4149. mov %treg, y
  4150. }
  4151. { We don't need to call UpdateUsedRegs for every instruction between
  4152. p and hp2 because the register we're concerned about will not
  4153. become deallocated (otherwise GetNextInstructionUsingReg would
  4154. have stopped at an earlier instruction). [Kit] }
  4155. TempRegUsed :=
  4156. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4157. RegReadByInstruction(p_TargetReg, hp3) or
  4158. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4159. case taicpu(p).oper[0]^.typ Of
  4160. top_reg:
  4161. begin
  4162. { change
  4163. mov %reg, %treg
  4164. mov %treg, y
  4165. to
  4166. mov %reg, y
  4167. }
  4168. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4169. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4170. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4171. begin
  4172. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4173. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4174. if TempRegUsed then
  4175. begin
  4176. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4177. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4178. { Set the start of the next GetNextInstructionUsingRegCond search
  4179. to start at the entry right before hp2 (which is about to be removed) }
  4180. hp3 := tai(hp2.Previous);
  4181. RemoveInstruction(hp2);
  4182. Include(OptsToCheck, aoc_ForceNewIteration);
  4183. { See if there's more we can optimise }
  4184. Continue;
  4185. end
  4186. else
  4187. begin
  4188. RemoveInstruction(hp2);
  4189. { We can remove the original MOV too }
  4190. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4191. RemoveCurrentP(p, hp1);
  4192. Result:=true;
  4193. JumpTracking.Free;
  4194. Exit;
  4195. end;
  4196. end
  4197. else
  4198. begin
  4199. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4200. taicpu(hp2).loadReg(0, p_SourceReg);
  4201. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4202. { Check to see if the register also appears in the reference }
  4203. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4204. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4205. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4206. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4207. begin
  4208. { Don't remove the first instruction if the temporary register is in use }
  4209. if not TempRegUsed then
  4210. begin
  4211. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4212. RemoveCurrentP(p, hp1);
  4213. Result:=true;
  4214. JumpTracking.Free;
  4215. Exit;
  4216. end;
  4217. { No need to set Result to True here. If there's another instruction later
  4218. on that can be optimised, it will be detected when the main Pass 1 loop
  4219. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4220. hp3 := hp2;
  4221. Continue;
  4222. end;
  4223. end;
  4224. end;
  4225. top_const:
  4226. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4227. begin
  4228. { change
  4229. mov const, %treg
  4230. mov %treg, y
  4231. to
  4232. mov const, y
  4233. }
  4234. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4235. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4236. begin
  4237. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4238. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4239. if TempRegUsed then
  4240. begin
  4241. { Don't remove the first instruction if the temporary register is in use }
  4242. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4243. { No need to set Result to True. If there's another instruction later on
  4244. that can be optimised, it will be detected when the main Pass 1 loop
  4245. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4246. end
  4247. else
  4248. begin
  4249. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4250. RemoveCurrentP(p, hp1);
  4251. Result:=true;
  4252. Exit;
  4253. end;
  4254. end;
  4255. end;
  4256. else
  4257. Internalerror(2019103001);
  4258. end;
  4259. end
  4260. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4261. begin
  4262. if not CrossJump and
  4263. not RegUsedBetween(p_TargetReg, p, hp2) and
  4264. not RegReadByInstruction(p_TargetReg, hp2) then
  4265. begin
  4266. { Register is not used before it is overwritten }
  4267. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4268. RemoveCurrentp(p, hp1);
  4269. Result := True;
  4270. Exit;
  4271. end;
  4272. if (taicpu(p).oper[0]^.typ = top_const) and
  4273. (taicpu(hp2).oper[0]^.typ = top_const) then
  4274. begin
  4275. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4276. begin
  4277. { Same value - register hasn't changed }
  4278. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4279. RemoveInstruction(hp2);
  4280. Include(OptsToCheck, aoc_ForceNewIteration);
  4281. { See if there's more we can optimise }
  4282. Continue;
  4283. end;
  4284. end;
  4285. {$ifdef x86_64}
  4286. end
  4287. { Change:
  4288. movl %reg1l,%reg2l
  4289. ...
  4290. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4291. To:
  4292. movl %reg1l,%reg2l
  4293. ...
  4294. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4295. If %reg1 = %reg3, convert to:
  4296. movl %reg1l,%reg2l
  4297. ...
  4298. andl %reg1l,%reg1l
  4299. }
  4300. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4301. (taicpu(p).oper[0]^.typ = top_reg) and
  4302. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4303. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4304. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2) then
  4305. begin
  4306. TempRegUsed :=
  4307. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4308. RegReadByInstruction(p_TargetReg, hp3) or
  4309. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4310. taicpu(hp2).opsize := S_L;
  4311. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4312. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4313. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4314. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4315. begin
  4316. { %reg1 = %reg3 }
  4317. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4318. taicpu(hp2).opcode := A_AND;
  4319. end
  4320. else
  4321. begin
  4322. { %reg1 <> %reg3 }
  4323. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4324. end;
  4325. if not TempRegUsed then
  4326. begin
  4327. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4328. RemoveCurrentP(p, hp1);
  4329. Result := True;
  4330. Exit;
  4331. end
  4332. else
  4333. begin
  4334. { Initial instruction wasn't actually changed }
  4335. Include(OptsToCheck, aoc_ForceNewIteration);
  4336. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4337. appears below since %reg1 has technically changed }
  4338. if taicpu(hp2).opcode = A_AND then
  4339. Break;
  4340. end;
  4341. {$endif x86_64}
  4342. end
  4343. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4344. GetNextInstruction(hp2, hp4) and
  4345. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4346. { Optimise the following first:
  4347. movl [mem1],reg1
  4348. movl [mem1],reg2
  4349. to
  4350. movl [mem1],reg1
  4351. movl reg1,reg2
  4352. If [mem1] contains the target register and reg1 is the
  4353. the source register, this optimisation will get missed
  4354. and produce less efficient code later on.
  4355. }
  4356. if CheckMovMov2MovMov2(hp2, hp4) then
  4357. { Initial instruction wasn't actually changed }
  4358. Include(OptsToCheck, aoc_ForceNewIteration);
  4359. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4360. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4361. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4362. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4363. begin
  4364. {
  4365. Change from:
  4366. mov ###, %reg
  4367. ...
  4368. movs/z %reg,%reg (Same register, just different sizes)
  4369. To:
  4370. movs/z ###, %reg (Longer version)
  4371. ...
  4372. (remove)
  4373. }
  4374. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4375. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4376. { Keep the first instruction as mov if ### is a constant }
  4377. if taicpu(p).oper[0]^.typ = top_const then
  4378. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4379. else
  4380. begin
  4381. taicpu(p).opcode := taicpu(hp2).opcode;
  4382. taicpu(p).opsize := taicpu(hp2).opsize;
  4383. end;
  4384. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4385. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4386. RemoveInstruction(hp2);
  4387. Result := True;
  4388. JumpTracking.Free;
  4389. Exit;
  4390. end;
  4391. else
  4392. { Move down to the if-block below };
  4393. end;
  4394. { Also catches MOV/S/Z instructions that aren't modified }
  4395. if taicpu(p).oper[0]^.typ = top_reg then
  4396. begin
  4397. p_SourceReg := taicpu(p).oper[0]^.reg;
  4398. if
  4399. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4400. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4401. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4402. begin
  4403. Result := True;
  4404. { Just in case something didn't get modified (e.g. an
  4405. implicit register). Also, if it does read from this
  4406. register, then there's no longer an advantage to
  4407. changing the register on subsequent instructions.}
  4408. if not RegReadByInstruction(p_TargetReg, hp2) then
  4409. begin
  4410. { If a conditional jump was crossed, do not delete
  4411. the original MOV no matter what }
  4412. if not CrossJump and
  4413. { RegEndOfLife returns True if the register is
  4414. deallocated before the next instruction or has
  4415. been loaded with a new value }
  4416. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4417. begin
  4418. { We can remove the original MOV }
  4419. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4420. RemoveCurrentp(p, hp1);
  4421. JumpTracking.Free;
  4422. Result := True;
  4423. Exit;
  4424. end;
  4425. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4426. begin
  4427. { See if there's more we can optimise }
  4428. hp3 := hp2;
  4429. Continue;
  4430. end;
  4431. end;
  4432. end;
  4433. end;
  4434. { Break out of the while loop under normal circumstances }
  4435. Break;
  4436. end;
  4437. JumpTracking.Free;
  4438. end;
  4439. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4440. (taicpu(p).oper[1]^.typ = top_reg) and
  4441. (taicpu(p).opsize = S_L) and
  4442. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4443. (hp2.typ = ait_instruction) and
  4444. (taicpu(hp2).opcode = A_AND) and
  4445. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4446. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4447. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4448. ) then
  4449. begin
  4450. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4451. begin
  4452. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4453. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4454. begin
  4455. { Optimize out:
  4456. mov x, %reg
  4457. and ffffffffh, %reg
  4458. }
  4459. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4460. RemoveInstruction(hp2);
  4461. Result:=true;
  4462. exit;
  4463. end;
  4464. end;
  4465. end;
  4466. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4467. x >= RetOffset) as it doesn't do anything (it writes either to a
  4468. parameter or to the temporary storage room for the function
  4469. result)
  4470. }
  4471. if IsExitCode(hp1) and
  4472. (taicpu(p).oper[1]^.typ = top_ref) and
  4473. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4474. (
  4475. (
  4476. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4477. not (
  4478. assigned(current_procinfo.procdef.funcretsym) and
  4479. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4480. )
  4481. ) or
  4482. { Also discard writes to the stack that are below the base pointer,
  4483. as this is temporary storage rather than a function result on the
  4484. stack, say. }
  4485. (
  4486. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4487. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4488. )
  4489. ) then
  4490. begin
  4491. RemoveCurrentp(p, hp1);
  4492. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4493. RemoveLastDeallocForFuncRes(p);
  4494. Result:=true;
  4495. exit;
  4496. end;
  4497. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4498. begin
  4499. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4500. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4501. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4502. begin
  4503. { change
  4504. mov reg1, mem1
  4505. test/cmp x, mem1
  4506. to
  4507. mov reg1, mem1
  4508. test/cmp x, reg1
  4509. }
  4510. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4511. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4512. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4513. Result := True;
  4514. Exit;
  4515. end;
  4516. if DoMovCmpMemOpt(p, hp1) then
  4517. begin
  4518. Result := True;
  4519. Exit;
  4520. end;
  4521. end;
  4522. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4523. { If the flags register is in use, don't change the instruction to an
  4524. ADD otherwise this will scramble the flags. [Kit] }
  4525. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4526. begin
  4527. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4528. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4529. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4530. ) or
  4531. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4532. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4533. )
  4534. ) then
  4535. { mov reg1,ref
  4536. lea reg2,[reg1,reg2]
  4537. to
  4538. add reg2,ref}
  4539. begin
  4540. TransferUsedRegs(TmpUsedRegs);
  4541. { reg1 may not be used afterwards }
  4542. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4543. begin
  4544. Taicpu(hp1).opcode:=A_ADD;
  4545. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4546. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4547. RemoveCurrentp(p, hp1);
  4548. result:=true;
  4549. exit;
  4550. end;
  4551. end;
  4552. { If the LEA instruction can be converted into an arithmetic instruction,
  4553. it may be possible to then fold it in the next optimisation, otherwise
  4554. there's nothing more that can be optimised here. }
  4555. if not ConvertLEA(taicpu(hp1)) then
  4556. Exit;
  4557. end;
  4558. if (taicpu(p).oper[1]^.typ = top_reg) and
  4559. (hp1.typ = ait_instruction) and
  4560. GetNextInstruction(hp1, hp2) and
  4561. MatchInstruction(hp2,A_MOV,[]) and
  4562. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4563. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4564. (
  4565. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4566. {$ifdef x86_64}
  4567. or
  4568. (
  4569. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4570. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4571. )
  4572. {$endif x86_64}
  4573. ) then
  4574. begin
  4575. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4576. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4577. { change movsX/movzX reg/ref, reg2
  4578. add/sub/or/... reg3/$const, reg2
  4579. mov reg2 reg/ref
  4580. dealloc reg2
  4581. to
  4582. add/sub/or/... reg3/$const, reg/ref }
  4583. begin
  4584. TransferUsedRegs(TmpUsedRegs);
  4585. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4586. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4587. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4588. begin
  4589. { by example:
  4590. movswl %si,%eax movswl %si,%eax p
  4591. decl %eax addl %edx,%eax hp1
  4592. movw %ax,%si movw %ax,%si hp2
  4593. ->
  4594. movswl %si,%eax movswl %si,%eax p
  4595. decw %eax addw %edx,%eax hp1
  4596. movw %ax,%si movw %ax,%si hp2
  4597. }
  4598. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4599. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4600. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4601. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4602. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4603. {
  4604. ->
  4605. movswl %si,%eax movswl %si,%eax p
  4606. decw %si addw %dx,%si hp1
  4607. movw %ax,%si movw %ax,%si hp2
  4608. }
  4609. case taicpu(hp1).ops of
  4610. 1:
  4611. begin
  4612. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4613. if taicpu(hp1).oper[0]^.typ=top_reg then
  4614. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4615. end;
  4616. 2:
  4617. begin
  4618. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4619. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4620. (taicpu(hp1).opcode<>A_SHL) and
  4621. (taicpu(hp1).opcode<>A_SHR) and
  4622. (taicpu(hp1).opcode<>A_SAR) then
  4623. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4624. end;
  4625. else
  4626. internalerror(2008042701);
  4627. end;
  4628. {
  4629. ->
  4630. decw %si addw %dx,%si p
  4631. }
  4632. RemoveInstruction(hp2);
  4633. RemoveCurrentP(p, hp1);
  4634. Result:=True;
  4635. Exit;
  4636. end;
  4637. end;
  4638. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4639. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4640. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4641. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4642. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4643. )
  4644. {$ifdef i386}
  4645. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4646. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4647. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4648. {$endif i386}
  4649. then
  4650. { change movsX/movzX reg/ref, reg2
  4651. add/sub/or/... regX/$const, reg2
  4652. mov reg2, reg3
  4653. dealloc reg2
  4654. to
  4655. movsX/movzX reg/ref, reg3
  4656. add/sub/or/... reg3/$const, reg3
  4657. }
  4658. begin
  4659. TransferUsedRegs(TmpUsedRegs);
  4660. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4661. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4662. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4663. begin
  4664. { by example:
  4665. movswl %si,%eax movswl %si,%eax p
  4666. decl %eax addl %edx,%eax hp1
  4667. movw %ax,%si movw %ax,%si hp2
  4668. ->
  4669. movswl %si,%eax movswl %si,%eax p
  4670. decw %eax addw %edx,%eax hp1
  4671. movw %ax,%si movw %ax,%si hp2
  4672. }
  4673. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4674. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4675. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4676. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4677. { limit size of constants as well to avoid assembler errors, but
  4678. check opsize to avoid overflow when left shifting the 1 }
  4679. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4680. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4681. {$ifdef x86_64}
  4682. { Be careful of, for example:
  4683. movl %reg1,%reg2
  4684. addl %reg3,%reg2
  4685. movq %reg2,%reg4
  4686. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4687. }
  4688. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4689. begin
  4690. taicpu(hp2).changeopsize(S_L);
  4691. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4692. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4693. end;
  4694. {$endif x86_64}
  4695. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4696. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4697. if taicpu(p).oper[0]^.typ=top_reg then
  4698. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4699. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4700. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4701. {
  4702. ->
  4703. movswl %si,%eax movswl %si,%eax p
  4704. decw %si addw %dx,%si hp1
  4705. movw %ax,%si movw %ax,%si hp2
  4706. }
  4707. case taicpu(hp1).ops of
  4708. 1:
  4709. begin
  4710. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4711. if taicpu(hp1).oper[0]^.typ=top_reg then
  4712. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4713. end;
  4714. 2:
  4715. begin
  4716. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4717. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4718. (taicpu(hp1).opcode<>A_SHL) and
  4719. (taicpu(hp1).opcode<>A_SHR) and
  4720. (taicpu(hp1).opcode<>A_SAR) then
  4721. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4722. end;
  4723. else
  4724. internalerror(2018111801);
  4725. end;
  4726. {
  4727. ->
  4728. decw %si addw %dx,%si p
  4729. }
  4730. RemoveInstruction(hp2);
  4731. end;
  4732. end;
  4733. end;
  4734. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4735. GetNextInstruction(hp1, hp2) and
  4736. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4737. MatchOperand(Taicpu(p).oper[0]^,0) and
  4738. (Taicpu(p).oper[1]^.typ = top_reg) and
  4739. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4740. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4741. { mov reg1,0
  4742. bts reg1,operand1 --> mov reg1,operand2
  4743. or reg1,operand2 bts reg1,operand1}
  4744. begin
  4745. Taicpu(hp2).opcode:=A_MOV;
  4746. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4747. asml.remove(hp1);
  4748. insertllitem(hp2,hp2.next,hp1);
  4749. RemoveCurrentp(p, hp1);
  4750. Result:=true;
  4751. exit;
  4752. end;
  4753. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4754. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4755. GetNextInstruction(hp1, hp2) and
  4756. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4757. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4758. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4759. { change
  4760. mov reg1,reg2
  4761. sub reg3,reg2
  4762. cmp reg3,reg1
  4763. into
  4764. mov reg1,reg2
  4765. sub reg3,reg2
  4766. }
  4767. begin
  4768. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4769. RemoveInstruction(hp2);
  4770. Result:=true;
  4771. exit;
  4772. end;
  4773. {
  4774. mov ref,reg0
  4775. <op> reg0,reg1
  4776. dealloc reg0
  4777. to
  4778. <op> ref,reg1
  4779. }
  4780. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4781. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4782. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4783. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4784. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4785. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4786. begin
  4787. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4788. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4789. RemoveCurrentp(p, hp1);
  4790. Result:=true;
  4791. exit;
  4792. end;
  4793. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4794. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4795. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4796. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4797. begin
  4798. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4799. {$ifdef x86_64}
  4800. { Convert:
  4801. movq x(ref),%reg64
  4802. shrq y,%reg64
  4803. To:
  4804. movl x+4(ref),%reg32
  4805. shrl y-32,%reg32 (Remove if y = 32)
  4806. }
  4807. if (taicpu(p).opsize = S_Q) and
  4808. (taicpu(hp1).opcode = A_SHR) and
  4809. (taicpu(hp1).oper[0]^.val >= 32) then
  4810. begin
  4811. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4812. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4813. { Convert to 32-bit }
  4814. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4815. taicpu(p).opsize := S_L;
  4816. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4817. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4818. if (taicpu(hp1).oper[0]^.val = 32) then
  4819. begin
  4820. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4821. RemoveInstruction(hp1);
  4822. end
  4823. else
  4824. begin
  4825. { This will potentially open up more arithmetic operations since
  4826. the peephole optimizer now has a big hint that only the lower
  4827. 32 bits are currently in use (and opcodes are smaller in size) }
  4828. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4829. taicpu(hp1).opsize := S_L;
  4830. Dec(taicpu(hp1).oper[0]^.val, 32);
  4831. DebugMsg(SPeepholeOptimization + PreMessage +
  4832. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4833. end;
  4834. Result := True;
  4835. Exit;
  4836. end;
  4837. {$endif x86_64}
  4838. { Convert:
  4839. movl x(ref),%reg
  4840. shrl $24,%reg
  4841. To:
  4842. movzbl x+3(ref),%reg
  4843. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4844. Also accept sar instead of shr, but convert to movsx instead of movzx
  4845. }
  4846. if taicpu(hp1).opcode = A_SHR then
  4847. MovUnaligned := A_MOVZX
  4848. else
  4849. MovUnaligned := A_MOVSX;
  4850. NewSize := S_NO;
  4851. NewOffset := 0;
  4852. case taicpu(p).opsize of
  4853. S_B:
  4854. { No valid combinations };
  4855. S_W:
  4856. if (taicpu(hp1).oper[0]^.val = 8) then
  4857. begin
  4858. NewSize := S_BW;
  4859. NewOffset := 1;
  4860. end;
  4861. S_L:
  4862. case taicpu(hp1).oper[0]^.val of
  4863. 16:
  4864. begin
  4865. NewSize := S_WL;
  4866. NewOffset := 2;
  4867. end;
  4868. 24:
  4869. begin
  4870. NewSize := S_BL;
  4871. NewOffset := 3;
  4872. end;
  4873. else
  4874. ;
  4875. end;
  4876. {$ifdef x86_64}
  4877. S_Q:
  4878. case taicpu(hp1).oper[0]^.val of
  4879. 32:
  4880. begin
  4881. if taicpu(hp1).opcode = A_SAR then
  4882. begin
  4883. { 32-bit to 64-bit is a distinct instruction }
  4884. MovUnaligned := A_MOVSXD;
  4885. NewSize := S_LQ;
  4886. NewOffset := 4;
  4887. end
  4888. else
  4889. { Should have been handled by MovShr2Mov above }
  4890. InternalError(2022081811);
  4891. end;
  4892. 48:
  4893. begin
  4894. NewSize := S_WQ;
  4895. NewOffset := 6;
  4896. end;
  4897. 56:
  4898. begin
  4899. NewSize := S_BQ;
  4900. NewOffset := 7;
  4901. end;
  4902. else
  4903. ;
  4904. end;
  4905. {$endif x86_64}
  4906. else
  4907. InternalError(2022081810);
  4908. end;
  4909. if (NewSize <> S_NO) and
  4910. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4911. begin
  4912. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4913. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4914. debug_op2str(MovUnaligned);
  4915. {$ifdef x86_64}
  4916. if MovUnaligned <> A_MOVSXD then
  4917. { Don't add size suffix for MOVSXD }
  4918. {$endif x86_64}
  4919. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4920. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4921. taicpu(p).opcode := MovUnaligned;
  4922. taicpu(p).opsize := NewSize;
  4923. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4924. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4925. RemoveInstruction(hp1);
  4926. Result := True;
  4927. Exit;
  4928. end;
  4929. end;
  4930. { Backward optimisation shared with OptPass2MOV }
  4931. if FuncMov2Func(p, hp1) then
  4932. begin
  4933. Result := True;
  4934. Exit;
  4935. end;
  4936. end;
  4937. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4938. var
  4939. hp1 : tai;
  4940. begin
  4941. Result:=false;
  4942. if taicpu(p).ops <> 2 then
  4943. exit;
  4944. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4945. GetNextInstruction(p,hp1) then
  4946. begin
  4947. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4948. (taicpu(hp1).ops = 2) then
  4949. begin
  4950. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4951. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4952. { movXX reg1, mem1 or movXX mem1, reg1
  4953. movXX mem2, reg2 movXX reg2, mem2}
  4954. begin
  4955. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4956. { movXX reg1, mem1 or movXX mem1, reg1
  4957. movXX mem2, reg1 movXX reg2, mem1}
  4958. begin
  4959. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4960. begin
  4961. { Removes the second statement from
  4962. movXX reg1, mem1/reg2
  4963. movXX mem1/reg2, reg1
  4964. }
  4965. if taicpu(p).oper[0]^.typ=top_reg then
  4966. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4967. { Removes the second statement from
  4968. movXX mem1/reg1, reg2
  4969. movXX reg2, mem1/reg1
  4970. }
  4971. if (taicpu(p).oper[1]^.typ=top_reg) and
  4972. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4973. begin
  4974. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4975. RemoveInstruction(hp1);
  4976. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4977. Result:=true;
  4978. exit;
  4979. end
  4980. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4981. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4982. begin
  4983. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4984. RemoveInstruction(hp1);
  4985. Result:=true;
  4986. exit;
  4987. end;
  4988. end
  4989. end;
  4990. end;
  4991. end;
  4992. end;
  4993. end;
  4994. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4995. var
  4996. hp1 : tai;
  4997. begin
  4998. result:=false;
  4999. { replace
  5000. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  5001. MovX %mreg2,%mreg1
  5002. dealloc %mreg2
  5003. by
  5004. <Op>X %mreg2,%mreg1
  5005. ?
  5006. }
  5007. if GetNextInstruction(p,hp1) and
  5008. { we mix single and double opperations here because we assume that the compiler
  5009. generates vmovapd only after double operations and vmovaps only after single operations }
  5010. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5011. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5012. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  5013. (taicpu(p).oper[0]^.typ=top_reg) then
  5014. begin
  5015. TransferUsedRegs(TmpUsedRegs);
  5016. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5017. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5018. begin
  5019. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  5020. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5021. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  5022. RemoveInstruction(hp1);
  5023. result:=true;
  5024. end;
  5025. end;
  5026. end;
  5027. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  5028. var
  5029. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  5030. JumpLabel, JumpLabel_dist: TAsmLabel;
  5031. FirstValue, SecondValue: TCGInt;
  5032. function OptimizeJump(var InputP: tai): Boolean;
  5033. var
  5034. TempBool: Boolean;
  5035. begin
  5036. Result := False;
  5037. TempBool := True;
  5038. if DoJumpOptimizations(InputP, TempBool) or
  5039. not TempBool then
  5040. begin
  5041. Result := True;
  5042. if Assigned(InputP) then
  5043. begin
  5044. { CollapseZeroDistJump will be set to the label or an align
  5045. before it after the jump if it optimises, whether or not
  5046. the label is live or dead }
  5047. if (InputP.typ = ait_align) or
  5048. (
  5049. (InputP.typ = ait_label) and
  5050. not (tai_label(InputP).labsym.is_used)
  5051. ) then
  5052. GetNextInstruction(InputP, InputP);
  5053. end;
  5054. Exit;
  5055. end;
  5056. end;
  5057. begin
  5058. Result := False;
  5059. if (taicpu(p).oper[0]^.typ = top_const) and
  5060. (taicpu(p).oper[0]^.val <> -1) then
  5061. begin
  5062. { Convert unsigned maximum constants to -1 to aid optimisation }
  5063. case taicpu(p).opsize of
  5064. S_B:
  5065. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  5066. begin
  5067. taicpu(p).oper[0]^.val := -1;
  5068. Result := True;
  5069. Exit;
  5070. end;
  5071. S_W:
  5072. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  5073. begin
  5074. taicpu(p).oper[0]^.val := -1;
  5075. Result := True;
  5076. Exit;
  5077. end;
  5078. S_L:
  5079. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  5080. begin
  5081. taicpu(p).oper[0]^.val := -1;
  5082. Result := True;
  5083. Exit;
  5084. end;
  5085. {$ifdef x86_64}
  5086. S_Q:
  5087. { Storing anything greater than $7FFFFFFF is not possible so do
  5088. nothing };
  5089. {$endif x86_64}
  5090. else
  5091. InternalError(2021121001);
  5092. end;
  5093. end;
  5094. if GetNextInstruction(p, hp1) and
  5095. TrySwapMovCmp(p, hp1) then
  5096. begin
  5097. Result := True;
  5098. Exit;
  5099. end;
  5100. p_label := nil;
  5101. JumpLabel := nil;
  5102. if MatchInstruction(hp1, A_Jcc, []) then
  5103. begin
  5104. if OptimizeJump(hp1) then
  5105. begin
  5106. Result := True;
  5107. if Assigned(hp1) then
  5108. begin
  5109. { CollapseZeroDistJump will be set to the label or an align
  5110. before it after the jump if it optimises, whether or not
  5111. the label is live or dead }
  5112. if (hp1.typ = ait_align) or
  5113. (
  5114. (hp1.typ = ait_label) and
  5115. not (tai_label(hp1).labsym.is_used)
  5116. ) then
  5117. GetNextInstruction(hp1, hp1);
  5118. end;
  5119. TransferUsedRegs(TmpUsedRegs);
  5120. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5121. if not Assigned(hp1) or
  5122. (
  5123. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5124. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5125. ) then
  5126. begin
  5127. { No more conditional jumps; conditional statement is no longer required }
  5128. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5129. RemoveCurrentP(p);
  5130. end;
  5131. Exit;
  5132. end;
  5133. if IsJumpToLabel(taicpu(hp1)) then
  5134. begin
  5135. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5136. if Assigned(JumpLabel) then
  5137. p_label := getlabelwithsym(JumpLabel);
  5138. end;
  5139. end;
  5140. { Search for:
  5141. test $x,(reg/ref)
  5142. jne @lbl1
  5143. test $y,(reg/ref) (same register or reference)
  5144. jne @lbl1
  5145. Change to:
  5146. test $(x or y),(reg/ref)
  5147. jne @lbl1
  5148. (Note, this doesn't work with je instead of jne)
  5149. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5150. Also search for:
  5151. test $x,(reg/ref)
  5152. je @lbl1
  5153. ...
  5154. test $y,(reg/ref)
  5155. je/jne @lbl2
  5156. If (x or y) = x, then the second jump is deterministic
  5157. }
  5158. if (
  5159. (
  5160. (taicpu(p).oper[0]^.typ = top_const) or
  5161. (
  5162. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5163. (taicpu(p).oper[0]^.typ = top_reg) and
  5164. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5165. )
  5166. ) and
  5167. MatchInstruction(hp1, A_JCC, [])
  5168. ) then
  5169. begin
  5170. if (taicpu(p).oper[0]^.typ = top_reg) and
  5171. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5172. FirstValue := -1
  5173. else
  5174. FirstValue := taicpu(p).oper[0]^.val;
  5175. { If we have several test/jne's in a row, it might be the case that
  5176. the second label doesn't go to the same location, but the one
  5177. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5178. so accommodate for this with a while loop.
  5179. }
  5180. hp1_last := hp1;
  5181. while (
  5182. (
  5183. (taicpu(p).oper[1]^.typ = top_reg) and
  5184. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5185. ) or GetNextInstruction(hp1_last, p_dist)
  5186. ) and (p_dist.typ = ait_instruction) do
  5187. begin
  5188. if (
  5189. (
  5190. (taicpu(p_dist).opcode = A_TEST) and
  5191. (
  5192. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5193. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5194. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5195. )
  5196. ) or
  5197. (
  5198. { cmp 0,%reg = test %reg,%reg }
  5199. (taicpu(p_dist).opcode = A_CMP) and
  5200. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5201. )
  5202. ) and
  5203. { Make sure the destination operands are actually the same }
  5204. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5205. GetNextInstruction(p_dist, hp1_dist) and
  5206. MatchInstruction(hp1_dist, A_JCC, []) then
  5207. begin
  5208. if OptimizeJump(hp1_dist) then
  5209. begin
  5210. Result := True;
  5211. Exit;
  5212. end;
  5213. if
  5214. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5215. (
  5216. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5217. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5218. ) then
  5219. SecondValue := -1
  5220. else
  5221. SecondValue := taicpu(p_dist).oper[0]^.val;
  5222. { If both of the TEST constants are identical, delete the
  5223. second TEST that is unnecessary (be careful though, just
  5224. in case the flags are modified in between) }
  5225. if (FirstValue = SecondValue) then
  5226. begin
  5227. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5228. begin
  5229. { Since the second jump's condition is a subset of the first, we
  5230. know it will never branch because the first jump dominates it.
  5231. Get it out of the way now rather than wait for the jump
  5232. optimisations for a speed boost. }
  5233. if IsJumpToLabel(taicpu(hp1_dist)) then
  5234. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5235. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5236. RemoveInstruction(hp1_dist);
  5237. Result := True;
  5238. end
  5239. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5240. begin
  5241. { If the inverse of the first condition is a subset of the second,
  5242. the second one will definitely branch if the first one doesn't }
  5243. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5244. { We can remove the TEST instruction too }
  5245. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5246. RemoveInstruction(p_dist);
  5247. MakeUnconditional(taicpu(hp1_dist));
  5248. RemoveDeadCodeAfterJump(hp1_dist);
  5249. { Since the jump is now unconditional, we can't
  5250. continue any further with this particular
  5251. optimisation. The original TEST is still intact
  5252. though, so there might be something else we can
  5253. do }
  5254. Include(OptsToCheck, aoc_ForceNewIteration);
  5255. Break;
  5256. end;
  5257. if Result or
  5258. { If a jump wasn't removed or made unconditional, only
  5259. remove the identical TEST instruction if the flags
  5260. weren't modified }
  5261. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5262. begin
  5263. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5264. RemoveInstruction(p_dist);
  5265. { If the jump was removed or made unconditional, we
  5266. don't need to allocate NR_DEFAULTFLAGS over the
  5267. entire range }
  5268. if not Result then
  5269. begin
  5270. { Mark the flags as 'in use' over the entire range }
  5271. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5272. { Speed gain - continue search from the Jcc instruction }
  5273. hp1_last := hp1_dist;
  5274. { Only the TEST instruction was removed, and the
  5275. original was unchanged, so we can safely do
  5276. another iteration of the while loop }
  5277. Include(OptsToCheck, aoc_ForceNewIteration);
  5278. Continue;
  5279. end;
  5280. Exit;
  5281. end;
  5282. end;
  5283. hp1_last := nil;
  5284. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5285. (
  5286. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5287. { Always adjacent under -O2 and under }
  5288. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5289. (
  5290. GetNextInstruction(hp1, hp1_last) and
  5291. (hp1_last = p_dist)
  5292. )
  5293. ) and
  5294. (
  5295. (
  5296. { Test the following variant:
  5297. test $x,(reg/ref)
  5298. jne @lbl1
  5299. test $y,(reg/ref)
  5300. je @lbl2
  5301. @lbl1:
  5302. Becomes:
  5303. test $(x or y),(reg/ref)
  5304. je @lbl2
  5305. @lbl1: (may become a dead label)
  5306. }
  5307. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5308. GetNextInstruction(hp1_dist, hp1_last) and
  5309. (hp1_last = p_label)
  5310. ) or
  5311. (
  5312. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5313. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5314. then the second jump will never branch, so it can also be
  5315. removed regardless of where it goes }
  5316. (
  5317. (FirstValue = -1) or
  5318. (SecondValue = -1) or
  5319. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5320. )
  5321. )
  5322. ) then
  5323. begin
  5324. { Same jump location... can be a register since nothing's changed }
  5325. { If any of the entries are equivalent to test %reg,%reg, then the
  5326. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5327. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5328. if (hp1_last = p_label) then
  5329. begin
  5330. { Variant }
  5331. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5332. RemoveInstruction(p_dist);
  5333. if Assigned(JumpLabel) then
  5334. JumpLabel.decrefs;
  5335. RemoveInstruction(hp1);
  5336. end
  5337. else
  5338. begin
  5339. { Only remove the second test if no jumps or other conditional instructions follow }
  5340. TransferUsedRegs(TmpUsedRegs);
  5341. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5342. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5343. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5344. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5345. begin
  5346. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5347. RemoveInstruction(p_dist);
  5348. { Remove the first jump, not the second, to keep
  5349. any register deallocations between the second
  5350. TEST/JNE pair in the same place. Aids future
  5351. optimisation. }
  5352. if Assigned(JumpLabel) then
  5353. JumpLabel.decrefs;
  5354. RemoveInstruction(hp1);
  5355. end
  5356. else
  5357. begin
  5358. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5359. if IsJumpToLabel(taicpu(hp1_dist)) then
  5360. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5361. { Remove second jump in this instance }
  5362. RemoveInstruction(hp1_dist);
  5363. end;
  5364. end;
  5365. Result := True;
  5366. Exit;
  5367. end;
  5368. end;
  5369. if { If -O2 and under, it may stop on any old instruction }
  5370. (cs_opt_level3 in current_settings.optimizerswitches) and
  5371. (taicpu(p).oper[1]^.typ = top_reg) and
  5372. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5373. begin
  5374. hp1_last := p_dist;
  5375. Continue;
  5376. end;
  5377. Break;
  5378. end;
  5379. end;
  5380. { Search for:
  5381. test %reg,%reg
  5382. j(c1) @lbl1
  5383. ...
  5384. @lbl:
  5385. test %reg,%reg (same register)
  5386. j(c2) @lbl2
  5387. If c2 is a subset of c1, change to:
  5388. test %reg,%reg
  5389. j(c1) @lbl2
  5390. (@lbl1 may become a dead label as a result)
  5391. }
  5392. if (taicpu(p).oper[1]^.typ = top_reg) and
  5393. (taicpu(p).oper[0]^.typ = top_reg) and
  5394. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5395. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5396. Assigned(p_label) and
  5397. GetNextInstruction(p_label, p_dist) and
  5398. MatchInstruction(p_dist, A_TEST, []) and
  5399. { It's fine if the second test uses smaller sub-registers }
  5400. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5401. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5402. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5403. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5404. GetNextInstruction(p_dist, hp1_dist) and
  5405. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5406. begin
  5407. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5408. if JumpLabel = JumpLabel_dist then
  5409. { This is an infinite loop }
  5410. Exit;
  5411. { Best optimisation when the first condition is a subset (or equal) of the second }
  5412. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5413. begin
  5414. { Any registers used here will already be allocated }
  5415. if Assigned(JumpLabel) then
  5416. JumpLabel.DecRefs;
  5417. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5418. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5419. Result := True;
  5420. Exit;
  5421. end;
  5422. end;
  5423. end;
  5424. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5425. var
  5426. hp1, hp2: tai;
  5427. ActiveReg: TRegister;
  5428. OldOffset: asizeint;
  5429. ThisConst: TCGInt;
  5430. function RegDeallocated: Boolean;
  5431. begin
  5432. TransferUsedRegs(TmpUsedRegs);
  5433. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5434. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5435. end;
  5436. begin
  5437. result:=false;
  5438. hp1 := nil;
  5439. { replace
  5440. addX const,%reg1
  5441. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5442. dealloc %reg1
  5443. by
  5444. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5445. }
  5446. if MatchOpType(taicpu(p),top_const,top_reg) then
  5447. begin
  5448. ActiveReg := taicpu(p).oper[1]^.reg;
  5449. { Ensures the entire register was updated }
  5450. if (taicpu(p).opsize >= S_L) and
  5451. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5452. MatchInstruction(hp1,A_LEA,[]) and
  5453. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5454. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5455. (
  5456. { Cover the case where the register in the reference is also the destination register }
  5457. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5458. (
  5459. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5460. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5461. RegDeallocated
  5462. )
  5463. ) then
  5464. begin
  5465. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5466. {$push}
  5467. {$R-}{$Q-}
  5468. { Explicitly disable overflow checking for these offset calculation
  5469. as those do not matter for the final result }
  5470. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5471. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5472. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5473. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5474. {$pop}
  5475. {$ifdef x86_64}
  5476. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5477. begin
  5478. { Overflow; abort }
  5479. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5480. end
  5481. else
  5482. {$endif x86_64}
  5483. begin
  5484. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5485. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5486. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5487. RemoveCurrentP(p, hp1)
  5488. else
  5489. RemoveCurrentP(p);
  5490. result:=true;
  5491. Exit;
  5492. end;
  5493. end;
  5494. if (
  5495. { Save calling GetNextInstructionUsingReg again }
  5496. Assigned(hp1) or
  5497. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5498. ) and
  5499. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5500. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5501. begin
  5502. if taicpu(hp1).oper[0]^.typ = top_const then
  5503. begin
  5504. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5505. if taicpu(hp1).opcode = A_ADD then
  5506. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5507. else
  5508. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5509. Result := True;
  5510. { Handle any overflows }
  5511. case taicpu(p).opsize of
  5512. S_B:
  5513. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5514. S_W:
  5515. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5516. S_L:
  5517. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5518. {$ifdef x86_64}
  5519. S_Q:
  5520. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5521. { Overflow; abort }
  5522. Result := False
  5523. else
  5524. taicpu(p).oper[0]^.val := ThisConst;
  5525. {$endif x86_64}
  5526. else
  5527. InternalError(2021102610);
  5528. end;
  5529. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5530. if Result then
  5531. begin
  5532. if (taicpu(p).oper[0]^.val < 0) and
  5533. (
  5534. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5535. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5536. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5537. ) then
  5538. begin
  5539. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5540. taicpu(p).opcode := A_SUB;
  5541. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5542. end
  5543. else
  5544. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5545. RemoveInstruction(hp1);
  5546. end;
  5547. end
  5548. else
  5549. begin
  5550. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5551. TransferUsedRegs(TmpUsedRegs);
  5552. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5553. hp2 := p;
  5554. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5555. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5556. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5557. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5558. begin
  5559. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5560. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5561. Asml.Remove(p);
  5562. Asml.InsertAfter(p, hp1);
  5563. p := hp1;
  5564. Result := True;
  5565. Exit;
  5566. end;
  5567. end;
  5568. end;
  5569. if DoArithCombineOpt(p) then
  5570. Result:=true;
  5571. end;
  5572. end;
  5573. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5574. var
  5575. hp1, hp2: tai;
  5576. ref: Integer;
  5577. saveref: treference;
  5578. offsetcalc: Int64;
  5579. TempReg: TRegister;
  5580. Multiple: TCGInt;
  5581. Adjacent, IntermediateRegDiscarded: Boolean;
  5582. begin
  5583. Result:=false;
  5584. { play save and throw an error if LEA uses a seg register prefix,
  5585. this is most likely an error somewhere else }
  5586. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5587. internalerror(2022022001);
  5588. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5589. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5590. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5591. (
  5592. { do not mess with leas accessing the stack pointer
  5593. unless it's a null operation }
  5594. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5595. (
  5596. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5597. (taicpu(p).oper[0]^.ref^.offset = 0)
  5598. )
  5599. ) and
  5600. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5601. begin
  5602. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5603. begin
  5604. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5605. begin
  5606. taicpu(p).opcode := A_MOV;
  5607. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5608. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5609. end
  5610. else
  5611. begin
  5612. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5613. RemoveCurrentP(p);
  5614. end;
  5615. Result:=true;
  5616. exit;
  5617. end
  5618. else if (
  5619. { continue to use lea to adjust the stack pointer,
  5620. it is the recommended way, but only if not optimizing for size }
  5621. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5622. (cs_opt_size in current_settings.optimizerswitches)
  5623. ) and
  5624. { If the flags register is in use, don't change the instruction
  5625. to an ADD otherwise this will scramble the flags. [Kit] }
  5626. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5627. ConvertLEA(taicpu(p)) then
  5628. begin
  5629. Result:=true;
  5630. exit;
  5631. end;
  5632. end;
  5633. { Don't optimise if the stack or frame pointer is the destination register }
  5634. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5635. Exit;
  5636. if GetNextInstruction(p,hp1) and
  5637. (hp1.typ=ait_instruction) then
  5638. begin
  5639. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5640. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5641. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5642. begin
  5643. TransferUsedRegs(TmpUsedRegs);
  5644. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5645. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5646. begin
  5647. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5648. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5649. RemoveInstruction(hp1);
  5650. result:=true;
  5651. exit;
  5652. end;
  5653. end;
  5654. { changes
  5655. lea <ref1>, reg1
  5656. <op> ...,<ref. with reg1>,...
  5657. to
  5658. <op> ...,<ref1>,... }
  5659. { find a reference which uses reg1 }
  5660. 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
  5661. ref:=0
  5662. 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
  5663. ref:=1
  5664. else
  5665. ref:=-1;
  5666. if (ref<>-1) and
  5667. { reg1 must be either the base or the index }
  5668. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5669. begin
  5670. { reg1 can be removed from the reference }
  5671. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5672. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5673. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5674. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5675. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5676. else
  5677. Internalerror(2019111201);
  5678. { check if the can insert all data of the lea into the second instruction }
  5679. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5680. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5681. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5682. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5683. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5684. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5685. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5686. {$ifdef x86_64}
  5687. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5688. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5689. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5690. )
  5691. {$endif x86_64}
  5692. then
  5693. begin
  5694. { reg1 might not used by the second instruction after it is remove from the reference }
  5695. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5696. begin
  5697. TransferUsedRegs(TmpUsedRegs);
  5698. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5699. { reg1 is not updated so it might not be used afterwards }
  5700. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5701. begin
  5702. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5703. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5704. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5705. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5706. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5707. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5708. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5709. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5710. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5711. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5712. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5713. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5714. RemoveCurrentP(p, hp1);
  5715. result:=true;
  5716. exit;
  5717. end
  5718. end;
  5719. end;
  5720. { recover }
  5721. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5722. end;
  5723. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5724. if Adjacent or
  5725. { Check further ahead (up to 2 instructions ahead for -O2) }
  5726. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5727. begin
  5728. { Check common LEA/LEA conditions }
  5729. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5730. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5731. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5732. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5733. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5734. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5735. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5736. (
  5737. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5738. calling it (since it calls GetNextInstruction) }
  5739. Adjacent or
  5740. (
  5741. (
  5742. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5743. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5744. ) and (
  5745. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5746. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5747. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5748. )
  5749. )
  5750. ) then
  5751. begin
  5752. TransferUsedRegs(TmpUsedRegs);
  5753. hp2 := p;
  5754. repeat
  5755. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5756. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5757. IntermediateRegDiscarded :=
  5758. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5759. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5760. { changes
  5761. lea offset1(regX,scale), reg1
  5762. lea offset2(reg1,reg1), reg2
  5763. to
  5764. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5765. and
  5766. lea offset1(regX,scale1), reg1
  5767. lea offset2(reg1,scale2), reg2
  5768. to
  5769. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5770. and
  5771. lea offset1(regX,scale1), reg1
  5772. lea offset2(reg3,reg1,scale2), reg2
  5773. to
  5774. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5775. ... so long as the final scale does not exceed 8
  5776. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5777. }
  5778. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5779. (
  5780. { Don't optimise if size is a concern and the intermediate register remains in use }
  5781. IntermediateRegDiscarded or
  5782. not (cs_opt_size in current_settings.optimizerswitches)
  5783. ) and
  5784. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5785. (
  5786. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5787. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5788. ) and (
  5789. (
  5790. { lea (reg1,scale2), reg2 variant }
  5791. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5792. (
  5793. Adjacent or
  5794. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5795. ) and
  5796. (
  5797. (
  5798. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5799. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5800. ) or (
  5801. { lea (regX,regX), reg1 variant }
  5802. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5803. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5804. )
  5805. )
  5806. ) or (
  5807. { lea (reg1,reg1), reg1 variant }
  5808. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5809. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5810. )
  5811. ) then
  5812. begin
  5813. { Make everything homogeneous to make calculations easier }
  5814. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5815. begin
  5816. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5817. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5818. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5819. else
  5820. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5821. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5822. end;
  5823. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5824. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5825. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5826. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5827. begin
  5828. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5829. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5830. begin
  5831. { Put the register to change in the index register }
  5832. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5833. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5834. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5835. end;
  5836. { Change lea (reg,reg) to lea(,reg,2) }
  5837. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5838. begin
  5839. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5840. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5841. end;
  5842. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5843. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5844. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5845. { Just to prevent miscalculations }
  5846. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5847. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5848. else
  5849. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5850. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5851. if IntermediateRegDiscarded then
  5852. begin
  5853. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5854. RemoveCurrentP(p);
  5855. end
  5856. else
  5857. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5858. result:=true;
  5859. exit;
  5860. end;
  5861. end;
  5862. { changes
  5863. lea offset1(regX), reg1
  5864. lea offset2(reg1), reg2
  5865. to
  5866. lea offset1+offset2(regX), reg2 }
  5867. if (
  5868. { Don't optimise if size is a concern and the intermediate register remains in use }
  5869. IntermediateRegDiscarded or
  5870. not (cs_opt_size in current_settings.optimizerswitches)
  5871. ) and
  5872. (
  5873. (
  5874. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5875. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5876. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5877. ) or (
  5878. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5879. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5880. (
  5881. (
  5882. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5883. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5884. ) or (
  5885. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5886. (
  5887. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5888. (
  5889. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5890. (
  5891. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5892. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5893. )
  5894. )
  5895. )
  5896. )
  5897. )
  5898. )
  5899. ) then
  5900. begin
  5901. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5902. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5903. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5904. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5905. begin
  5906. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5907. begin
  5908. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5909. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5910. { if the register is used as index and base, we have to increase for base as well
  5911. and adapt base }
  5912. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5913. begin
  5914. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5915. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5916. end;
  5917. end
  5918. else
  5919. begin
  5920. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5921. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5922. end;
  5923. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5924. begin
  5925. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5926. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5927. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  5928. { Catch the situation where the base = index
  5929. and treat this as *2. The scalefactor of
  5930. p will be 0 or 1 due to the conditional
  5931. checks above. Fixes i40647 }
  5932. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  5933. else
  5934. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  5935. end;
  5936. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5937. if IntermediateRegDiscarded then
  5938. begin
  5939. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5940. RemoveCurrentP(p);
  5941. end
  5942. else
  5943. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5944. result:=true;
  5945. exit;
  5946. end;
  5947. end;
  5948. end;
  5949. { Change:
  5950. leal/q $x(%reg1),%reg2
  5951. ...
  5952. shll/q $y,%reg2
  5953. To:
  5954. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5955. }
  5956. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5957. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5958. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5959. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5960. (taicpu(hp1).oper[0]^.val <= 3) then
  5961. begin
  5962. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5963. TransferUsedRegs(TmpUsedRegs);
  5964. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5965. if
  5966. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5967. (this works even if scalefactor is zero) }
  5968. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5969. { Ensure offset doesn't go out of bounds }
  5970. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5971. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5972. (
  5973. (
  5974. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5975. (
  5976. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5977. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5978. (
  5979. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5980. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5981. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5982. )
  5983. )
  5984. ) or (
  5985. (
  5986. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5987. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5988. ) and
  5989. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5990. )
  5991. ) then
  5992. begin
  5993. repeat
  5994. with taicpu(p).oper[0]^.ref^ do
  5995. begin
  5996. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5997. if index = base then
  5998. begin
  5999. if Multiple > 4 then
  6000. { Optimisation will no longer work because resultant
  6001. scale factor will exceed 8 }
  6002. Break;
  6003. base := NR_NO;
  6004. scalefactor := 2;
  6005. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  6006. end
  6007. else if (base <> NR_NO) and (base <> NR_INVALID) then
  6008. begin
  6009. { Scale factor only works on the index register }
  6010. index := base;
  6011. base := NR_NO;
  6012. end;
  6013. { For safety }
  6014. if scalefactor <= 1 then
  6015. begin
  6016. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  6017. scalefactor := Multiple;
  6018. end
  6019. else
  6020. begin
  6021. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  6022. scalefactor := scalefactor * Multiple;
  6023. end;
  6024. offset := offset * Multiple;
  6025. end;
  6026. RemoveInstruction(hp1);
  6027. Result := True;
  6028. Exit;
  6029. { This repeat..until loop exists for the benefit of Break }
  6030. until True;
  6031. end;
  6032. end;
  6033. end;
  6034. end;
  6035. end;
  6036. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  6037. var
  6038. hp1 : tai;
  6039. SubInstr: Boolean;
  6040. ThisConst: TCGInt;
  6041. const
  6042. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  6043. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  6044. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  6045. begin
  6046. Result := False;
  6047. if taicpu(p).oper[0]^.typ <> top_const then
  6048. { Should have been confirmed before calling }
  6049. InternalError(2021102601);
  6050. SubInstr := (taicpu(p).opcode = A_SUB);
  6051. if GetLastInstruction(p, hp1) and
  6052. (hp1.typ = ait_instruction) and
  6053. (taicpu(hp1).opsize = taicpu(p).opsize) then
  6054. begin
  6055. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  6056. { Bad size }
  6057. InternalError(2022042001);
  6058. case taicpu(hp1).opcode Of
  6059. A_INC:
  6060. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6061. begin
  6062. if SubInstr then
  6063. ThisConst := taicpu(p).oper[0]^.val - 1
  6064. else
  6065. ThisConst := taicpu(p).oper[0]^.val + 1;
  6066. end
  6067. else
  6068. Exit;
  6069. A_DEC:
  6070. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6071. begin
  6072. if SubInstr then
  6073. ThisConst := taicpu(p).oper[0]^.val + 1
  6074. else
  6075. ThisConst := taicpu(p).oper[0]^.val - 1;
  6076. end
  6077. else
  6078. Exit;
  6079. A_SUB:
  6080. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6081. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6082. begin
  6083. if SubInstr then
  6084. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  6085. else
  6086. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  6087. end
  6088. else
  6089. Exit;
  6090. A_ADD:
  6091. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6092. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6093. begin
  6094. if SubInstr then
  6095. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  6096. else
  6097. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6098. end
  6099. else
  6100. Exit;
  6101. else
  6102. Exit;
  6103. end;
  6104. { Check that the values are in range }
  6105. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  6106. { Overflow; abort }
  6107. Exit;
  6108. if (ThisConst = 0) then
  6109. begin
  6110. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6111. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6112. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  6113. RemoveInstruction(hp1);
  6114. hp1 := tai(p.next);
  6115. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  6116. if not GetLastInstruction(hp1, p) then
  6117. p := hp1;
  6118. end
  6119. else
  6120. begin
  6121. if taicpu(hp1).opercnt=1 then
  6122. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6123. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6124. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6125. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6126. else
  6127. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6128. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6129. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6130. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6131. RemoveInstruction(hp1);
  6132. taicpu(p).loadconst(0, ThisConst);
  6133. end;
  6134. Result := True;
  6135. end;
  6136. end;
  6137. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6138. begin
  6139. Result := False;
  6140. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6141. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6142. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6143. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6144. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6145. (
  6146. (
  6147. (taicpu(hp1).opcode = A_TEST)
  6148. ) or (
  6149. (taicpu(hp1).opcode = A_CMP) and
  6150. { A sanity check more than anything }
  6151. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6152. )
  6153. ) then
  6154. begin
  6155. { change
  6156. mov mem, %reg
  6157. ...
  6158. cmp/test x, %reg / test %reg,%reg
  6159. (reg deallocated)
  6160. to
  6161. cmp/test x, mem / cmp 0, mem
  6162. }
  6163. TransferUsedRegs(TmpUsedRegs);
  6164. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6165. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6166. begin
  6167. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6168. if (taicpu(hp1).opcode = A_TEST) and
  6169. (
  6170. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6171. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6172. ) then
  6173. begin
  6174. taicpu(hp1).opcode := A_CMP;
  6175. taicpu(hp1).loadconst(0, 0);
  6176. end;
  6177. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6178. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6179. RemoveCurrentP(p);
  6180. if (p <> hp1) then
  6181. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6182. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6183. { Make sure the flags are allocated across the CMP instruction }
  6184. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6185. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6186. Result := True;
  6187. Exit;
  6188. end;
  6189. end;
  6190. end;
  6191. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6192. var
  6193. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6194. ThisReg, SecondReg: TRegister;
  6195. JumpLoc: TAsmLabel;
  6196. NewSize: TOpSize;
  6197. begin
  6198. Result := False;
  6199. {
  6200. Convert:
  6201. j<c> .L1
  6202. .L2:
  6203. mov 1,reg
  6204. jmp .L3 (or ret, although it might not be a RET yet)
  6205. .L1:
  6206. mov 0,reg
  6207. jmp .L3 (or ret)
  6208. ( As long as .L3 <> .L1 or .L2)
  6209. To:
  6210. mov 0,reg
  6211. set<not(c)> reg
  6212. jmp .L3 (or ret)
  6213. .L2:
  6214. mov 1,reg
  6215. jmp .L3 (or ret)
  6216. .L1:
  6217. mov 0,reg
  6218. jmp .L3 (or ret)
  6219. }
  6220. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6221. Exit;
  6222. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6223. if GetNextInstruction(hp_label, hp2) and
  6224. MatchInstruction(hp2,A_MOV,[]) and
  6225. (taicpu(hp2).oper[0]^.typ = top_const) and
  6226. (
  6227. (
  6228. (taicpu(hp2).oper[1]^.typ = top_reg)
  6229. {$ifdef i386}
  6230. { Under i386, ESI, EDI, EBP and ESP
  6231. don't have an 8-bit representation }
  6232. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6233. {$endif i386}
  6234. ) or (
  6235. {$ifdef i386}
  6236. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6237. {$endif i386}
  6238. (taicpu(hp2).opsize = S_B)
  6239. )
  6240. ) and
  6241. GetNextInstruction(hp2, hp3) and
  6242. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6243. (
  6244. (taicpu(hp3).opcode=A_RET) or
  6245. (
  6246. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6247. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6248. )
  6249. ) and
  6250. GetNextInstruction(hp3, hp4) and
  6251. (hp4.typ=ait_label) and
  6252. (tai_label(hp4).labsym=JumpLoc) and
  6253. (
  6254. not (cs_opt_size in current_settings.optimizerswitches) or
  6255. { If the initial jump is the label's only reference, then it will
  6256. become a dead label if the other conditions are met and hence
  6257. remove at least 2 instructions, including a jump }
  6258. (JumpLoc.getrefs = 1)
  6259. ) and
  6260. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6261. that will be optimised out }
  6262. GetNextInstruction(hp4, hp5) and
  6263. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6264. (taicpu(hp5).oper[0]^.typ = top_const) and
  6265. (
  6266. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6267. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6268. ) and
  6269. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6270. GetNextInstruction(hp5,hp6) and
  6271. (
  6272. (hp6.typ<>ait_label) or
  6273. SkipLabels(hp6, hp6)
  6274. ) and
  6275. (hp6.typ=ait_instruction) then
  6276. begin
  6277. { First, let's look at the two jumps that are hp3 and hp6 }
  6278. if not
  6279. (
  6280. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6281. (
  6282. (taicpu(hp6).opcode=A_RET) or
  6283. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6284. )
  6285. ) then
  6286. { If condition is False, then the JMP/RET instructions matched conventionally }
  6287. begin
  6288. { See if one of the jumps can be instantly converted into a RET }
  6289. if (taicpu(hp3).opcode=A_JMP) then
  6290. begin
  6291. { Reuse hp5 }
  6292. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6293. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  6294. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  6295. Exit;
  6296. if MatchInstruction(hp5, A_RET, []) then
  6297. begin
  6298. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6299. ConvertJumpToRET(hp3, hp5);
  6300. Result := True;
  6301. end
  6302. else
  6303. Exit;
  6304. end;
  6305. if (taicpu(hp6).opcode=A_JMP) then
  6306. begin
  6307. { Reuse hp5 }
  6308. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6309. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6310. Exit;
  6311. if MatchInstruction(hp5, A_RET, []) then
  6312. begin
  6313. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6314. ConvertJumpToRET(hp6, hp5);
  6315. Result := True;
  6316. end
  6317. else
  6318. Exit;
  6319. end;
  6320. if not
  6321. (
  6322. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6323. (
  6324. (taicpu(hp6).opcode=A_RET) or
  6325. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6326. )
  6327. ) then
  6328. { Still doesn't match }
  6329. Exit;
  6330. end;
  6331. if (taicpu(hp2).oper[0]^.val = 1) then
  6332. begin
  6333. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6334. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6335. end
  6336. else
  6337. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6338. if taicpu(hp2).opsize=S_B then
  6339. begin
  6340. if taicpu(hp2).oper[1]^.typ = top_reg then
  6341. begin
  6342. SecondReg := taicpu(hp2).oper[1]^.reg;
  6343. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6344. end
  6345. else
  6346. begin
  6347. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6348. SecondReg := NR_NO;
  6349. end;
  6350. hp_pos := p;
  6351. hp_allocstart := hp4;
  6352. end
  6353. else
  6354. begin
  6355. { Will be a register because the size can't be S_B otherwise }
  6356. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6357. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6358. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6359. if (cs_opt_size in current_settings.optimizerswitches) then
  6360. begin
  6361. { Favour using MOVZX when optimising for size }
  6362. case taicpu(hp2).opsize of
  6363. S_W:
  6364. NewSize := S_BW;
  6365. S_L:
  6366. NewSize := S_BL;
  6367. {$ifdef x86_64}
  6368. S_Q:
  6369. begin
  6370. NewSize := S_BL;
  6371. { Will implicitly zero-extend to 64-bit }
  6372. setsubreg(SecondReg, R_SUBD);
  6373. end;
  6374. {$endif x86_64}
  6375. else
  6376. InternalError(2022101301);
  6377. end;
  6378. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6379. { Inserting it right before p will guarantee that the flags are also tracked }
  6380. Asml.InsertBefore(hp5, p);
  6381. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6382. hp_pos := hp5;
  6383. hp_allocstart := hp4;
  6384. end
  6385. else
  6386. begin
  6387. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6388. { Inserting it right before p will guarantee that the flags are also tracked }
  6389. Asml.InsertBefore(hp5, p);
  6390. hp_pos := p;
  6391. hp_allocstart := hp5;
  6392. end;
  6393. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6394. end;
  6395. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6396. taicpu(hp4).condition := taicpu(p).condition;
  6397. asml.InsertBefore(hp4, hp_pos);
  6398. if taicpu(hp3).is_jmp then
  6399. begin
  6400. JumpLoc.decrefs;
  6401. MakeUnconditional(taicpu(p));
  6402. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6403. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6404. end
  6405. else
  6406. ConvertJumpToRET(p, hp3);
  6407. if SecondReg <> NR_NO then
  6408. { Ensure the destination register is allocated over this region }
  6409. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6410. if (JumpLoc.getrefs = 0) then
  6411. RemoveDeadCodeAfterJump(hp3);
  6412. Result:=true;
  6413. exit;
  6414. end;
  6415. end;
  6416. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6417. var
  6418. hp1, hp2: tai;
  6419. ActiveReg: TRegister;
  6420. OldOffset: asizeint;
  6421. ThisConst: TCGInt;
  6422. function RegDeallocated: Boolean;
  6423. begin
  6424. TransferUsedRegs(TmpUsedRegs);
  6425. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6426. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6427. end;
  6428. begin
  6429. Result:=false;
  6430. hp1 := nil;
  6431. { replace
  6432. subX const,%reg1
  6433. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6434. dealloc %reg1
  6435. by
  6436. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6437. }
  6438. if MatchOpType(taicpu(p),top_const,top_reg) then
  6439. begin
  6440. ActiveReg := taicpu(p).oper[1]^.reg;
  6441. { Ensures the entire register was updated }
  6442. if (taicpu(p).opsize >= S_L) and
  6443. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6444. MatchInstruction(hp1,A_LEA,[]) and
  6445. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6446. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6447. (
  6448. { Cover the case where the register in the reference is also the destination register }
  6449. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6450. (
  6451. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6452. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6453. RegDeallocated
  6454. )
  6455. ) then
  6456. begin
  6457. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6458. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6459. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6460. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6461. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6462. {$ifdef x86_64}
  6463. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6464. begin
  6465. { Overflow; abort }
  6466. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6467. end
  6468. else
  6469. {$endif x86_64}
  6470. begin
  6471. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6472. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6473. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6474. RemoveCurrentP(p, hp1)
  6475. else
  6476. RemoveCurrentP(p);
  6477. result:=true;
  6478. Exit;
  6479. end;
  6480. end;
  6481. if (
  6482. { Save calling GetNextInstructionUsingReg again }
  6483. Assigned(hp1) or
  6484. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6485. ) and
  6486. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6487. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6488. begin
  6489. if taicpu(hp1).oper[0]^.typ = top_const then
  6490. begin
  6491. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6492. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6493. Result := True;
  6494. { Handle any overflows }
  6495. case taicpu(p).opsize of
  6496. S_B:
  6497. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6498. S_W:
  6499. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6500. S_L:
  6501. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6502. {$ifdef x86_64}
  6503. S_Q:
  6504. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6505. { Overflow; abort }
  6506. Result := False
  6507. else
  6508. taicpu(p).oper[0]^.val := ThisConst;
  6509. {$endif x86_64}
  6510. else
  6511. InternalError(2021102611);
  6512. end;
  6513. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6514. if Result then
  6515. begin
  6516. if (taicpu(p).oper[0]^.val < 0) and
  6517. (
  6518. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6519. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6520. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6521. ) then
  6522. begin
  6523. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6524. taicpu(p).opcode := A_SUB;
  6525. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6526. end
  6527. else
  6528. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6529. RemoveInstruction(hp1);
  6530. end;
  6531. end
  6532. else
  6533. begin
  6534. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6535. TransferUsedRegs(TmpUsedRegs);
  6536. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6537. hp2 := p;
  6538. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6539. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6540. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6541. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6542. begin
  6543. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6544. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6545. Asml.Remove(p);
  6546. Asml.InsertAfter(p, hp1);
  6547. p := hp1;
  6548. Result := True;
  6549. Exit;
  6550. end;
  6551. end;
  6552. end;
  6553. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6554. { * change "sub/add const1, reg" or "dec reg" followed by
  6555. "sub const2, reg" to one "sub ..., reg" }
  6556. {$ifdef i386}
  6557. if (taicpu(p).oper[0]^.val = 2) and
  6558. (ActiveReg = NR_ESP) and
  6559. { Don't do the sub/push optimization if the sub }
  6560. { comes from setting up the stack frame (JM) }
  6561. (not(GetLastInstruction(p,hp1)) or
  6562. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6563. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6564. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6565. begin
  6566. hp1 := tai(p.next);
  6567. while Assigned(hp1) and
  6568. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6569. not RegReadByInstruction(NR_ESP,hp1) and
  6570. not RegModifiedByInstruction(NR_ESP,hp1) do
  6571. hp1 := tai(hp1.next);
  6572. if Assigned(hp1) and
  6573. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6574. begin
  6575. taicpu(hp1).changeopsize(S_L);
  6576. if taicpu(hp1).oper[0]^.typ=top_reg then
  6577. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6578. hp1 := tai(p.next);
  6579. RemoveCurrentp(p, hp1);
  6580. Result:=true;
  6581. exit;
  6582. end;
  6583. end;
  6584. {$endif i386}
  6585. if DoArithCombineOpt(p) then
  6586. Result:=true;
  6587. end;
  6588. end;
  6589. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6590. var
  6591. TmpBool1,TmpBool2 : Boolean;
  6592. tmpref : treference;
  6593. hp1,hp2: tai;
  6594. mask, shiftval: tcgint;
  6595. begin
  6596. Result:=false;
  6597. { All these optimisations work on "shl/sal const,%reg" }
  6598. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6599. Exit;
  6600. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6601. (taicpu(p).oper[0]^.val <= 3) then
  6602. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6603. begin
  6604. { should we check the next instruction? }
  6605. TmpBool1 := True;
  6606. { have we found an add/sub which could be
  6607. integrated in the lea? }
  6608. TmpBool2 := False;
  6609. reference_reset(tmpref,2,[]);
  6610. TmpRef.index := taicpu(p).oper[1]^.reg;
  6611. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6612. while TmpBool1 and
  6613. GetNextInstruction(p, hp1) and
  6614. (tai(hp1).typ = ait_instruction) and
  6615. ((((taicpu(hp1).opcode = A_ADD) or
  6616. (taicpu(hp1).opcode = A_SUB)) and
  6617. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6618. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6619. (((taicpu(hp1).opcode = A_INC) or
  6620. (taicpu(hp1).opcode = A_DEC)) and
  6621. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6622. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6623. ((taicpu(hp1).opcode = A_LEA) and
  6624. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6625. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6626. (not GetNextInstruction(hp1,hp2) or
  6627. not instrReadsFlags(hp2)) Do
  6628. begin
  6629. TmpBool1 := False;
  6630. if taicpu(hp1).opcode=A_LEA then
  6631. begin
  6632. if (TmpRef.base = NR_NO) and
  6633. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6634. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6635. { Segment register isn't a concern here }
  6636. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6637. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6638. begin
  6639. TmpBool1 := True;
  6640. TmpBool2 := True;
  6641. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6642. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6643. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6644. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6645. RemoveInstruction(hp1);
  6646. end
  6647. end
  6648. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6649. begin
  6650. TmpBool1 := True;
  6651. TmpBool2 := True;
  6652. case taicpu(hp1).opcode of
  6653. A_ADD:
  6654. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6655. A_SUB:
  6656. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6657. else
  6658. internalerror(2019050536);
  6659. end;
  6660. RemoveInstruction(hp1);
  6661. end
  6662. else
  6663. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6664. (((taicpu(hp1).opcode = A_ADD) and
  6665. (TmpRef.base = NR_NO)) or
  6666. (taicpu(hp1).opcode = A_INC) or
  6667. (taicpu(hp1).opcode = A_DEC)) then
  6668. begin
  6669. TmpBool1 := True;
  6670. TmpBool2 := True;
  6671. case taicpu(hp1).opcode of
  6672. A_ADD:
  6673. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6674. A_INC:
  6675. inc(TmpRef.offset);
  6676. A_DEC:
  6677. dec(TmpRef.offset);
  6678. else
  6679. internalerror(2019050535);
  6680. end;
  6681. RemoveInstruction(hp1);
  6682. end;
  6683. end;
  6684. if TmpBool2
  6685. {$ifndef x86_64}
  6686. or
  6687. ((current_settings.optimizecputype < cpu_Pentium2) and
  6688. (taicpu(p).oper[0]^.val <= 3) and
  6689. not(cs_opt_size in current_settings.optimizerswitches))
  6690. {$endif x86_64}
  6691. then
  6692. begin
  6693. if not(TmpBool2) and
  6694. (taicpu(p).oper[0]^.val=1) then
  6695. begin
  6696. taicpu(p).opcode := A_ADD;
  6697. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6698. end
  6699. else
  6700. begin
  6701. taicpu(p).opcode := A_LEA;
  6702. taicpu(p).loadref(0, TmpRef);
  6703. end;
  6704. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6705. Result := True;
  6706. end;
  6707. end
  6708. {$ifndef x86_64}
  6709. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6710. begin
  6711. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6712. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6713. (unlike shl, which is only Tairable in the U pipe) }
  6714. if taicpu(p).oper[0]^.val=1 then
  6715. begin
  6716. taicpu(p).opcode := A_ADD;
  6717. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6718. Result := True;
  6719. end
  6720. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6721. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6722. else if (taicpu(p).opsize = S_L) and
  6723. (taicpu(p).oper[0]^.val<= 3) then
  6724. begin
  6725. reference_reset(tmpref,2,[]);
  6726. TmpRef.index := taicpu(p).oper[1]^.reg;
  6727. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6728. taicpu(p).opcode := A_LEA;
  6729. taicpu(p).loadref(0, TmpRef);
  6730. Result := True;
  6731. end;
  6732. end
  6733. {$endif x86_64}
  6734. else if
  6735. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6736. (
  6737. (
  6738. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6739. SetAndTest(hp1, hp2)
  6740. {$ifdef x86_64}
  6741. ) or
  6742. (
  6743. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6744. GetNextInstruction(hp1, hp2) and
  6745. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6746. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6747. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6748. {$endif x86_64}
  6749. )
  6750. ) and
  6751. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6752. begin
  6753. { Change:
  6754. shl x, %reg1
  6755. mov -(1<<x), %reg2
  6756. and %reg2, %reg1
  6757. Or:
  6758. shl x, %reg1
  6759. and -(1<<x), %reg1
  6760. To just:
  6761. shl x, %reg1
  6762. Since the and operation only zeroes bits that are already zero from the shl operation
  6763. }
  6764. case taicpu(p).oper[0]^.val of
  6765. 8:
  6766. mask:=$FFFFFFFFFFFFFF00;
  6767. 16:
  6768. mask:=$FFFFFFFFFFFF0000;
  6769. 32:
  6770. mask:=$FFFFFFFF00000000;
  6771. 63:
  6772. { Constant pre-calculated to prevent overflow errors with Int64 }
  6773. mask:=$8000000000000000;
  6774. else
  6775. begin
  6776. if taicpu(p).oper[0]^.val >= 64 then
  6777. { Shouldn't happen realistically, since the register
  6778. is guaranteed to be set to zero at this point }
  6779. mask := 0
  6780. else
  6781. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6782. end;
  6783. end;
  6784. if taicpu(hp1).oper[0]^.val = mask then
  6785. begin
  6786. { Everything checks out, perform the optimisation, as long as
  6787. the FLAGS register isn't being used}
  6788. TransferUsedRegs(TmpUsedRegs);
  6789. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6790. {$ifdef x86_64}
  6791. if (hp1 <> hp2) then
  6792. begin
  6793. { "shl/mov/and" version }
  6794. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6795. { Don't do the optimisation if the FLAGS register is in use }
  6796. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6797. begin
  6798. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6799. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6800. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6801. begin
  6802. RemoveInstruction(hp1);
  6803. Result := True;
  6804. end;
  6805. { Only set Result to True if the 'mov' instruction was removed }
  6806. RemoveInstruction(hp2);
  6807. end;
  6808. end
  6809. else
  6810. {$endif x86_64}
  6811. begin
  6812. { "shl/and" version }
  6813. { Don't do the optimisation if the FLAGS register is in use }
  6814. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6815. begin
  6816. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6817. RemoveInstruction(hp1);
  6818. Result := True;
  6819. end;
  6820. end;
  6821. Exit;
  6822. end
  6823. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6824. begin
  6825. { Even if the mask doesn't allow for its removal, we might be
  6826. able to optimise the mask for the "shl/and" version, which
  6827. may permit other peephole optimisations }
  6828. {$ifdef DEBUG_AOPTCPU}
  6829. mask := taicpu(hp1).oper[0]^.val and mask;
  6830. if taicpu(hp1).oper[0]^.val <> mask then
  6831. begin
  6832. DebugMsg(
  6833. SPeepholeOptimization +
  6834. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6835. ' to $' + debug_tostr(mask) +
  6836. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6837. taicpu(hp1).oper[0]^.val := mask;
  6838. end;
  6839. {$else DEBUG_AOPTCPU}
  6840. { If debugging is off, just set the operand even if it's the same }
  6841. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6842. {$endif DEBUG_AOPTCPU}
  6843. end;
  6844. end;
  6845. {
  6846. change
  6847. shl/sal const,reg
  6848. <op> ...(...,reg,1),...
  6849. into
  6850. <op> ...(...,reg,1 shl const),...
  6851. if const in 1..3
  6852. }
  6853. if MatchOpType(taicpu(p), top_const, top_reg) and
  6854. (taicpu(p).oper[0]^.val in [1..3]) and
  6855. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6856. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6857. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6858. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6859. MatchOpType(taicpu(hp1),top_ref))
  6860. ) and
  6861. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6862. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6863. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6864. begin
  6865. TransferUsedRegs(TmpUsedRegs);
  6866. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6867. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6868. begin
  6869. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6870. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6871. RemoveCurrentP(p);
  6872. Result:=true;
  6873. exit;
  6874. end;
  6875. end;
  6876. if MatchOpType(taicpu(p), top_const, top_reg) and
  6877. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6878. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6879. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6880. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6881. begin
  6882. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6883. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6884. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6885. {$ifdef x86_64}
  6886. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6887. {$endif x86_64}
  6888. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6889. begin
  6890. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6891. taicpu(hp1).opcode:=A_MOV;
  6892. taicpu(hp1).oper[0]^.val:=0;
  6893. end
  6894. else
  6895. begin
  6896. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6897. taicpu(hp1).oper[0]^.val:=shiftval;
  6898. end;
  6899. RemoveCurrentP(p);
  6900. Result:=true;
  6901. exit;
  6902. end;
  6903. end;
  6904. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6905. begin
  6906. case shr_size of
  6907. S_B:
  6908. { No valid combinations }
  6909. Result := False;
  6910. S_W:
  6911. Result := (Shift >= 8) and (movz_size = S_BW);
  6912. S_L:
  6913. Result :=
  6914. (Shift >= 24) { Any opsize is valid for this shift } or
  6915. ((Shift >= 16) and (movz_size = S_WL));
  6916. {$ifdef x86_64}
  6917. S_Q:
  6918. Result :=
  6919. (Shift >= 56) { Any opsize is valid for this shift } or
  6920. ((Shift >= 48) and (movz_size = S_WL));
  6921. {$endif x86_64}
  6922. else
  6923. InternalError(2022081510);
  6924. end;
  6925. end;
  6926. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6927. var
  6928. hp1, hp2: tai;
  6929. Shift: TCGInt;
  6930. LimitSize: Topsize;
  6931. DoNotMerge: Boolean;
  6932. begin
  6933. Result := False;
  6934. { All these optimisations work on "shr const,%reg" }
  6935. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6936. Exit;
  6937. DoNotMerge := False;
  6938. Shift := taicpu(p).oper[0]^.val;
  6939. LimitSize := taicpu(p).opsize;
  6940. hp1 := p;
  6941. repeat
  6942. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6943. Exit;
  6944. case taicpu(hp1).opcode of
  6945. A_TEST, A_CMP, A_Jcc:
  6946. { Skip over conditional jumps and relevant comparisons }
  6947. Continue;
  6948. A_MOVZX:
  6949. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6950. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6951. begin
  6952. { Since the original register is being read as is, subsequent
  6953. SHRs must not be merged at this point }
  6954. DoNotMerge := True;
  6955. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6956. begin
  6957. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6958. begin
  6959. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6960. taicpu(hp1).opcode := A_MOV;
  6961. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6962. case taicpu(hp1).opsize of
  6963. S_BW:
  6964. taicpu(hp1).opsize := S_W;
  6965. S_BL, S_WL:
  6966. taicpu(hp1).opsize := S_L;
  6967. else
  6968. InternalError(2022081503);
  6969. end;
  6970. { p itself hasn't changed, so no need to set Result to True }
  6971. Include(OptsToCheck, aoc_ForceNewIteration);
  6972. { See if there's anything afterwards that can be
  6973. optimised, since the input register hasn't changed }
  6974. Continue;
  6975. end;
  6976. { NOTE: If the MOVZX instruction reads and writes the same
  6977. register, defer this to the post-peephole optimisation stage }
  6978. Exit;
  6979. end;
  6980. end;
  6981. A_SHL, A_SAL, A_SHR:
  6982. if (taicpu(hp1).opsize <= LimitSize) and
  6983. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6984. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6985. begin
  6986. { Make sure the sizes don't exceed the register size limit
  6987. (measured by the shift value falling below the limit) }
  6988. if taicpu(hp1).opsize < LimitSize then
  6989. LimitSize := taicpu(hp1).opsize;
  6990. if taicpu(hp1).opcode = A_SHR then
  6991. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6992. else
  6993. begin
  6994. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6995. DoNotMerge := True;
  6996. end;
  6997. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6998. Exit;
  6999. { Since we've established that the combined shift is within
  7000. limits, we can actually combine the adjacent SHR
  7001. instructions even if they're different sizes }
  7002. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  7003. begin
  7004. hp2 := tai(hp1.Previous);
  7005. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  7006. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  7007. RemoveInstruction(hp1);
  7008. hp1 := hp2;
  7009. { Though p has changed, only the constant has, and its
  7010. effects can still be detected on the next iteration of
  7011. the repeat..until loop }
  7012. Include(OptsToCheck, aoc_ForceNewIteration);
  7013. end;
  7014. { Move onto the next instruction }
  7015. Continue;
  7016. end;
  7017. else
  7018. ;
  7019. end;
  7020. Break;
  7021. until False;
  7022. end;
  7023. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  7024. var
  7025. CurrentRef: TReference;
  7026. FullReg: TRegister;
  7027. hp1, hp2: tai;
  7028. begin
  7029. Result := False;
  7030. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  7031. Exit;
  7032. { We assume you've checked if the operand is actually a reference by
  7033. this point. If it isn't, you'll most likely get an access violation }
  7034. CurrentRef := first_mov.oper[1]^.ref^;
  7035. { Memory must be aligned }
  7036. if (CurrentRef.offset mod 4) <> 0 then
  7037. Exit;
  7038. Inc(CurrentRef.offset);
  7039. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7040. if MatchOperand(second_mov.oper[0]^, 0) and
  7041. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  7042. GetNextInstruction(second_mov, hp1) and
  7043. (hp1.typ = ait_instruction) and
  7044. (taicpu(hp1).opcode = A_MOV) and
  7045. MatchOpType(taicpu(hp1), top_const, top_ref) and
  7046. (taicpu(hp1).oper[0]^.val = 0) then
  7047. begin
  7048. Inc(CurrentRef.offset);
  7049. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  7050. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  7051. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  7052. begin
  7053. case taicpu(hp1).opsize of
  7054. S_B:
  7055. if GetNextInstruction(hp1, hp2) and
  7056. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  7057. MatchOpType(taicpu(hp2), top_const, top_ref) and
  7058. (taicpu(hp2).oper[0]^.val = 0) then
  7059. begin
  7060. Inc(CurrentRef.offset);
  7061. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7062. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  7063. (taicpu(hp2).opsize = S_B) then
  7064. begin
  7065. RemoveInstruction(hp1);
  7066. RemoveInstruction(hp2);
  7067. first_mov.opsize := S_L;
  7068. if first_mov.oper[0]^.typ = top_reg then
  7069. begin
  7070. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  7071. { Reuse second_mov as a MOVZX instruction }
  7072. second_mov.opcode := A_MOVZX;
  7073. second_mov.opsize := S_BL;
  7074. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7075. second_mov.loadreg(1, FullReg);
  7076. first_mov.oper[0]^.reg := FullReg;
  7077. asml.Remove(second_mov);
  7078. asml.InsertBefore(second_mov, first_mov);
  7079. end
  7080. else
  7081. { It's a value }
  7082. begin
  7083. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  7084. RemoveInstruction(second_mov);
  7085. end;
  7086. Result := True;
  7087. Exit;
  7088. end;
  7089. end;
  7090. S_W:
  7091. begin
  7092. RemoveInstruction(hp1);
  7093. first_mov.opsize := S_L;
  7094. if first_mov.oper[0]^.typ = top_reg then
  7095. begin
  7096. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  7097. { Reuse second_mov as a MOVZX instruction }
  7098. second_mov.opcode := A_MOVZX;
  7099. second_mov.opsize := S_BL;
  7100. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7101. second_mov.loadreg(1, FullReg);
  7102. first_mov.oper[0]^.reg := FullReg;
  7103. asml.Remove(second_mov);
  7104. asml.InsertBefore(second_mov, first_mov);
  7105. end
  7106. else
  7107. { It's a value }
  7108. begin
  7109. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  7110. RemoveInstruction(second_mov);
  7111. end;
  7112. Result := True;
  7113. Exit;
  7114. end;
  7115. else
  7116. ;
  7117. end;
  7118. end;
  7119. end;
  7120. end;
  7121. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7122. { returns true if a "continue" should be done after this optimization }
  7123. var
  7124. hp1, hp2, hp3: tai;
  7125. begin
  7126. Result := false;
  7127. hp3 := nil;
  7128. if MatchOpType(taicpu(p),top_ref) and
  7129. GetNextInstruction(p, hp1) and
  7130. (hp1.typ = ait_instruction) and
  7131. (((taicpu(hp1).opcode = A_FLD) and
  7132. (taicpu(p).opcode = A_FSTP)) or
  7133. ((taicpu(p).opcode = A_FISTP) and
  7134. (taicpu(hp1).opcode = A_FILD))) and
  7135. MatchOpType(taicpu(hp1),top_ref) and
  7136. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7137. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7138. begin
  7139. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7140. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7141. GetNextInstruction(hp1, hp2) and
  7142. (((hp2.typ = ait_instruction) and
  7143. IsExitCode(hp2) and
  7144. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7145. not(assigned(current_procinfo.procdef.funcretsym) and
  7146. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7147. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7148. { fstp <temp>
  7149. fld <temp>
  7150. <dealloc> <temp>
  7151. }
  7152. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7153. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7154. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7155. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7156. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7157. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7158. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7159. )
  7160. )
  7161. ) then
  7162. begin
  7163. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7164. RemoveInstruction(hp1);
  7165. RemoveCurrentP(p, hp2);
  7166. { first case: exit code }
  7167. if hp2.typ = ait_instruction then
  7168. RemoveLastDeallocForFuncRes(p);
  7169. Result := true;
  7170. end
  7171. else
  7172. { we can do this only in fast math mode as fstp is rounding ...
  7173. ... still disabled as it breaks the compiler and/or rtl }
  7174. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7175. { ... or if another fstp equal to the first one follows }
  7176. GetNextInstruction(hp1,hp2) and
  7177. (hp2.typ = ait_instruction) and
  7178. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7179. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7180. begin
  7181. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7182. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7183. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7184. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7185. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7186. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7187. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7188. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7189. ) then
  7190. begin
  7191. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7192. RemoveCurrentP(p,hp2);
  7193. RemoveInstruction(hp1);
  7194. Result := true;
  7195. end
  7196. else if { fst can't store an extended/comp value }
  7197. (taicpu(p).opsize <> S_FX) and
  7198. (taicpu(p).opsize <> S_IQ) then
  7199. begin
  7200. if (taicpu(p).opcode = A_FSTP) then
  7201. taicpu(p).opcode := A_FST
  7202. else
  7203. taicpu(p).opcode := A_FIST;
  7204. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7205. RemoveInstruction(hp1);
  7206. Result := true;
  7207. end;
  7208. end;
  7209. end;
  7210. end;
  7211. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7212. var
  7213. hp1, hp2, hp3: tai;
  7214. begin
  7215. result:=false;
  7216. if MatchOpType(taicpu(p),top_reg) and
  7217. GetNextInstruction(p, hp1) and
  7218. (hp1.typ = Ait_Instruction) and
  7219. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7220. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7221. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7222. { change to
  7223. fld reg fxxx reg,st
  7224. fxxxp st, st1 (hp1)
  7225. Remark: non commutative operations must be reversed!
  7226. }
  7227. begin
  7228. case taicpu(hp1).opcode Of
  7229. A_FMULP,A_FADDP,
  7230. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7231. begin
  7232. case taicpu(hp1).opcode Of
  7233. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7234. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7235. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7236. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7237. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7238. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7239. else
  7240. internalerror(2019050534);
  7241. end;
  7242. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7243. taicpu(hp1).oper[1]^.reg := NR_ST;
  7244. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7245. RemoveCurrentP(p, hp1);
  7246. Result:=true;
  7247. exit;
  7248. end;
  7249. else
  7250. ;
  7251. end;
  7252. end
  7253. else
  7254. if MatchOpType(taicpu(p),top_ref) and
  7255. GetNextInstruction(p, hp2) and
  7256. (hp2.typ = Ait_Instruction) and
  7257. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7258. (taicpu(p).opsize in [S_FS, S_FL]) and
  7259. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7260. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7261. if GetLastInstruction(p, hp1) and
  7262. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7263. MatchOpType(taicpu(hp1),top_ref) and
  7264. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7265. if ((taicpu(hp2).opcode = A_FMULP) or
  7266. (taicpu(hp2).opcode = A_FADDP)) then
  7267. { change to
  7268. fld/fst mem1 (hp1) fld/fst mem1
  7269. fld mem1 (p) fadd/
  7270. faddp/ fmul st, st
  7271. fmulp st, st1 (hp2) }
  7272. begin
  7273. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7274. RemoveCurrentP(p, hp1);
  7275. if (taicpu(hp2).opcode = A_FADDP) then
  7276. taicpu(hp2).opcode := A_FADD
  7277. else
  7278. taicpu(hp2).opcode := A_FMUL;
  7279. taicpu(hp2).oper[1]^.reg := NR_ST;
  7280. end
  7281. else
  7282. { change to
  7283. fld/fst mem1 (hp1) fld/fst mem1
  7284. fld mem1 (p) fld st
  7285. }
  7286. begin
  7287. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7288. taicpu(p).changeopsize(S_FL);
  7289. taicpu(p).loadreg(0,NR_ST);
  7290. end
  7291. else
  7292. begin
  7293. case taicpu(hp2).opcode Of
  7294. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7295. { change to
  7296. fld/fst mem1 (hp1) fld/fst mem1
  7297. fld mem2 (p) fxxx mem2
  7298. fxxxp st, st1 (hp2) }
  7299. begin
  7300. case taicpu(hp2).opcode Of
  7301. A_FADDP: taicpu(p).opcode := A_FADD;
  7302. A_FMULP: taicpu(p).opcode := A_FMUL;
  7303. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7304. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7305. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7306. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7307. else
  7308. internalerror(2019050533);
  7309. end;
  7310. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7311. RemoveInstruction(hp2);
  7312. end
  7313. else
  7314. ;
  7315. end
  7316. end
  7317. end;
  7318. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7319. begin
  7320. Result := condition_in(cond1, cond2) or
  7321. { Not strictly subsets due to the actual flags checked, but because we're
  7322. comparing integers, E is a subset of AE and GE and their aliases }
  7323. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7324. end;
  7325. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7326. var
  7327. v: TCGInt;
  7328. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7329. FirstMatch, TempBool: Boolean;
  7330. NewReg: TRegister;
  7331. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7332. begin
  7333. Result:=false;
  7334. { All these optimisations need a next instruction }
  7335. if not GetNextInstruction(p, hp1) then
  7336. Exit;
  7337. true_hp1 := hp1;
  7338. { Search for:
  7339. cmp ###,###
  7340. j(c1) @lbl1
  7341. ...
  7342. @lbl:
  7343. cmp ###,### (same comparison as above)
  7344. j(c2) @lbl2
  7345. If c1 is a subset of c2, change to:
  7346. cmp ###,###
  7347. j(c1) @lbl2
  7348. (@lbl1 may become a dead label as a result)
  7349. }
  7350. { Also handle cases where there are multiple jumps in a row }
  7351. p_jump := hp1;
  7352. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7353. begin
  7354. Prefetch(p_jump.Next);
  7355. if IsJumpToLabel(taicpu(p_jump)) then
  7356. begin
  7357. { Do jump optimisations first in case the condition becomes
  7358. unnecessary }
  7359. TempBool := True;
  7360. if DoJumpOptimizations(p_jump, TempBool) or
  7361. not TempBool then
  7362. begin
  7363. if Assigned(p_jump) then
  7364. begin
  7365. { CollapseZeroDistJump will be set to the label or an align
  7366. before it after the jump if it optimises, whether or not
  7367. the label is live or dead }
  7368. if (p_jump.typ = ait_align) or
  7369. (
  7370. (p_jump.typ = ait_label) and
  7371. not (tai_label(p_jump).labsym.is_used)
  7372. ) then
  7373. GetNextInstruction(p_jump, p_jump);
  7374. end;
  7375. TransferUsedRegs(TmpUsedRegs);
  7376. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7377. if not Assigned(p_jump) or
  7378. (
  7379. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7380. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7381. ) then
  7382. begin
  7383. { No more conditional jumps; conditional statement is no longer required }
  7384. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7385. RemoveCurrentP(p);
  7386. Result := True;
  7387. Exit;
  7388. end;
  7389. hp1 := p_jump;
  7390. Include(OptsToCheck, aoc_ForceNewIteration);
  7391. Continue;
  7392. end;
  7393. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7394. if GetNextInstruction(p_jump, hp2) and
  7395. (
  7396. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7397. not TempBool
  7398. ) then
  7399. begin
  7400. hp1 := p_jump;
  7401. Include(OptsToCheck, aoc_ForceNewIteration);
  7402. Continue;
  7403. end;
  7404. p_label := nil;
  7405. if Assigned(JumpLabel) then
  7406. p_label := getlabelwithsym(JumpLabel);
  7407. if Assigned(p_label) and
  7408. GetNextInstruction(p_label, p_dist) and
  7409. MatchInstruction(p_dist, A_CMP, []) and
  7410. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7411. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7412. GetNextInstruction(p_dist, hp1_dist) and
  7413. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7414. begin
  7415. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7416. if JumpLabel = JumpLabel_dist then
  7417. { This is an infinite loop }
  7418. Exit;
  7419. { Best optimisation when the first condition is a subset (or equal) of the second }
  7420. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7421. begin
  7422. { Any registers used here will already be allocated }
  7423. if Assigned(JumpLabel) then
  7424. JumpLabel.DecRefs;
  7425. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7426. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7427. Include(OptsToCheck, aoc_ForceNewIteration);
  7428. { Don't exit yet. Since p and p_jump haven't actually been
  7429. removed, we can check for more on this iteration }
  7430. end
  7431. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7432. GetNextInstruction(hp1_dist, hp1_label) and
  7433. (hp1_label.typ = ait_label) then
  7434. begin
  7435. JumpLabel_far := tai_label(hp1_label).labsym;
  7436. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7437. { This is an infinite loop }
  7438. Exit;
  7439. if Assigned(JumpLabel_far) then
  7440. begin
  7441. { In this situation, if the first jump branches, the second one will never,
  7442. branch so change the destination label to after the second jump }
  7443. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7444. if Assigned(JumpLabel) then
  7445. JumpLabel.DecRefs;
  7446. JumpLabel_far.IncRefs;
  7447. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7448. Result := True;
  7449. { Don't exit yet. Since p and p_jump haven't actually been
  7450. removed, we can check for more on this iteration }
  7451. Continue;
  7452. end;
  7453. end;
  7454. end;
  7455. end;
  7456. { Search for:
  7457. cmp ###,###
  7458. j(c1) @lbl1
  7459. cmp ###,### (same as first)
  7460. Remove second cmp
  7461. }
  7462. if GetNextInstruction(p_jump, hp2) and
  7463. (
  7464. (
  7465. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7466. (
  7467. (
  7468. MatchOpType(taicpu(p), top_const, top_reg) and
  7469. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7470. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7471. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7472. ) or (
  7473. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7474. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7475. )
  7476. )
  7477. ) or (
  7478. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7479. MatchOperand(taicpu(p).oper[0]^, 0) and
  7480. (taicpu(p).oper[1]^.typ = top_reg) and
  7481. MatchInstruction(hp2, A_TEST, []) and
  7482. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7483. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7484. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7485. )
  7486. ) then
  7487. begin
  7488. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7489. TransferUsedRegs(TmpUsedRegs);
  7490. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7491. RemoveInstruction(hp2);
  7492. Result := True;
  7493. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7494. end
  7495. else
  7496. begin
  7497. { hp2 is the next instruction, so save time and just set p_jump
  7498. to it instead of calling GetNextInstruction below }
  7499. p_jump := hp2;
  7500. Continue;
  7501. end;
  7502. GetNextInstruction(p_jump, p_jump);
  7503. end;
  7504. if (
  7505. { Don't call GetNextInstruction again if we already have it }
  7506. (true_hp1 = p_jump) or
  7507. GetNextInstruction(p, hp1)
  7508. ) and
  7509. MatchInstruction(hp1, A_Jcc, []) and
  7510. IsJumpToLabel(taicpu(hp1)) and
  7511. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7512. GetNextInstruction(hp1, hp2) then
  7513. begin
  7514. {
  7515. cmp x, y (or "cmp y, x")
  7516. je @lbl
  7517. mov x, y
  7518. @lbl:
  7519. (x and y can be constants, registers or references)
  7520. Change to:
  7521. mov x, y (x and y will always be equal in the end)
  7522. @lbl: (may beceome a dead label)
  7523. Also:
  7524. cmp x, y (or "cmp y, x")
  7525. jne @lbl
  7526. mov x, y
  7527. @lbl:
  7528. (x and y can be constants, registers or references)
  7529. Change to:
  7530. Absolutely nothing! (Except @lbl if it's still live)
  7531. }
  7532. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7533. (
  7534. (
  7535. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7536. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7537. ) or (
  7538. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7539. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7540. )
  7541. ) and
  7542. GetNextInstruction(hp2, hp1_label) and
  7543. (hp1_label.typ = ait_label) and
  7544. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7545. begin
  7546. tai_label(hp1_label).labsym.DecRefs;
  7547. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7548. begin
  7549. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7550. RemoveInstruction(hp2);
  7551. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7552. end
  7553. else
  7554. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7555. RemoveInstruction(hp1);
  7556. RemoveCurrentp(p, hp2);
  7557. Result := True;
  7558. Exit;
  7559. end;
  7560. {
  7561. Try to optimise the following:
  7562. cmp $x,### ($x and $y can be registers or constants)
  7563. je @lbl1 (only reference)
  7564. cmp $y,### (### are identical)
  7565. @Lbl:
  7566. sete %reg1
  7567. Change to:
  7568. cmp $x,###
  7569. sete %reg2 (allocate new %reg2)
  7570. cmp $y,###
  7571. sete %reg1
  7572. orb %reg2,%reg1
  7573. (dealloc %reg2)
  7574. This adds an instruction (so don't perform under -Os), but it removes
  7575. a conditional branch.
  7576. }
  7577. if not (cs_opt_size in current_settings.optimizerswitches) and
  7578. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7579. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7580. { The first operand of CMP instructions can only be a register or
  7581. immediate anyway, so no need to check }
  7582. GetNextInstruction(hp2, p_label) and
  7583. (p_label.typ = ait_label) and
  7584. (tai_label(p_label).labsym.getrefs = 1) and
  7585. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7586. GetNextInstruction(p_label, p_dist) and
  7587. MatchInstruction(p_dist, A_SETcc, []) and
  7588. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7589. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7590. begin
  7591. TransferUsedRegs(TmpUsedRegs);
  7592. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7593. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7594. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7595. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7596. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7597. { Get the instruction after the SETcc instruction so we can
  7598. allocate a new register over the entire range }
  7599. GetNextInstruction(p_dist, hp1_dist) then
  7600. begin
  7601. { Register can appear in p if it's not used afterwards, so only
  7602. allocate between hp1 and hp1_dist }
  7603. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7604. if NewReg <> NR_NO then
  7605. begin
  7606. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7607. { Change the jump instruction into a SETcc instruction }
  7608. taicpu(hp1).opcode := A_SETcc;
  7609. taicpu(hp1).opsize := S_B;
  7610. taicpu(hp1).loadreg(0, NewReg);
  7611. { This is now a dead label }
  7612. tai_label(p_label).labsym.decrefs;
  7613. { Prefer adding before the next instruction so the FLAGS
  7614. register is deallicated first }
  7615. AsmL.InsertBefore(
  7616. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7617. hp1_dist
  7618. );
  7619. Result := True;
  7620. { Don't exit yet, as p wasn't changed and hp1, while
  7621. modified, is still intact and might be optimised by the
  7622. SETcc optimisation below }
  7623. end;
  7624. end;
  7625. end;
  7626. end;
  7627. if (taicpu(p).oper[0]^.typ = top_const) and
  7628. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7629. begin
  7630. if (taicpu(p).oper[0]^.val = 0) and
  7631. (taicpu(p).oper[1]^.typ = top_reg) then
  7632. begin
  7633. hp2 := p;
  7634. FirstMatch := True;
  7635. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7636. anything meaningful once it's converted to "test %reg,%reg";
  7637. additionally, some jumps will always (or never) branch, so
  7638. evaluate every jump immediately following the
  7639. comparison, optimising the conditions if possible.
  7640. Similarly with SETcc... those that are always set to 0 or 1
  7641. are changed to MOV instructions }
  7642. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7643. (
  7644. GetNextInstruction(hp2, hp1) and
  7645. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7646. ) do
  7647. begin
  7648. Prefetch(hp1.Next);
  7649. FirstMatch := False;
  7650. case taicpu(hp1).condition of
  7651. C_B, C_C, C_NAE, C_O:
  7652. { For B/NAE:
  7653. Will never branch since an unsigned integer can never be below zero
  7654. For C/O:
  7655. Result cannot overflow because 0 is being subtracted
  7656. }
  7657. begin
  7658. if taicpu(hp1).opcode = A_Jcc then
  7659. begin
  7660. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7661. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7662. RemoveInstruction(hp1);
  7663. { Since hp1 was deleted, hp2 must not be updated }
  7664. Continue;
  7665. end
  7666. else
  7667. begin
  7668. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7669. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7670. taicpu(hp1).opcode := A_MOV;
  7671. taicpu(hp1).ops := 2;
  7672. taicpu(hp1).condition := C_None;
  7673. taicpu(hp1).opsize := S_B;
  7674. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7675. taicpu(hp1).loadconst(0, 0);
  7676. end;
  7677. end;
  7678. C_BE, C_NA:
  7679. begin
  7680. { Will only branch if equal to zero }
  7681. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7682. taicpu(hp1).condition := C_E;
  7683. end;
  7684. C_A, C_NBE:
  7685. begin
  7686. { Will only branch if not equal to zero }
  7687. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7688. taicpu(hp1).condition := C_NE;
  7689. end;
  7690. C_AE, C_NB, C_NC, C_NO:
  7691. begin
  7692. { Will always branch }
  7693. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7694. if taicpu(hp1).opcode = A_Jcc then
  7695. begin
  7696. MakeUnconditional(taicpu(hp1));
  7697. { Any jumps/set that follow will now be dead code }
  7698. RemoveDeadCodeAfterJump(taicpu(hp1));
  7699. Break;
  7700. end
  7701. else
  7702. begin
  7703. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7704. taicpu(hp1).opcode := A_MOV;
  7705. taicpu(hp1).ops := 2;
  7706. taicpu(hp1).condition := C_None;
  7707. taicpu(hp1).opsize := S_B;
  7708. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7709. taicpu(hp1).loadconst(0, 1);
  7710. end;
  7711. end;
  7712. C_None:
  7713. InternalError(2020012201);
  7714. C_P, C_PE, C_NP, C_PO:
  7715. { We can't handle parity checks and they should never be generated
  7716. after a general-purpose CMP (it's used in some floating-point
  7717. comparisons that don't use CMP) }
  7718. InternalError(2020012202);
  7719. else
  7720. { Zero/Equality, Sign, their complements and all of the
  7721. signed comparisons do not need to be converted };
  7722. end;
  7723. hp2 := hp1;
  7724. end;
  7725. { Convert the instruction to a TEST }
  7726. taicpu(p).opcode := A_TEST;
  7727. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7728. Result := True;
  7729. Exit;
  7730. end
  7731. else
  7732. begin
  7733. TransferUsedRegs(TmpUsedRegs);
  7734. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7735. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7736. begin
  7737. if (taicpu(p).oper[0]^.val = 1) and
  7738. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7739. begin
  7740. { Convert; To:
  7741. cmp $1,r/m cmp $0,r/m
  7742. jl @lbl jle @lbl
  7743. (Also do inverted conditions)
  7744. }
  7745. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7746. taicpu(p).oper[0]^.val := 0;
  7747. if taicpu(hp1).condition in [C_L, C_NGE] then
  7748. taicpu(hp1).condition := C_LE
  7749. else
  7750. taicpu(hp1).condition := C_NLE;
  7751. { If the instruction is now "cmp $0,%reg", convert it to a
  7752. TEST (and effectively do the work of the "cmp $0,%reg" in
  7753. the block above)
  7754. }
  7755. if (taicpu(p).oper[1]^.typ = top_reg) then
  7756. begin
  7757. taicpu(p).opcode := A_TEST;
  7758. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7759. end;
  7760. Result := True;
  7761. Exit;
  7762. end
  7763. else if (taicpu(p).oper[1]^.typ = top_reg)
  7764. {$ifdef x86_64}
  7765. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7766. {$endif x86_64}
  7767. then
  7768. begin
  7769. { cmp register,$8000 neg register
  7770. je target --> jo target
  7771. .... only if register is deallocated before jump.}
  7772. case Taicpu(p).opsize of
  7773. S_B: v:=$80;
  7774. S_W: v:=$8000;
  7775. S_L: v:=qword($80000000);
  7776. else
  7777. internalerror(2013112905);
  7778. end;
  7779. if (taicpu(p).oper[0]^.val=v) and
  7780. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7781. begin
  7782. TransferUsedRegs(TmpUsedRegs);
  7783. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7784. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7785. begin
  7786. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7787. Taicpu(p).opcode:=A_NEG;
  7788. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7789. Taicpu(p).clearop(1);
  7790. Taicpu(p).ops:=1;
  7791. if Taicpu(hp1).condition=C_E then
  7792. Taicpu(hp1).condition:=C_O
  7793. else
  7794. Taicpu(hp1).condition:=C_NO;
  7795. Result:=true;
  7796. exit;
  7797. end;
  7798. end;
  7799. end;
  7800. end;
  7801. end;
  7802. end;
  7803. if TrySwapMovCmp(p, hp1) then
  7804. begin
  7805. Result := True;
  7806. Exit;
  7807. end;
  7808. end;
  7809. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7810. var
  7811. hp1: tai;
  7812. begin
  7813. {
  7814. remove the second (v)pxor from
  7815. pxor reg,reg
  7816. ...
  7817. pxor reg,reg
  7818. }
  7819. Result:=false;
  7820. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7821. MatchOpType(taicpu(p),top_reg,top_reg) and
  7822. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7823. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7824. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7825. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7826. begin
  7827. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7828. RemoveInstruction(hp1);
  7829. Result:=true;
  7830. Exit;
  7831. end
  7832. {
  7833. replace
  7834. pxor reg1,reg1
  7835. movapd/s reg1,reg2
  7836. dealloc reg1
  7837. by
  7838. pxor reg2,reg2
  7839. }
  7840. else if GetNextInstruction(p,hp1) and
  7841. { we mix single and double opperations here because we assume that the compiler
  7842. generates vmovapd only after double operations and vmovaps only after single operations }
  7843. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7844. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7845. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7846. (taicpu(p).oper[0]^.typ=top_reg) then
  7847. begin
  7848. TransferUsedRegs(TmpUsedRegs);
  7849. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7850. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7851. begin
  7852. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7853. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7854. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7855. RemoveInstruction(hp1);
  7856. result:=true;
  7857. end;
  7858. end;
  7859. end;
  7860. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7861. var
  7862. hp1: tai;
  7863. begin
  7864. {
  7865. remove the second (v)pxor from
  7866. (v)pxor reg,reg
  7867. ...
  7868. (v)pxor reg,reg
  7869. }
  7870. Result:=false;
  7871. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7872. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7873. begin
  7874. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7875. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7876. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7877. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7878. begin
  7879. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7880. RemoveInstruction(hp1);
  7881. Result:=true;
  7882. Exit;
  7883. end;
  7884. {$ifdef x86_64}
  7885. {
  7886. replace
  7887. vpxor reg1,reg1,reg1
  7888. vmov reg,mem
  7889. by
  7890. movq $0,mem
  7891. }
  7892. if GetNextInstruction(p,hp1) and
  7893. MatchInstruction(hp1,A_VMOVSD,[]) and
  7894. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7895. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7896. begin
  7897. TransferUsedRegs(TmpUsedRegs);
  7898. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7899. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7900. begin
  7901. taicpu(hp1).loadconst(0,0);
  7902. taicpu(hp1).opcode:=A_MOV;
  7903. taicpu(hp1).opsize:=S_Q;
  7904. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7905. RemoveCurrentP(p);
  7906. result:=true;
  7907. Exit;
  7908. end;
  7909. end;
  7910. {$endif x86_64}
  7911. end
  7912. {
  7913. replace
  7914. vpxor reg1,reg1,reg2
  7915. by
  7916. vpxor reg2,reg2,reg2
  7917. to avoid unncessary data dependencies
  7918. }
  7919. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7920. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7921. begin
  7922. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7923. { avoid unncessary data dependency }
  7924. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7925. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7926. result:=true;
  7927. exit;
  7928. end;
  7929. Result:=OptPass1VOP(p);
  7930. end;
  7931. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7932. var
  7933. hp1 : tai;
  7934. begin
  7935. result:=false;
  7936. { replace
  7937. IMul const,%mreg1,%mreg2
  7938. Mov %reg2,%mreg3
  7939. dealloc %mreg3
  7940. by
  7941. Imul const,%mreg1,%mreg23
  7942. }
  7943. if (taicpu(p).ops=3) and
  7944. GetNextInstruction(p,hp1) and
  7945. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7946. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7947. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7948. begin
  7949. TransferUsedRegs(TmpUsedRegs);
  7950. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7951. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7952. begin
  7953. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7954. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7955. RemoveInstruction(hp1);
  7956. result:=true;
  7957. end;
  7958. end;
  7959. end;
  7960. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7961. var
  7962. hp1 : tai;
  7963. begin
  7964. result:=false;
  7965. { replace
  7966. IMul %reg0,%reg1,%reg2
  7967. Mov %reg2,%reg3
  7968. dealloc %reg2
  7969. by
  7970. Imul %reg0,%reg1,%reg3
  7971. }
  7972. if GetNextInstruction(p,hp1) and
  7973. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7974. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7975. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7976. begin
  7977. TransferUsedRegs(TmpUsedRegs);
  7978. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7979. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7980. begin
  7981. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7982. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7983. RemoveInstruction(hp1);
  7984. result:=true;
  7985. end;
  7986. end;
  7987. end;
  7988. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7989. var
  7990. hp1: tai;
  7991. begin
  7992. Result:=false;
  7993. { get rid of
  7994. (v)cvtss2sd reg0,<reg1,>reg2
  7995. (v)cvtss2sd reg2,<reg2,>reg0
  7996. }
  7997. if GetNextInstruction(p,hp1) and
  7998. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7999. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  8000. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  8001. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  8002. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  8003. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8004. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8005. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  8006. )
  8007. ) then
  8008. begin
  8009. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  8010. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  8011. begin
  8012. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  8013. RemoveCurrentP(p);
  8014. RemoveInstruction(hp1);
  8015. end
  8016. else
  8017. begin
  8018. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  8019. if taicpu(hp1).opcode=A_CVTSD2SS then
  8020. begin
  8021. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8022. taicpu(p).opcode:=A_MOVAPS;
  8023. end
  8024. else
  8025. begin
  8026. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  8027. taicpu(p).opcode:=A_VMOVAPS;
  8028. end;
  8029. taicpu(p).ops:=2;
  8030. RemoveInstruction(hp1);
  8031. end;
  8032. Result:=true;
  8033. Exit;
  8034. end;
  8035. end;
  8036. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  8037. var
  8038. hp1, hp2, hp3, hp4, hp5: tai;
  8039. ThisReg: TRegister;
  8040. begin
  8041. Result := False;
  8042. if not GetNextInstruction(p,hp1) then
  8043. Exit;
  8044. {
  8045. convert
  8046. j<c> .L1
  8047. mov 1,reg
  8048. jmp .L2
  8049. .L1
  8050. mov 0,reg
  8051. .L2
  8052. into
  8053. mov 0,reg
  8054. set<not(c)> reg
  8055. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8056. would destroy the flag contents
  8057. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  8058. executed at the same time as a previous comparison.
  8059. set<not(c)> reg
  8060. movzx reg, reg
  8061. }
  8062. if MatchInstruction(hp1,A_MOV,[]) and
  8063. (taicpu(hp1).oper[0]^.typ = top_const) and
  8064. (
  8065. (
  8066. (taicpu(hp1).oper[1]^.typ = top_reg)
  8067. {$ifdef i386}
  8068. { Under i386, ESI, EDI, EBP and ESP
  8069. don't have an 8-bit representation }
  8070. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8071. {$endif i386}
  8072. ) or (
  8073. {$ifdef i386}
  8074. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  8075. {$endif i386}
  8076. (taicpu(hp1).opsize = S_B)
  8077. )
  8078. ) and
  8079. GetNextInstruction(hp1,hp2) and
  8080. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8081. GetNextInstruction(hp2,hp3) and
  8082. (hp3.typ=ait_label) and
  8083. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  8084. GetNextInstruction(hp3,hp4) and
  8085. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  8086. (taicpu(hp4).oper[0]^.typ = top_const) and
  8087. (
  8088. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  8089. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  8090. ) and
  8091. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8092. GetNextInstruction(hp4,hp5) and
  8093. (hp5.typ=ait_label) and
  8094. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  8095. begin
  8096. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8097. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8098. tai_label(hp3).labsym.DecRefs;
  8099. { If this isn't the only reference to the middle label, we can
  8100. still make a saving - only that the first jump and everything
  8101. that follows will remain. }
  8102. if (tai_label(hp3).labsym.getrefs = 0) then
  8103. begin
  8104. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8105. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  8106. else
  8107. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  8108. { remove jump, first label and second MOV (also catching any aligns) }
  8109. repeat
  8110. if not GetNextInstruction(hp2, hp3) then
  8111. InternalError(2021040810);
  8112. RemoveInstruction(hp2);
  8113. hp2 := hp3;
  8114. until hp2 = hp5;
  8115. { Don't decrement reference count before the removal loop
  8116. above, otherwise GetNextInstruction won't stop on the
  8117. the label }
  8118. tai_label(hp5).labsym.DecRefs;
  8119. end
  8120. else
  8121. begin
  8122. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8123. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8124. else
  8125. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8126. end;
  8127. taicpu(p).opcode:=A_SETcc;
  8128. taicpu(p).opsize:=S_B;
  8129. taicpu(p).is_jmp:=False;
  8130. if taicpu(hp1).opsize=S_B then
  8131. begin
  8132. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8133. if taicpu(hp1).oper[1]^.typ = top_reg then
  8134. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8135. RemoveInstruction(hp1);
  8136. end
  8137. else
  8138. begin
  8139. { Will be a register because the size can't be S_B otherwise }
  8140. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8141. taicpu(p).loadreg(0, ThisReg);
  8142. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8143. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8144. begin
  8145. case taicpu(hp1).opsize of
  8146. S_W:
  8147. taicpu(hp1).opsize := S_BW;
  8148. S_L:
  8149. taicpu(hp1).opsize := S_BL;
  8150. {$ifdef x86_64}
  8151. S_Q:
  8152. begin
  8153. taicpu(hp1).opsize := S_BL;
  8154. { Change the destination register to 32-bit }
  8155. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8156. end;
  8157. {$endif x86_64}
  8158. else
  8159. InternalError(2021040820);
  8160. end;
  8161. taicpu(hp1).opcode := A_MOVZX;
  8162. taicpu(hp1).loadreg(0, ThisReg);
  8163. end
  8164. else
  8165. begin
  8166. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8167. { hp1 is already a MOV instruction with the correct register }
  8168. taicpu(hp1).loadconst(0, 0);
  8169. { Inserting it right before p will guarantee that the flags are also tracked }
  8170. asml.Remove(hp1);
  8171. asml.InsertBefore(hp1, p);
  8172. end;
  8173. end;
  8174. Result:=true;
  8175. exit;
  8176. end
  8177. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8178. Result := TryJccStcClcOpt(p, hp1)
  8179. else if (hp1.typ = ait_label) then
  8180. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8181. end;
  8182. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8183. var
  8184. hp1, hp2, hp3: tai;
  8185. SourceRef, TargetRef: TReference;
  8186. CurrentReg: TRegister;
  8187. begin
  8188. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8189. if not UseAVX then
  8190. InternalError(2021100501);
  8191. Result := False;
  8192. { Look for the following to simplify:
  8193. vmovdqa/u x(mem1), %xmmreg
  8194. vmovdqa/u %xmmreg, y(mem2)
  8195. vmovdqa/u x+16(mem1), %xmmreg
  8196. vmovdqa/u %xmmreg, y+16(mem2)
  8197. Change to:
  8198. vmovdqa/u x(mem1), %ymmreg
  8199. vmovdqa/u %ymmreg, y(mem2)
  8200. vpxor %ymmreg, %ymmreg, %ymmreg
  8201. ( The VPXOR instruction is to zero the upper half, thus removing the
  8202. need to call the potentially expensive VZEROUPPER instruction. Other
  8203. peephole optimisations can remove VPXOR if it's unnecessary )
  8204. }
  8205. TransferUsedRegs(TmpUsedRegs);
  8206. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8207. { NOTE: In the optimisations below, if the references dictate that an
  8208. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8209. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8210. if (taicpu(p).opsize = S_XMM) and
  8211. MatchOpType(taicpu(p), top_ref, top_reg) and
  8212. GetNextInstruction(p, hp1) and
  8213. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8214. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8215. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8216. begin
  8217. SourceRef := taicpu(p).oper[0]^.ref^;
  8218. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8219. if GetNextInstruction(hp1, hp2) and
  8220. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8221. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8222. begin
  8223. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8224. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8225. Inc(SourceRef.offset, 16);
  8226. { Reuse the register in the first block move }
  8227. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8228. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8229. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8230. begin
  8231. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8232. Inc(TargetRef.offset, 16);
  8233. if GetNextInstruction(hp2, hp3) and
  8234. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8235. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8236. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8237. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8238. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8239. begin
  8240. { Update the register tracking to the new size }
  8241. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8242. { Remember that the offsets are 16 ahead }
  8243. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8244. if not (
  8245. ((SourceRef.offset mod 32) = 16) and
  8246. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8247. ) then
  8248. taicpu(p).opcode := A_VMOVDQU;
  8249. taicpu(p).opsize := S_YMM;
  8250. taicpu(p).oper[1]^.reg := CurrentReg;
  8251. if not (
  8252. ((TargetRef.offset mod 32) = 16) and
  8253. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8254. ) then
  8255. taicpu(hp1).opcode := A_VMOVDQU;
  8256. taicpu(hp1).opsize := S_YMM;
  8257. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8258. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8259. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8260. if (pi_uses_ymm in current_procinfo.flags) then
  8261. RemoveInstruction(hp2)
  8262. else
  8263. begin
  8264. taicpu(hp2).opcode := A_VPXOR;
  8265. taicpu(hp2).opsize := S_YMM;
  8266. taicpu(hp2).loadreg(0, CurrentReg);
  8267. taicpu(hp2).loadreg(1, CurrentReg);
  8268. taicpu(hp2).loadreg(2, CurrentReg);
  8269. taicpu(hp2).ops := 3;
  8270. end;
  8271. RemoveInstruction(hp3);
  8272. Result := True;
  8273. Exit;
  8274. end;
  8275. end
  8276. else
  8277. begin
  8278. { See if the next references are 16 less rather than 16 greater }
  8279. Dec(SourceRef.offset, 32); { -16 the other way }
  8280. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8281. begin
  8282. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8283. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8284. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8285. GetNextInstruction(hp2, hp3) and
  8286. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8287. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8288. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8289. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8290. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8291. begin
  8292. { Update the register tracking to the new size }
  8293. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8294. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8295. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8296. if not(
  8297. ((SourceRef.offset mod 32) = 0) and
  8298. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8299. ) then
  8300. taicpu(hp2).opcode := A_VMOVDQU;
  8301. taicpu(hp2).opsize := S_YMM;
  8302. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8303. if not (
  8304. ((TargetRef.offset mod 32) = 0) and
  8305. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8306. ) then
  8307. taicpu(hp3).opcode := A_VMOVDQU;
  8308. taicpu(hp3).opsize := S_YMM;
  8309. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8310. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8311. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8312. if (pi_uses_ymm in current_procinfo.flags) then
  8313. RemoveInstruction(hp1)
  8314. else
  8315. begin
  8316. taicpu(hp1).opcode := A_VPXOR;
  8317. taicpu(hp1).opsize := S_YMM;
  8318. taicpu(hp1).loadreg(0, CurrentReg);
  8319. taicpu(hp1).loadreg(1, CurrentReg);
  8320. taicpu(hp1).loadreg(2, CurrentReg);
  8321. taicpu(hp1).ops := 3;
  8322. Asml.Remove(hp1);
  8323. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8324. end;
  8325. RemoveCurrentP(p, hp2);
  8326. Result := True;
  8327. Exit;
  8328. end;
  8329. end;
  8330. end;
  8331. end;
  8332. end;
  8333. end;
  8334. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8335. var
  8336. hp2, hp3, first_assignment: tai;
  8337. IncCount, OperIdx: Integer;
  8338. OrigLabel: TAsmLabel;
  8339. begin
  8340. Count := 0;
  8341. Result := False;
  8342. first_assignment := nil;
  8343. if (LoopCount >= 20) then
  8344. begin
  8345. { Guard against infinite loops }
  8346. Exit;
  8347. end;
  8348. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8349. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8350. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8351. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8352. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8353. Exit;
  8354. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8355. {
  8356. change
  8357. jmp .L1
  8358. ...
  8359. .L1:
  8360. mov ##, ## ( multiple movs possible )
  8361. jmp/ret
  8362. into
  8363. mov ##, ##
  8364. jmp/ret
  8365. }
  8366. if not Assigned(hp1) then
  8367. begin
  8368. hp1 := GetLabelWithSym(OrigLabel);
  8369. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8370. Exit;
  8371. end;
  8372. hp2 := hp1;
  8373. while Assigned(hp2) do
  8374. begin
  8375. if Assigned(hp2) and (hp2.typ = ait_label) then
  8376. SkipLabels(hp2,hp2);
  8377. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8378. Break;
  8379. case taicpu(hp2).opcode of
  8380. A_MOVSD:
  8381. begin
  8382. if taicpu(hp2).ops = 0 then
  8383. { Wrong MOVSD }
  8384. Break;
  8385. Inc(Count);
  8386. if Count >= 5 then
  8387. { Too many to be worthwhile }
  8388. Break;
  8389. GetNextInstruction(hp2, hp2);
  8390. Continue;
  8391. end;
  8392. A_MOV,
  8393. A_MOVD,
  8394. A_MOVQ,
  8395. A_MOVSX,
  8396. {$ifdef x86_64}
  8397. A_MOVSXD,
  8398. {$endif x86_64}
  8399. A_MOVZX,
  8400. A_MOVAPS,
  8401. A_MOVUPS,
  8402. A_MOVSS,
  8403. A_MOVAPD,
  8404. A_MOVUPD,
  8405. A_MOVDQA,
  8406. A_MOVDQU,
  8407. A_VMOVSS,
  8408. A_VMOVAPS,
  8409. A_VMOVUPS,
  8410. A_VMOVSD,
  8411. A_VMOVAPD,
  8412. A_VMOVUPD,
  8413. A_VMOVDQA,
  8414. A_VMOVDQU:
  8415. begin
  8416. Inc(Count);
  8417. if Count >= 5 then
  8418. { Too many to be worthwhile }
  8419. Break;
  8420. GetNextInstruction(hp2, hp2);
  8421. Continue;
  8422. end;
  8423. A_JMP:
  8424. begin
  8425. { Guard against infinite loops }
  8426. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8427. Exit;
  8428. { Analyse this jump first in case it also duplicates assignments }
  8429. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8430. begin
  8431. { Something did change! }
  8432. Result := True;
  8433. Inc(Count, IncCount);
  8434. if Count >= 5 then
  8435. begin
  8436. { Too many to be worthwhile }
  8437. Exit;
  8438. end;
  8439. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8440. Break;
  8441. end;
  8442. Result := True;
  8443. Break;
  8444. end;
  8445. A_RET:
  8446. begin
  8447. Result := True;
  8448. Break;
  8449. end;
  8450. else
  8451. Break;
  8452. end;
  8453. end;
  8454. if Result then
  8455. begin
  8456. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8457. if Count = 0 then
  8458. begin
  8459. Result := False;
  8460. Exit;
  8461. end;
  8462. TransferUsedRegs(TmpUsedRegs);
  8463. hp3 := p;
  8464. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8465. while True do
  8466. begin
  8467. if Assigned(hp1) and (hp1.typ = ait_label) then
  8468. SkipLabels(hp1,hp1);
  8469. case hp1.typ of
  8470. ait_regalloc:
  8471. if tai_regalloc(hp1).ratype = ra_dealloc then
  8472. begin
  8473. { Duplicate the register deallocation... }
  8474. hp3:=tai(hp1.getcopy);
  8475. if first_assignment = nil then
  8476. first_assignment := hp3;
  8477. asml.InsertBefore(hp3, p);
  8478. { ... but also reallocate it after the jump }
  8479. hp3:=tai(hp1.getcopy);
  8480. tai_regalloc(hp3).ratype := ra_alloc;
  8481. asml.InsertAfter(hp3, p);
  8482. end;
  8483. ait_instruction:
  8484. case taicpu(hp1).opcode of
  8485. A_JMP:
  8486. begin
  8487. { Change the original jump to the new destination }
  8488. OrigLabel.decrefs;
  8489. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8490. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8491. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8492. if not Assigned(first_assignment) then
  8493. InternalError(2021040810)
  8494. else
  8495. p := first_assignment;
  8496. Exit;
  8497. end;
  8498. A_RET:
  8499. begin
  8500. { Now change the jump into a RET instruction }
  8501. ConvertJumpToRET(p, hp1);
  8502. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8503. if not Assigned(first_assignment) then
  8504. InternalError(2021040811)
  8505. else
  8506. p := first_assignment;
  8507. Exit;
  8508. end;
  8509. else
  8510. begin
  8511. { Duplicate the MOV instruction }
  8512. hp3:=tai(hp1.getcopy);
  8513. if first_assignment = nil then
  8514. first_assignment := hp3;
  8515. asml.InsertBefore(hp3, p);
  8516. { Make sure the compiler knows about any final registers written here }
  8517. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8518. with taicpu(hp3).oper[OperIdx]^ do
  8519. begin
  8520. case typ of
  8521. top_ref:
  8522. begin
  8523. if (ref^.base <> NR_NO) and
  8524. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  8525. (
  8526. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  8527. (
  8528. { Allow the frame pointer if it's not being used by the procedure as such }
  8529. Assigned(current_procinfo) and
  8530. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8531. )
  8532. )
  8533. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8534. then
  8535. begin
  8536. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  8537. if not Assigned(first_assignment) then
  8538. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  8539. end;
  8540. if (ref^.index <> NR_NO) and
  8541. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  8542. (
  8543. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  8544. (
  8545. { Allow the frame pointer if it's not being used by the procedure as such }
  8546. Assigned(current_procinfo) and
  8547. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8548. )
  8549. )
  8550. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8551. (ref^.index <> ref^.base) then
  8552. begin
  8553. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  8554. if not Assigned(first_assignment) then
  8555. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  8556. end;
  8557. end;
  8558. top_reg:
  8559. begin
  8560. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  8561. if not Assigned(first_assignment) then
  8562. IncludeRegInUsedRegs(reg, UsedRegs);
  8563. end;
  8564. else
  8565. ;
  8566. end;
  8567. end;
  8568. end;
  8569. end;
  8570. else
  8571. InternalError(2021040720);
  8572. end;
  8573. if not GetNextInstruction(hp1, hp1, [ait_regalloc]) then
  8574. { Should have dropped out earlier }
  8575. InternalError(2021040710);
  8576. end;
  8577. end;
  8578. end;
  8579. const
  8580. WriteOp: array[0..3] of set of TInsChange = (
  8581. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8582. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8583. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8584. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8585. RegWriteFlags: array[0..7] of set of TInsChange = (
  8586. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8587. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8588. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8589. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8590. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8591. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8592. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8593. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8594. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8595. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8596. var
  8597. hp2: tai;
  8598. X: Integer;
  8599. begin
  8600. { If we have something like:
  8601. op ###,###
  8602. mov ###,###
  8603. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8604. interfere in regards to what they write to.
  8605. NOTE: p must be a 2-operand instruction
  8606. }
  8607. Result := False;
  8608. if (hp1.typ <> ait_instruction) or
  8609. taicpu(hp1).is_jmp or
  8610. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8611. Exit;
  8612. { NOP is a pipeline fence, likely marking the beginning of the function
  8613. epilogue, so drop out. Similarly, drop out if POP or RET are
  8614. encountered }
  8615. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8616. Exit;
  8617. if (taicpu(hp1).opcode = A_MOVSD) and
  8618. (taicpu(hp1).ops = 0) then
  8619. { Wrong MOVSD }
  8620. Exit;
  8621. { Check for writes to specific registers first }
  8622. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8623. for X := 0 to 7 do
  8624. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8625. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8626. Exit;
  8627. for X := 0 to taicpu(hp1).ops - 1 do
  8628. begin
  8629. { Check to see if this operand writes to something }
  8630. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8631. { And matches something in the CMP/TEST instruction }
  8632. (
  8633. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8634. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8635. (
  8636. { If it's a register, make sure the register written to doesn't
  8637. appear in the cmp instruction as part of a reference }
  8638. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8639. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8640. )
  8641. ) then
  8642. Exit;
  8643. end;
  8644. { Check p to make sure it doesn't write to something that affects hp1 }
  8645. { Check for writes to specific registers first }
  8646. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8647. for X := 0 to 7 do
  8648. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8649. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8650. Exit;
  8651. for X := 0 to taicpu(p).ops - 1 do
  8652. begin
  8653. { Check to see if this operand writes to something }
  8654. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8655. { And matches something in hp1 }
  8656. (taicpu(p).oper[X]^.typ = top_reg) and
  8657. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8658. Exit;
  8659. end;
  8660. { The instruction can be safely moved }
  8661. asml.Remove(hp1);
  8662. { Try to insert after the last instructions where the FLAGS register is not
  8663. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8664. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8665. asml.InsertBefore(hp1, hp2)
  8666. { Failing that, try to insert after the last instructions where the
  8667. FLAGS register is not yet in use }
  8668. else if GetLastInstruction(p, hp2) and
  8669. (
  8670. (hp2.typ <> ait_instruction) or
  8671. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8672. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8673. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8674. ) then
  8675. asml.InsertAfter(hp1, hp2)
  8676. else
  8677. { Note, if p.Previous is nil (even if it should logically never be the
  8678. case), FindRegAllocBackward immediately exits with False and so we
  8679. safely land here (we can't just pass p because FindRegAllocBackward
  8680. immediately exits on an instruction). [Kit] }
  8681. asml.InsertBefore(hp1, p);
  8682. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8683. { We can't trust UsedRegs because we're looking backwards, although we
  8684. know the registers are allocated after p at the very least, so manually
  8685. create tai_regalloc objects if needed }
  8686. for X := 0 to taicpu(hp1).ops - 1 do
  8687. case taicpu(hp1).oper[X]^.typ of
  8688. top_reg:
  8689. begin
  8690. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8691. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8692. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8693. end;
  8694. top_ref:
  8695. begin
  8696. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8697. begin
  8698. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8699. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8700. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8701. end;
  8702. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8703. begin
  8704. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8705. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8706. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8707. end;
  8708. end;
  8709. else
  8710. ;
  8711. end;
  8712. Result := True;
  8713. end;
  8714. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8715. var
  8716. hp2: tai;
  8717. X: Integer;
  8718. begin
  8719. { If we have something like:
  8720. cmp ###,%reg1
  8721. mov 0,%reg2
  8722. And no modified registers are shared, move the instruction to before
  8723. the comparison as this means it can be optimised without worrying
  8724. about the FLAGS register. (CMP/MOV is generated by
  8725. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8726. As long as the second instruction doesn't use the flags or one of the
  8727. registers used by CMP or TEST (also check any references that use the
  8728. registers), then it can be moved prior to the comparison.
  8729. }
  8730. Result := False;
  8731. if not TrySwapMovOp(p, hp1) then
  8732. Exit;
  8733. if taicpu(hp1).opcode = A_LEA then
  8734. { The flags will be overwritten by the CMP/TEST instruction }
  8735. ConvertLEA(taicpu(hp1));
  8736. Result := True;
  8737. { Can we move it one further back? }
  8738. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8739. { Check to see if CMP/TEST is a comparison against zero }
  8740. (
  8741. (
  8742. (taicpu(p).opcode = A_CMP) and
  8743. MatchOperand(taicpu(p).oper[0]^, 0)
  8744. ) or
  8745. (
  8746. (taicpu(p).opcode = A_TEST) and
  8747. (
  8748. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8749. MatchOperand(taicpu(p).oper[0]^, -1)
  8750. )
  8751. )
  8752. ) and
  8753. { These instructions set the zero flag if the result is zero }
  8754. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8755. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8756. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8757. TrySwapMovOp(hp2, hp1);
  8758. end;
  8759. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  8760. var
  8761. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  8762. JumpLabel: TAsmLabel;
  8763. TmpBool: Boolean;
  8764. begin
  8765. Result := False;
  8766. { Look for:
  8767. stc/clc
  8768. j(c) .L1
  8769. ...
  8770. .L1:
  8771. set(n)cb %reg
  8772. (flags deallocated)
  8773. j(c) .L2
  8774. Change to:
  8775. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  8776. j(c) .L2
  8777. }
  8778. p_last := p;
  8779. while GetNextInstruction(p_last, hp1) and
  8780. (hp1.typ = ait_instruction) and
  8781. IsJumpToLabel(taicpu(hp1)) do
  8782. begin
  8783. if DoJumpOptimizations(hp1, TmpBool) then
  8784. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8785. Continue;
  8786. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  8787. if not Assigned(JumpLabel) then
  8788. InternalError(2024012801);
  8789. { Optimise the J(c); stc/clc optimisation first since this will
  8790. get missed if the main optimisation takes place }
  8791. if (taicpu(hp1).opcode = A_JCC) then
  8792. begin
  8793. if GetNextInstruction(hp1, hp2) and
  8794. MatchInstruction(hp2, A_CLC, A_STC, []) and
  8795. TryJccStcClcOpt(hp1, hp2) then
  8796. begin
  8797. Result := True;
  8798. Exit;
  8799. end;
  8800. hp2 := nil; { Suppress compiler warning }
  8801. if (taicpu(hp1).condition in [C_C, C_NC]) and
  8802. { Make sure the flags aren't used again }
  8803. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  8804. begin
  8805. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8806. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  8807. begin
  8808. if (taicpu(p).opcode = A_STC) then
  8809. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  8810. else
  8811. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  8812. MakeUnconditional(taicpu(hp1));
  8813. { Move the jump to after the flag deallocations }
  8814. Asml.Remove(hp1);
  8815. Asml.InsertAfter(hp1, hp2);
  8816. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8817. Result := True;
  8818. Exit;
  8819. end
  8820. else
  8821. begin
  8822. if (taicpu(p).opcode = A_STC) then
  8823. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  8824. else
  8825. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  8826. { In this case, the jump is deterministic in that it will never be taken }
  8827. JumpLabel.DecRefs;
  8828. RemoveInstruction(hp1);
  8829. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  8830. Result := True;
  8831. Exit;
  8832. end;
  8833. end;
  8834. end;
  8835. hp2 := nil; { Suppress compiler warning }
  8836. if
  8837. { Make sure the carry flag doesn't appear in the jump conditions }
  8838. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8839. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  8840. GetNextInstruction(hp2, p_dist) and
  8841. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  8842. (taicpu(p_dist).condition in [C_C, C_NC]) then
  8843. begin
  8844. case taicpu(p_dist).opcode of
  8845. A_Jcc:
  8846. begin
  8847. if DoJumpOptimizations(p_dist, TmpBool) then
  8848. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8849. Continue;
  8850. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8851. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  8852. begin
  8853. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  8854. JumpLabel.decrefs;
  8855. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  8856. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8857. Result := True;
  8858. Exit;
  8859. end
  8860. else if GetNextInstruction(p_dist, hp1_dist) and
  8861. (hp1_dist.typ = ait_label) then
  8862. begin
  8863. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  8864. JumpLabel.decrefs;
  8865. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  8866. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8867. Result := True;
  8868. Exit;
  8869. end;
  8870. end;
  8871. A_SETcc:
  8872. if { Make sure the flags aren't used again }
  8873. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  8874. GetNextInstruction(hp2, hp1_dist) and
  8875. (hp1_dist.typ = ait_instruction) and
  8876. IsJumpToLabel(taicpu(hp1_dist)) and
  8877. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8878. { This works if hp1_dist or both are regular JMP instructions }
  8879. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  8880. (
  8881. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  8882. { Make sure the register isn't still in use, otherwise it
  8883. may get corrupted (fixes #40659) }
  8884. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  8885. ) then
  8886. begin
  8887. taicpu(p).allocate_oper(2);
  8888. taicpu(p).ops := 2;
  8889. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  8890. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  8891. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  8892. taicpu(p).opcode := A_MOV;
  8893. taicpu(p).opsize := S_B;
  8894. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8895. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  8896. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  8897. JumpLabel.decrefs;
  8898. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  8899. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  8900. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  8901. (tai_regalloc(hp2).ratype = ra_alloc) then
  8902. begin
  8903. Asml.Remove(hp2);
  8904. Asml.InsertAfter(hp2, p);
  8905. end;
  8906. Result := True;
  8907. Exit;
  8908. end;
  8909. else
  8910. ;
  8911. end;
  8912. end;
  8913. p_last := hp1;
  8914. end;
  8915. end;
  8916. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  8917. var
  8918. hp2, hp3: tai;
  8919. TempBool: Boolean;
  8920. begin
  8921. Result := False;
  8922. {
  8923. j(c) .L1
  8924. stc/clc
  8925. .L1:
  8926. jc/jnc .L2
  8927. (Flags deallocated)
  8928. Change to:
  8929. j)c) .L1
  8930. jmp .L2
  8931. .L1:
  8932. jc/jnc .L2
  8933. Then call DoJumpOptimizations to convert to:
  8934. j(nc) .L2
  8935. .L1: (may become a dead label)
  8936. jc/jnc .L2
  8937. }
  8938. if GetNextInstruction(hp1, hp2) and
  8939. (hp2.typ = ait_label) and
  8940. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  8941. GetNextInstruction(hp2, hp3) and
  8942. MatchInstruction(hp3, A_Jcc, []) and
  8943. (
  8944. (
  8945. (taicpu(hp3).condition = C_C) and
  8946. (taicpu(hp1).opcode = A_STC)
  8947. ) or (
  8948. (taicpu(hp3).condition = C_NC) and
  8949. (taicpu(hp1).opcode = A_CLC)
  8950. )
  8951. ) and
  8952. { Make sure the flags aren't used again }
  8953. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  8954. begin
  8955. taicpu(hp1).allocate_oper(1);
  8956. taicpu(hp1).ops := 1;
  8957. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  8958. taicpu(hp1).opcode := A_JMP;
  8959. taicpu(hp1).is_jmp := True;
  8960. TempBool := True; { Prevent compiler warnings }
  8961. if DoJumpOptimizations(p, TempBool) then
  8962. Result := True
  8963. else
  8964. Include(OptsToCheck, aoc_ForceNewIteration);
  8965. end;
  8966. end;
  8967. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  8968. begin
  8969. { This generally only executes under -O3 and above }
  8970. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  8971. end;
  8972. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  8973. var
  8974. hp1, hp2: tai;
  8975. FoundComparison: Boolean;
  8976. begin
  8977. { Run the pass 1 optimisations as well, since they may have some effect
  8978. after the CMOV blocks are created in OptPass2Jcc }
  8979. Result := False;
  8980. { Result := OptPass1CMOVcc(p);
  8981. if Result then
  8982. Exit;}
  8983. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  8984. and make a slightly inefficent result on branching-type blocks, notably
  8985. when setting a function result then jumping to the function epilogue.
  8986. In this case, change:
  8987. cmov(c) %reg1,%reg2
  8988. j(c) @lbl
  8989. (%reg2 deallocated)
  8990. To:
  8991. mov %reg11,%reg2
  8992. j(c) @lbl
  8993. Note, we can't use GetNextInstructionUsingReg to find the conditional
  8994. jump because if it's not present, we may end up with a jump that's
  8995. completely unrelated.
  8996. }
  8997. hp1 := p;
  8998. while GetNextInstruction(hp1, hp1) and
  8999. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  9000. if (hp1.typ = ait_instruction) and
  9001. (taicpu(hp1).opcode = A_Jcc) and
  9002. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  9003. begin
  9004. TransferUsedRegs(TmpUsedRegs);
  9005. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  9006. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  9007. (
  9008. { See if we can find a more distant instruction that overwrites
  9009. the destination register }
  9010. (cs_opt_level3 in current_settings.optimizerswitches) and
  9011. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9012. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  9013. ) then
  9014. begin
  9015. if (taicpu(p).oper[0]^.typ = top_reg) then
  9016. begin
  9017. { Search backwards to see if the source register is set to a
  9018. constant }
  9019. FoundComparison := False;
  9020. hp1 := p;
  9021. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  9022. begin
  9023. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  9024. begin
  9025. FoundComparison := True;
  9026. Continue;
  9027. end;
  9028. { Once we find the CMP, TEST or similar instruction, we
  9029. have to stop if we find anything other than a MOV }
  9030. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  9031. Break;
  9032. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  9033. { Destination register was modified }
  9034. Break;
  9035. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  9036. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  9037. begin
  9038. { Found a constant! }
  9039. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  9040. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9041. { The source register is no longer in use }
  9042. RemoveInstruction(hp1);
  9043. Break;
  9044. end;
  9045. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  9046. { Some other instruction has modified the source register }
  9047. Break;
  9048. end;
  9049. end;
  9050. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  9051. taicpu(p).opcode := A_MOV;
  9052. taicpu(p).condition := C_None;
  9053. { Rely on the post peephole stage to put the MOV before the
  9054. CMP/TEST instruction that appears prior }
  9055. Result := True;
  9056. Exit;
  9057. end;
  9058. end;
  9059. end;
  9060. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  9061. function IsXCHGAcceptable: Boolean; inline;
  9062. begin
  9063. { Always accept if optimising for size }
  9064. Result := (cs_opt_size in current_settings.optimizerswitches) or
  9065. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  9066. than 3, so it becomes a saving compared to three MOVs with two of
  9067. them able to execute simultaneously. [Kit] }
  9068. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  9069. end;
  9070. var
  9071. NewRef: TReference;
  9072. hp1, hp2, hp3, hp4: Tai;
  9073. {$ifndef x86_64}
  9074. OperIdx: Integer;
  9075. {$endif x86_64}
  9076. NewInstr : Taicpu;
  9077. NewAligh : Tai_align;
  9078. DestLabel: TAsmLabel;
  9079. TempTracking: TAllUsedRegs;
  9080. function TryMovArith2Lea(InputInstr: tai): Boolean;
  9081. var
  9082. NextInstr: tai;
  9083. begin
  9084. Result := False;
  9085. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  9086. if not GetNextInstruction(InputInstr, NextInstr) or
  9087. (
  9088. { The FLAGS register isn't always tracked properly, so do not
  9089. perform this optimisation if a conditional statement follows }
  9090. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  9091. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  9092. ) then
  9093. begin
  9094. reference_reset(NewRef, 1, []);
  9095. NewRef.base := taicpu(p).oper[0]^.reg;
  9096. NewRef.scalefactor := 1;
  9097. if taicpu(InputInstr).opcode = A_ADD then
  9098. begin
  9099. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  9100. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  9101. end
  9102. else
  9103. begin
  9104. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  9105. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  9106. end;
  9107. taicpu(p).opcode := A_LEA;
  9108. taicpu(p).loadref(0, NewRef);
  9109. { For the sake of debugging, have the line info match the
  9110. arithmetic instruction rather than the MOV instruction }
  9111. taicpu(p).fileinfo := taicpu(InputInstr).fileinfo;
  9112. RemoveInstruction(InputInstr);
  9113. Result := True;
  9114. end;
  9115. end;
  9116. begin
  9117. Result:=false;
  9118. { This optimisation adds an instruction, so only do it for speed }
  9119. if not (cs_opt_size in current_settings.optimizerswitches) and
  9120. MatchOpType(taicpu(p), top_const, top_reg) and
  9121. (taicpu(p).oper[0]^.val = 0) then
  9122. begin
  9123. { To avoid compiler warning }
  9124. DestLabel := nil;
  9125. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  9126. InternalError(2021040750);
  9127. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  9128. Exit;
  9129. case hp1.typ of
  9130. ait_label:
  9131. begin
  9132. { Change:
  9133. mov $0,%reg mov $0,%reg
  9134. @Lbl1: @Lbl1:
  9135. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  9136. je @Lbl2 jne @Lbl2
  9137. To: To:
  9138. mov $0,%reg mov $0,%reg
  9139. jmp @Lbl2 jmp @Lbl3
  9140. (align) (align)
  9141. @Lbl1: @Lbl1:
  9142. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9143. je @Lbl2 je @Lbl2
  9144. @Lbl3: <-- Only if label exists
  9145. (Not if it's optimised for size)
  9146. }
  9147. if not GetNextInstruction(hp1, hp2) then
  9148. Exit;
  9149. if (hp2.typ = ait_instruction) and
  9150. (
  9151. { Register sizes must exactly match }
  9152. (
  9153. (taicpu(hp2).opcode = A_CMP) and
  9154. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9155. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9156. ) or (
  9157. (taicpu(hp2).opcode = A_TEST) and
  9158. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9159. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9160. )
  9161. ) and GetNextInstruction(hp2, hp3) and
  9162. (hp3.typ = ait_instruction) and
  9163. (taicpu(hp3).opcode = A_JCC) and
  9164. (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
  9165. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9166. begin
  9167. { Check condition of jump }
  9168. { Always true? }
  9169. if condition_in(C_E, taicpu(hp3).condition) then
  9170. begin
  9171. { Copy label symbol and obtain matching label entry for the
  9172. conditional jump, as this will be our destination}
  9173. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9174. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9175. Result := True;
  9176. end
  9177. { Always false? }
  9178. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9179. begin
  9180. { This is only worth it if there's a jump to take }
  9181. case hp2.typ of
  9182. ait_instruction:
  9183. begin
  9184. if taicpu(hp2).opcode = A_JMP then
  9185. begin
  9186. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9187. { An unconditional jump follows the conditional jump which will always be false,
  9188. so use this jump's destination for the new jump }
  9189. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9190. Result := True;
  9191. end
  9192. else if taicpu(hp2).opcode = A_JCC then
  9193. begin
  9194. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9195. if condition_in(C_E, taicpu(hp2).condition) then
  9196. begin
  9197. { A second conditional jump follows the conditional jump which will always be false,
  9198. while the second jump is always True, so use this jump's destination for the new jump }
  9199. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9200. Result := True;
  9201. end;
  9202. { Don't risk it if the jump isn't always true (Result remains False) }
  9203. end;
  9204. end;
  9205. else
  9206. { If anything else don't optimise };
  9207. end;
  9208. end;
  9209. if Result then
  9210. begin
  9211. { Just so we have something to insert as a paremeter}
  9212. reference_reset(NewRef, 1, []);
  9213. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9214. { Now actually load the correct parameter (this also
  9215. increases the reference count) }
  9216. NewInstr.loadsymbol(0, DestLabel, 0);
  9217. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9218. begin
  9219. { Get instruction before original label (may not be p under -O3) }
  9220. if not GetLastInstruction(hp1, hp2) then
  9221. { Shouldn't fail here }
  9222. InternalError(2021040701);
  9223. end
  9224. else
  9225. hp2 := p;
  9226. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9227. AsmL.InsertAfter(NewInstr, hp2);
  9228. { Add new alignment field }
  9229. (* AsmL.InsertAfter(
  9230. cai_align.create_max(
  9231. current_settings.alignment.jumpalign,
  9232. current_settings.alignment.jumpalignskipmax
  9233. ),
  9234. NewInstr
  9235. ); *)
  9236. end;
  9237. Exit;
  9238. end;
  9239. end;
  9240. else
  9241. ;
  9242. end;
  9243. end;
  9244. if not GetNextInstruction(p, hp1) then
  9245. Exit;
  9246. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9247. begin
  9248. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9249. begin
  9250. Result := True;
  9251. Exit;
  9252. end;
  9253. { This optimisation is only effective on a second run of Pass 2,
  9254. hence -O3 or above.
  9255. Change:
  9256. mov %reg1,%reg2
  9257. cmp/test (contains %reg1)
  9258. mov x, %reg1
  9259. (another mov or a j(c))
  9260. To:
  9261. mov %reg1,%reg2
  9262. mov x, %reg1
  9263. cmp (%reg1 replaced with %reg2)
  9264. (another mov or a j(c))
  9265. The requirement of an additional MOV or a jump ensures there
  9266. isn't performance loss, since a j(c) will permit macro-fusion
  9267. with the cmp instruction, while another MOV likely means it's
  9268. not all being executed in a single cycle due to parallelisation.
  9269. }
  9270. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9271. MatchOpType(taicpu(p), top_reg, top_reg) and
  9272. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9273. GetNextInstruction(hp1, hp2) and
  9274. MatchInstruction(hp2, A_MOV, []) and
  9275. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9276. { Registers don't have to be the same size in this case }
  9277. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9278. GetNextInstruction(hp2, hp3) and
  9279. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9280. { Make sure the operands in the camparison can be safely replaced }
  9281. (
  9282. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9283. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9284. ) and
  9285. (
  9286. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9287. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9288. ) then
  9289. begin
  9290. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9291. AsmL.Remove(hp2);
  9292. AsmL.InsertAfter(hp2, p);
  9293. Result := True;
  9294. Exit;
  9295. end;
  9296. end;
  9297. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9298. begin
  9299. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9300. further, but we can't just put this jump optimisation in pass 1
  9301. because it tends to perform worse when conditional jumps are
  9302. nearby (e.g. when converting CMOV instructions). [Kit] }
  9303. CopyUsedRegs(TempTracking);
  9304. UpdateUsedRegs(tai(p.Next));
  9305. if OptPass2JMP(hp1) then
  9306. begin
  9307. { Restore register state }
  9308. RestoreUsedRegs(TempTracking);
  9309. ReleaseUsedRegs(TempTracking);
  9310. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9311. OptPass1MOV(p);
  9312. Result := True;
  9313. Exit;
  9314. end;
  9315. { If OptPass2JMP returned False, no optimisations were done to
  9316. the jump and there are no further optimisations that can be done
  9317. to the MOV instruction on this pass other than FuncMov2Func }
  9318. { Restore register state }
  9319. RestoreUsedRegs(TempTracking);
  9320. ReleaseUsedRegs(TempTracking);
  9321. Result := FuncMov2Func(p, hp1);
  9322. Exit;
  9323. end;
  9324. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9325. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9326. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9327. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9328. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9329. begin
  9330. { Change:
  9331. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9332. addl/q $x,%reg2 subl/q $x,%reg2
  9333. To:
  9334. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9335. }
  9336. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9337. { be lazy, checking separately for sub would be slightly better }
  9338. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9339. begin
  9340. TransferUsedRegs(TmpUsedRegs);
  9341. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9342. if TryMovArith2Lea(hp1) then
  9343. begin
  9344. Result := True;
  9345. Exit;
  9346. end
  9347. end
  9348. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9349. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9350. { Same as above, but also adds or subtracts to %reg2 in between.
  9351. It's still valid as long as the flags aren't in use }
  9352. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9353. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9354. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9355. { be lazy, checking separately for sub would be slightly better }
  9356. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9357. begin
  9358. TransferUsedRegs(TmpUsedRegs);
  9359. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9360. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9361. if TryMovArith2Lea(hp2) then
  9362. begin
  9363. Result := True;
  9364. Exit;
  9365. end;
  9366. end;
  9367. end;
  9368. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9369. {$ifdef x86_64}
  9370. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9371. {$else x86_64}
  9372. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9373. {$endif x86_64}
  9374. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9375. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9376. { mov reg1, reg2 mov reg1, reg2
  9377. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9378. begin
  9379. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9380. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9381. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9382. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9383. TransferUsedRegs(TmpUsedRegs);
  9384. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9385. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9386. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9387. then
  9388. begin
  9389. RemoveCurrentP(p, hp1);
  9390. Result:=true;
  9391. end;
  9392. Exit;
  9393. end;
  9394. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9395. IsXCHGAcceptable and
  9396. { XCHG doesn't support 8-bit registers }
  9397. (taicpu(p).opsize <> S_B) and
  9398. MatchInstruction(hp1, A_MOV, []) and
  9399. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9400. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9401. GetNextInstruction(hp1, hp2) and
  9402. MatchInstruction(hp2, A_MOV, []) and
  9403. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9404. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9405. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9406. begin
  9407. { mov %reg1,%reg2
  9408. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9409. mov %reg2,%reg3
  9410. (%reg2 not used afterwards)
  9411. Note that xchg takes 3 cycles to execute, and generally mov's take
  9412. only one cycle apiece, but the first two mov's can be executed in
  9413. parallel, only taking 2 cycles overall. Older processors should
  9414. therefore only optimise for size. [Kit]
  9415. }
  9416. TransferUsedRegs(TmpUsedRegs);
  9417. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9418. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9419. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9420. begin
  9421. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9422. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9423. taicpu(hp1).opcode := A_XCHG;
  9424. RemoveCurrentP(p, hp1);
  9425. RemoveInstruction(hp2);
  9426. Result := True;
  9427. Exit;
  9428. end;
  9429. end;
  9430. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9431. MatchInstruction(hp1, A_SAR, []) then
  9432. begin
  9433. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9434. begin
  9435. { the use of %edx also covers the opsize being S_L }
  9436. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9437. begin
  9438. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9439. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9440. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9441. begin
  9442. { Change:
  9443. movl %eax,%edx
  9444. sarl $31,%edx
  9445. To:
  9446. cltd
  9447. }
  9448. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9449. RemoveInstruction(hp1);
  9450. taicpu(p).opcode := A_CDQ;
  9451. taicpu(p).opsize := S_NO;
  9452. taicpu(p).clearop(1);
  9453. taicpu(p).clearop(0);
  9454. taicpu(p).ops:=0;
  9455. Result := True;
  9456. Exit;
  9457. end
  9458. else if (cs_opt_size in current_settings.optimizerswitches) and
  9459. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9460. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9461. begin
  9462. { Change:
  9463. movl %edx,%eax
  9464. sarl $31,%edx
  9465. To:
  9466. movl %edx,%eax
  9467. cltd
  9468. Note that this creates a dependency between the two instructions,
  9469. so only perform if optimising for size.
  9470. }
  9471. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9472. taicpu(hp1).opcode := A_CDQ;
  9473. taicpu(hp1).opsize := S_NO;
  9474. taicpu(hp1).clearop(1);
  9475. taicpu(hp1).clearop(0);
  9476. taicpu(hp1).ops:=0;
  9477. Include(OptsToCheck, aoc_ForceNewIteration);
  9478. Exit;
  9479. end;
  9480. {$ifndef x86_64}
  9481. end
  9482. { Don't bother if CMOV is supported, because a more optimal
  9483. sequence would have been generated for the Abs() intrinsic }
  9484. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9485. { the use of %eax also covers the opsize being S_L }
  9486. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9487. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9488. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9489. GetNextInstruction(hp1, hp2) and
  9490. MatchInstruction(hp2, A_XOR, [S_L]) and
  9491. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9492. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9493. GetNextInstruction(hp2, hp3) and
  9494. MatchInstruction(hp3, A_SUB, [S_L]) and
  9495. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9496. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9497. begin
  9498. { Change:
  9499. movl %eax,%edx
  9500. sarl $31,%eax
  9501. xorl %eax,%edx
  9502. subl %eax,%edx
  9503. (Instruction that uses %edx)
  9504. (%eax deallocated)
  9505. (%edx deallocated)
  9506. To:
  9507. cltd
  9508. xorl %edx,%eax <-- Note the registers have swapped
  9509. subl %edx,%eax
  9510. (Instruction that uses %eax) <-- %eax rather than %edx
  9511. }
  9512. TransferUsedRegs(TmpUsedRegs);
  9513. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9514. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9515. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9516. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9517. begin
  9518. if GetNextInstruction(hp3, hp4) and
  9519. not RegModifiedByInstruction(NR_EDX, hp4) and
  9520. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9521. begin
  9522. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9523. taicpu(p).opcode := A_CDQ;
  9524. taicpu(p).clearop(1);
  9525. taicpu(p).clearop(0);
  9526. taicpu(p).ops:=0;
  9527. RemoveInstruction(hp1);
  9528. taicpu(hp2).loadreg(0, NR_EDX);
  9529. taicpu(hp2).loadreg(1, NR_EAX);
  9530. taicpu(hp3).loadreg(0, NR_EDX);
  9531. taicpu(hp3).loadreg(1, NR_EAX);
  9532. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9533. { Convert references in the following instruction (hp4) from %edx to %eax }
  9534. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9535. with taicpu(hp4).oper[OperIdx]^ do
  9536. case typ of
  9537. top_reg:
  9538. if getsupreg(reg) = RS_EDX then
  9539. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9540. top_ref:
  9541. begin
  9542. if getsupreg(reg) = RS_EDX then
  9543. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9544. if getsupreg(reg) = RS_EDX then
  9545. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9546. end;
  9547. else
  9548. ;
  9549. end;
  9550. Result := True;
  9551. Exit;
  9552. end;
  9553. end;
  9554. {$else x86_64}
  9555. end;
  9556. end
  9557. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9558. { the use of %rdx also covers the opsize being S_Q }
  9559. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9560. begin
  9561. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9562. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9563. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9564. begin
  9565. { Change:
  9566. movq %rax,%rdx
  9567. sarq $63,%rdx
  9568. To:
  9569. cqto
  9570. }
  9571. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9572. RemoveInstruction(hp1);
  9573. taicpu(p).opcode := A_CQO;
  9574. taicpu(p).opsize := S_NO;
  9575. taicpu(p).clearop(1);
  9576. taicpu(p).clearop(0);
  9577. taicpu(p).ops:=0;
  9578. Result := True;
  9579. Exit;
  9580. end
  9581. else if (cs_opt_size in current_settings.optimizerswitches) and
  9582. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9583. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9584. begin
  9585. { Change:
  9586. movq %rdx,%rax
  9587. sarq $63,%rdx
  9588. To:
  9589. movq %rdx,%rax
  9590. cqto
  9591. Note that this creates a dependency between the two instructions,
  9592. so only perform if optimising for size.
  9593. }
  9594. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9595. taicpu(hp1).opcode := A_CQO;
  9596. taicpu(hp1).opsize := S_NO;
  9597. taicpu(hp1).clearop(1);
  9598. taicpu(hp1).clearop(0);
  9599. taicpu(hp1).ops:=0;
  9600. Include(OptsToCheck, aoc_ForceNewIteration);
  9601. Exit;
  9602. {$endif x86_64}
  9603. end;
  9604. end;
  9605. end;
  9606. if MatchInstruction(hp1, A_MOV, []) and
  9607. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9608. { Though "GetNextInstruction" could be factored out, along with
  9609. the instructions that depend on hp2, it is an expensive call that
  9610. should be delayed for as long as possible, hence we do cheaper
  9611. checks first that are likely to be False. [Kit] }
  9612. begin
  9613. if (
  9614. (
  9615. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9616. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9617. (
  9618. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9619. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9620. )
  9621. ) or
  9622. (
  9623. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9624. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9625. (
  9626. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9627. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9628. )
  9629. )
  9630. ) and
  9631. GetNextInstruction(hp1, hp2) and
  9632. MatchInstruction(hp2, A_SAR, []) and
  9633. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9634. begin
  9635. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9636. begin
  9637. { Change:
  9638. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9639. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9640. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9641. To:
  9642. movl r/m,%eax <- Note the change in register
  9643. cltd
  9644. }
  9645. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9646. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9647. taicpu(p).loadreg(1, NR_EAX);
  9648. taicpu(hp1).opcode := A_CDQ;
  9649. taicpu(hp1).clearop(1);
  9650. taicpu(hp1).clearop(0);
  9651. taicpu(hp1).ops:=0;
  9652. RemoveInstruction(hp2);
  9653. Include(OptsToCheck, aoc_ForceNewIteration);
  9654. (*
  9655. {$ifdef x86_64}
  9656. end
  9657. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9658. { This code sequence does not get generated - however it might become useful
  9659. if and when 128-bit signed integer types make an appearance, so the code
  9660. is kept here for when it is eventually needed. [Kit] }
  9661. (
  9662. (
  9663. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9664. (
  9665. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9666. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9667. )
  9668. ) or
  9669. (
  9670. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9671. (
  9672. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9673. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9674. )
  9675. )
  9676. ) and
  9677. GetNextInstruction(hp1, hp2) and
  9678. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9679. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9680. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9681. begin
  9682. { Change:
  9683. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9684. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9685. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9686. To:
  9687. movq r/m,%rax <- Note the change in register
  9688. cqto
  9689. }
  9690. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9691. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9692. taicpu(p).loadreg(1, NR_RAX);
  9693. taicpu(hp1).opcode := A_CQO;
  9694. taicpu(hp1).clearop(1);
  9695. taicpu(hp1).clearop(0);
  9696. taicpu(hp1).ops:=0;
  9697. RemoveInstruction(hp2);
  9698. Include(OptsToCheck, aoc_ForceNewIteration);
  9699. {$endif x86_64}
  9700. *)
  9701. end;
  9702. end;
  9703. {$ifdef x86_64}
  9704. end;
  9705. if (taicpu(p).opsize = S_L) and
  9706. (taicpu(p).oper[1]^.typ = top_reg) and
  9707. (
  9708. MatchInstruction(hp1, A_MOV,[]) and
  9709. (taicpu(hp1).opsize = S_L) and
  9710. (taicpu(hp1).oper[1]^.typ = top_reg)
  9711. ) and (
  9712. GetNextInstruction(hp1, hp2) and
  9713. (tai(hp2).typ=ait_instruction) and
  9714. (taicpu(hp2).opsize = S_Q) and
  9715. (
  9716. (
  9717. MatchInstruction(hp2, A_ADD,[]) and
  9718. (taicpu(hp2).opsize = S_Q) and
  9719. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9720. (
  9721. (
  9722. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9723. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9724. ) or (
  9725. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9726. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9727. )
  9728. )
  9729. ) or (
  9730. MatchInstruction(hp2, A_LEA,[]) and
  9731. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9732. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9733. (
  9734. (
  9735. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9736. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9737. ) or (
  9738. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9739. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9740. )
  9741. ) and (
  9742. (
  9743. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9744. ) or (
  9745. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9746. )
  9747. )
  9748. )
  9749. )
  9750. ) and (
  9751. GetNextInstruction(hp2, hp3) and
  9752. MatchInstruction(hp3, A_SHR,[]) and
  9753. (taicpu(hp3).opsize = S_Q) and
  9754. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9755. (taicpu(hp3).oper[0]^.val = 1) and
  9756. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9757. ) then
  9758. begin
  9759. { Change movl x, reg1d movl x, reg1d
  9760. movl y, reg2d movl y, reg2d
  9761. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9762. shrq $1, reg1q shrq $1, reg1q
  9763. ( reg1d and reg2d can be switched around in the first two instructions )
  9764. To movl x, reg1d
  9765. addl y, reg1d
  9766. rcrl $1, reg1d
  9767. This corresponds to the common expression (x + y) shr 1, where
  9768. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9769. smaller code, but won't account for x + y causing an overflow). [Kit]
  9770. }
  9771. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9772. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9773. begin
  9774. { Change first MOV command to have the same register as the final output }
  9775. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  9776. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  9777. Result := True;
  9778. end
  9779. else
  9780. begin
  9781. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9782. Include(OptsToCheck, aoc_ForceNewIteration);
  9783. end;
  9784. { Change second MOV command to an ADD command. This is easier than
  9785. converting the existing command because it means we don't have to
  9786. touch 'y', which might be a complicated reference, and also the
  9787. fact that the third command might either be ADD or LEA. [Kit] }
  9788. taicpu(hp1).opcode := A_ADD;
  9789. { Delete old ADD/LEA instruction }
  9790. RemoveInstruction(hp2);
  9791. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9792. taicpu(hp3).opcode := A_RCR;
  9793. taicpu(hp3).changeopsize(S_L);
  9794. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9795. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  9796. called, so FuncMov2Func below is safe to call }
  9797. {$endif x86_64}
  9798. end;
  9799. if FuncMov2Func(p, hp1) then
  9800. begin
  9801. Result := True;
  9802. Exit;
  9803. end;
  9804. end;
  9805. {$push}
  9806. {$q-}{$r-}
  9807. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9808. var
  9809. ThisReg: TRegister;
  9810. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9811. TargetSubReg: TSubRegister;
  9812. hp1, hp2: tai;
  9813. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9814. { Store list of found instructions so we don't have to call
  9815. GetNextInstructionUsingReg multiple times }
  9816. InstrList: array of taicpu;
  9817. InstrMax, Index: Integer;
  9818. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9819. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9820. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9821. WorkingValue: TCgInt;
  9822. PreMessage: string;
  9823. { Data flow analysis }
  9824. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9825. BitwiseOnly, OrXorUsed,
  9826. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9827. function CheckOverflowConditions: Boolean;
  9828. begin
  9829. Result := True;
  9830. if (TestValSignedMax > SignedUpperLimit) then
  9831. UpperSignedOverflow := True;
  9832. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9833. LowerSignedOverflow := True;
  9834. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9835. LowerUnsignedOverflow := True;
  9836. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9837. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9838. begin
  9839. { Absolute overflow }
  9840. Result := False;
  9841. Exit;
  9842. end;
  9843. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9844. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9845. ShiftDownOverflow := True;
  9846. if (TestValMin < 0) or (TestValMax < 0) then
  9847. begin
  9848. LowerUnsignedOverflow := True;
  9849. UpperUnsignedOverflow := True;
  9850. end;
  9851. end;
  9852. function AdjustInitialLoadAndSize: Boolean;
  9853. begin
  9854. Result := False;
  9855. if not p_removed then
  9856. begin
  9857. if TargetSize = MinSize then
  9858. begin
  9859. { Convert the input MOVZX to a MOV }
  9860. if (taicpu(p).oper[0]^.typ = top_reg) and
  9861. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9862. begin
  9863. { Or remove it completely! }
  9864. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9865. RemoveCurrentP(p);
  9866. p_removed := True;
  9867. end
  9868. else
  9869. begin
  9870. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9871. taicpu(p).opcode := A_MOV;
  9872. taicpu(p).oper[1]^.reg := ThisReg;
  9873. taicpu(p).opsize := TargetSize;
  9874. end;
  9875. Result := True;
  9876. end
  9877. else if TargetSize <> MaxSize then
  9878. begin
  9879. case MaxSize of
  9880. S_L:
  9881. if TargetSize = S_W then
  9882. begin
  9883. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9884. taicpu(p).opsize := S_BW;
  9885. taicpu(p).oper[1]^.reg := ThisReg;
  9886. Result := True;
  9887. end
  9888. else
  9889. InternalError(2020112341);
  9890. S_W:
  9891. if TargetSize = S_L then
  9892. begin
  9893. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9894. taicpu(p).opsize := S_BL;
  9895. taicpu(p).oper[1]^.reg := ThisReg;
  9896. Result := True;
  9897. end
  9898. else
  9899. InternalError(2020112342);
  9900. else
  9901. ;
  9902. end;
  9903. end
  9904. else if not hp1_removed and not RegInUse then
  9905. begin
  9906. { If we have something like:
  9907. movzbl (oper),%regd
  9908. add x, %regd
  9909. movzbl %regb, %regd
  9910. We can reduce the register size to the input of the final
  9911. movzbl instruction. Overflows won't have any effect.
  9912. }
  9913. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9914. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9915. begin
  9916. TargetSize := S_B;
  9917. setsubreg(ThisReg, R_SUBL);
  9918. Result := True;
  9919. end
  9920. else if (taicpu(p).opsize = S_WL) and
  9921. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9922. begin
  9923. TargetSize := S_W;
  9924. setsubreg(ThisReg, R_SUBW);
  9925. Result := True;
  9926. end;
  9927. if Result then
  9928. begin
  9929. { Convert the input MOVZX to a MOV }
  9930. if (taicpu(p).oper[0]^.typ = top_reg) and
  9931. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9932. begin
  9933. { Or remove it completely! }
  9934. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9935. RemoveCurrentP(p);
  9936. p_removed := True;
  9937. end
  9938. else
  9939. begin
  9940. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9941. taicpu(p).opcode := A_MOV;
  9942. taicpu(p).oper[1]^.reg := ThisReg;
  9943. taicpu(p).opsize := TargetSize;
  9944. end;
  9945. end;
  9946. end;
  9947. end;
  9948. end;
  9949. procedure AdjustFinalLoad;
  9950. begin
  9951. if not LowerUnsignedOverflow then
  9952. begin
  9953. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9954. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9955. begin
  9956. { Convert the output MOVZX to a MOV }
  9957. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9958. begin
  9959. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9960. if (MinSize = S_B) or
  9961. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9962. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9963. begin
  9964. { Remove it completely! }
  9965. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9966. { Be careful; if p = hp1 and p was also removed, p
  9967. will become a dangling pointer }
  9968. if p = hp1 then
  9969. begin
  9970. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9971. p_removed := True;
  9972. end
  9973. else
  9974. RemoveInstruction(hp1);
  9975. hp1_removed := True;
  9976. end;
  9977. end
  9978. else
  9979. begin
  9980. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9981. taicpu(hp1).opcode := A_MOV;
  9982. taicpu(hp1).oper[0]^.reg := ThisReg;
  9983. taicpu(hp1).opsize := TargetSize;
  9984. end;
  9985. end
  9986. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9987. begin
  9988. { Need to change the size of the output }
  9989. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9990. taicpu(hp1).oper[0]^.reg := ThisReg;
  9991. taicpu(hp1).opsize := S_BL;
  9992. end;
  9993. end;
  9994. end;
  9995. function CompressInstructions: Boolean;
  9996. var
  9997. LocalIndex: Integer;
  9998. begin
  9999. Result := False;
  10000. { The objective here is to try to find a combination that
  10001. removes one of the MOV/Z instructions. }
  10002. if (
  10003. (taicpu(p).oper[0]^.typ <> top_reg) or
  10004. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  10005. ) and
  10006. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10007. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10008. begin
  10009. { Make a preference to remove the second MOVZX instruction }
  10010. case taicpu(hp1).opsize of
  10011. S_BL, S_WL:
  10012. begin
  10013. TargetSize := S_L;
  10014. TargetSubReg := R_SUBD;
  10015. end;
  10016. S_BW:
  10017. begin
  10018. TargetSize := S_W;
  10019. TargetSubReg := R_SUBW;
  10020. end;
  10021. else
  10022. InternalError(2020112302);
  10023. end;
  10024. end
  10025. else
  10026. begin
  10027. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10028. begin
  10029. { Exceeded lower bound but not upper bound }
  10030. TargetSize := MaxSize;
  10031. end
  10032. else if not LowerUnsignedOverflow then
  10033. begin
  10034. { Size didn't exceed lower bound }
  10035. TargetSize := MinSize;
  10036. end
  10037. else
  10038. Exit;
  10039. end;
  10040. case TargetSize of
  10041. S_B:
  10042. TargetSubReg := R_SUBL;
  10043. S_W:
  10044. TargetSubReg := R_SUBW;
  10045. S_L:
  10046. TargetSubReg := R_SUBD;
  10047. else
  10048. InternalError(2020112350);
  10049. end;
  10050. { Update the register to its new size }
  10051. setsubreg(ThisReg, TargetSubReg);
  10052. RegInUse := False;
  10053. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10054. begin
  10055. { Check to see if the active register is used afterwards;
  10056. if not, we can change it and make a saving. }
  10057. TransferUsedRegs(TmpUsedRegs);
  10058. { The target register may be marked as in use to cross
  10059. a jump to a distant label, so exclude it }
  10060. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  10061. hp2 := p;
  10062. repeat
  10063. { Explicitly check for the excluded register (don't include the first
  10064. instruction as it may be reading from here }
  10065. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  10066. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  10067. begin
  10068. RegInUse := True;
  10069. Break;
  10070. end;
  10071. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  10072. if not GetNextInstruction(hp2, hp2) then
  10073. InternalError(2020112340);
  10074. until (hp2 = hp1);
  10075. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10076. { We might still be able to get away with this }
  10077. RegInUse := not
  10078. (
  10079. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  10080. (hp2.typ = ait_instruction) and
  10081. (
  10082. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10083. instruction that doesn't actually contain ThisReg }
  10084. (cs_opt_level3 in current_settings.optimizerswitches) or
  10085. RegInInstruction(ThisReg, hp2)
  10086. ) and
  10087. RegLoadedWithNewValue(ThisReg, hp2)
  10088. );
  10089. if not RegInUse then
  10090. begin
  10091. { Force the register size to the same as this instruction so it can be removed}
  10092. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  10093. begin
  10094. TargetSize := S_L;
  10095. TargetSubReg := R_SUBD;
  10096. end
  10097. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  10098. begin
  10099. TargetSize := S_W;
  10100. TargetSubReg := R_SUBW;
  10101. end;
  10102. ThisReg := taicpu(hp1).oper[1]^.reg;
  10103. setsubreg(ThisReg, TargetSubReg);
  10104. RegChanged := True;
  10105. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  10106. TransferUsedRegs(TmpUsedRegs);
  10107. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  10108. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  10109. if p = hp1 then
  10110. begin
  10111. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10112. p_removed := True;
  10113. end
  10114. else
  10115. RemoveInstruction(hp1);
  10116. hp1_removed := True;
  10117. { Instruction will become "mov %reg,%reg" }
  10118. if not p_removed and (taicpu(p).opcode = A_MOV) and
  10119. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  10120. begin
  10121. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  10122. RemoveCurrentP(p);
  10123. p_removed := True;
  10124. end
  10125. else
  10126. taicpu(p).oper[1]^.reg := ThisReg;
  10127. Result := True;
  10128. end
  10129. else
  10130. begin
  10131. if TargetSize <> MaxSize then
  10132. begin
  10133. { Since the register is in use, we have to force it to
  10134. MaxSize otherwise part of it may become undefined later on }
  10135. TargetSize := MaxSize;
  10136. case TargetSize of
  10137. S_B:
  10138. TargetSubReg := R_SUBL;
  10139. S_W:
  10140. TargetSubReg := R_SUBW;
  10141. S_L:
  10142. TargetSubReg := R_SUBD;
  10143. else
  10144. InternalError(2020112351);
  10145. end;
  10146. setsubreg(ThisReg, TargetSubReg);
  10147. end;
  10148. AdjustFinalLoad;
  10149. end;
  10150. end
  10151. else
  10152. AdjustFinalLoad;
  10153. Result := AdjustInitialLoadAndSize or Result;
  10154. { Now go through every instruction we found and change the
  10155. size. If TargetSize = MaxSize, then almost no changes are
  10156. needed and Result can remain False if it hasn't been set
  10157. yet.
  10158. If RegChanged is True, then the register requires changing
  10159. and so the point about TargetSize = MaxSize doesn't apply. }
  10160. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10161. begin
  10162. for LocalIndex := 0 to InstrMax do
  10163. begin
  10164. { If p_removed is true, then the original MOV/Z was removed
  10165. and removing the AND instruction may not be safe if it
  10166. appears first }
  10167. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10168. InternalError(2020112310);
  10169. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10170. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10171. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10172. InstrList[LocalIndex].opsize := TargetSize;
  10173. end;
  10174. Result := True;
  10175. end;
  10176. end;
  10177. begin
  10178. Result := False;
  10179. p_removed := False;
  10180. hp1_removed := False;
  10181. ThisReg := taicpu(p).oper[1]^.reg;
  10182. { Check for:
  10183. movs/z ###,%ecx (or %cx or %rcx)
  10184. ...
  10185. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10186. (dealloc %ecx)
  10187. Change to:
  10188. mov ###,%cl (if ### = %cl, then remove completely)
  10189. ...
  10190. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10191. }
  10192. if (getsupreg(ThisReg) = RS_ECX) and
  10193. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10194. (hp1.typ = ait_instruction) and
  10195. (
  10196. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10197. instruction that doesn't actually contain ECX }
  10198. (cs_opt_level3 in current_settings.optimizerswitches) or
  10199. RegInInstruction(NR_ECX, hp1) or
  10200. (
  10201. { It's common for the shift/rotate's read/write register to be
  10202. initialised in between, so under -O2 and under, search ahead
  10203. one more instruction
  10204. }
  10205. GetNextInstruction(hp1, hp1) and
  10206. (hp1.typ = ait_instruction) and
  10207. RegInInstruction(NR_ECX, hp1)
  10208. )
  10209. ) and
  10210. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10211. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10212. begin
  10213. TransferUsedRegs(TmpUsedRegs);
  10214. hp2 := p;
  10215. repeat
  10216. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10217. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10218. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10219. begin
  10220. case taicpu(p).opsize of
  10221. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10222. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10223. begin
  10224. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10225. RemoveCurrentP(p);
  10226. end
  10227. else
  10228. begin
  10229. taicpu(p).opcode := A_MOV;
  10230. taicpu(p).opsize := S_B;
  10231. taicpu(p).oper[1]^.reg := NR_CL;
  10232. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10233. end;
  10234. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10235. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10236. begin
  10237. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10238. RemoveCurrentP(p);
  10239. end
  10240. else
  10241. begin
  10242. taicpu(p).opcode := A_MOV;
  10243. taicpu(p).opsize := S_W;
  10244. taicpu(p).oper[1]^.reg := NR_CX;
  10245. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10246. end;
  10247. {$ifdef x86_64}
  10248. S_LQ:
  10249. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10250. begin
  10251. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10252. RemoveCurrentP(p);
  10253. end
  10254. else
  10255. begin
  10256. taicpu(p).opcode := A_MOV;
  10257. taicpu(p).opsize := S_L;
  10258. taicpu(p).oper[1]^.reg := NR_ECX;
  10259. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10260. end;
  10261. {$endif x86_64}
  10262. else
  10263. InternalError(2021120401);
  10264. end;
  10265. Result := True;
  10266. Exit;
  10267. end;
  10268. end;
  10269. { This is anything but quick! }
  10270. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10271. Exit;
  10272. SetLength(InstrList, 0);
  10273. InstrMax := -1;
  10274. case taicpu(p).opsize of
  10275. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10276. begin
  10277. {$if defined(i386) or defined(i8086)}
  10278. { If the target size is 8-bit, make sure we can actually encode it }
  10279. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10280. Exit;
  10281. {$endif i386 or i8086}
  10282. LowerLimit := $FF;
  10283. SignedLowerLimit := $7F;
  10284. SignedLowerLimitBottom := -128;
  10285. MinSize := S_B;
  10286. if taicpu(p).opsize = S_BW then
  10287. begin
  10288. MaxSize := S_W;
  10289. UpperLimit := $FFFF;
  10290. SignedUpperLimit := $7FFF;
  10291. SignedUpperLimitBottom := -32768;
  10292. end
  10293. else
  10294. begin
  10295. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10296. MaxSize := S_L;
  10297. UpperLimit := $FFFFFFFF;
  10298. SignedUpperLimit := $7FFFFFFF;
  10299. SignedUpperLimitBottom := -2147483648;
  10300. end;
  10301. end;
  10302. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10303. begin
  10304. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10305. LowerLimit := $FFFF;
  10306. SignedLowerLimit := $7FFF;
  10307. SignedLowerLimitBottom := -32768;
  10308. UpperLimit := $FFFFFFFF;
  10309. SignedUpperLimit := $7FFFFFFF;
  10310. SignedUpperLimitBottom := -2147483648;
  10311. MinSize := S_W;
  10312. MaxSize := S_L;
  10313. end;
  10314. {$ifdef x86_64}
  10315. S_LQ:
  10316. begin
  10317. { Both the lower and upper limits are set to 32-bit. If a limit
  10318. is breached, then optimisation is impossible }
  10319. LowerLimit := $FFFFFFFF;
  10320. SignedLowerLimit := $7FFFFFFF;
  10321. SignedLowerLimitBottom := -2147483648;
  10322. UpperLimit := $FFFFFFFF;
  10323. SignedUpperLimit := $7FFFFFFF;
  10324. SignedUpperLimitBottom := -2147483648;
  10325. MinSize := S_L;
  10326. MaxSize := S_L;
  10327. end;
  10328. {$endif x86_64}
  10329. else
  10330. InternalError(2020112301);
  10331. end;
  10332. TestValMin := 0;
  10333. TestValMax := LowerLimit;
  10334. TestValSignedMax := SignedLowerLimit;
  10335. TryShiftDownLimit := LowerLimit;
  10336. TryShiftDown := S_NO;
  10337. ShiftDownOverflow := False;
  10338. RegChanged := False;
  10339. BitwiseOnly := True;
  10340. OrXorUsed := False;
  10341. UpperSignedOverflow := False;
  10342. LowerSignedOverflow := False;
  10343. UpperUnsignedOverflow := False;
  10344. LowerUnsignedOverflow := False;
  10345. hp1 := p;
  10346. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10347. (hp1.typ = ait_instruction) and
  10348. (
  10349. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10350. instruction that doesn't actually contain ThisReg }
  10351. (cs_opt_level3 in current_settings.optimizerswitches) or
  10352. { This allows this Movx optimisation to work through the SETcc instructions
  10353. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10354. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10355. skip over these SETcc instructions). }
  10356. (taicpu(hp1).opcode = A_SETcc) or
  10357. RegInInstruction(ThisReg, hp1)
  10358. ) do
  10359. begin
  10360. case taicpu(hp1).opcode of
  10361. A_INC,A_DEC:
  10362. begin
  10363. { Has to be an exact match on the register }
  10364. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10365. Break;
  10366. if taicpu(hp1).opcode = A_INC then
  10367. begin
  10368. Inc(TestValMin);
  10369. Inc(TestValMax);
  10370. Inc(TestValSignedMax);
  10371. end
  10372. else
  10373. begin
  10374. Dec(TestValMin);
  10375. Dec(TestValMax);
  10376. Dec(TestValSignedMax);
  10377. end;
  10378. end;
  10379. A_TEST, A_CMP:
  10380. begin
  10381. if (
  10382. { Too high a risk of non-linear behaviour that breaks DFA
  10383. here, unless it's cmp $0,%reg, which is equivalent to
  10384. test %reg,%reg }
  10385. OrXorUsed and
  10386. (taicpu(hp1).opcode = A_CMP) and
  10387. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10388. ) or
  10389. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10390. { Has to be an exact match on the register }
  10391. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10392. (
  10393. { Permit "test %reg,%reg" }
  10394. (taicpu(hp1).opcode = A_TEST) and
  10395. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10396. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10397. ) or
  10398. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10399. { Make sure the comparison value is not smaller than the
  10400. smallest allowed signed value for the minimum size (e.g.
  10401. -128 for 8-bit) }
  10402. not (
  10403. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10404. { Is it in the negative range? }
  10405. (
  10406. (taicpu(hp1).oper[0]^.val < 0) and
  10407. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10408. )
  10409. ) then
  10410. Break;
  10411. { Check to see if the active register is used afterwards }
  10412. TransferUsedRegs(TmpUsedRegs);
  10413. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10414. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10415. begin
  10416. { Make sure the comparison or any previous instructions
  10417. hasn't pushed the test values outside of the range of
  10418. MinSize }
  10419. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10420. begin
  10421. { Exceeded lower bound but not upper bound }
  10422. Exit;
  10423. end
  10424. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10425. begin
  10426. { Size didn't exceed lower bound }
  10427. TargetSize := MinSize;
  10428. end
  10429. else
  10430. Break;
  10431. case TargetSize of
  10432. S_B:
  10433. TargetSubReg := R_SUBL;
  10434. S_W:
  10435. TargetSubReg := R_SUBW;
  10436. S_L:
  10437. TargetSubReg := R_SUBD;
  10438. else
  10439. InternalError(2021051002);
  10440. end;
  10441. if TargetSize <> MaxSize then
  10442. begin
  10443. { Update the register to its new size }
  10444. setsubreg(ThisReg, TargetSubReg);
  10445. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10446. taicpu(hp1).oper[1]^.reg := ThisReg;
  10447. taicpu(hp1).opsize := TargetSize;
  10448. { Convert the input MOVZX to a MOV if necessary }
  10449. AdjustInitialLoadAndSize;
  10450. if (InstrMax >= 0) then
  10451. begin
  10452. for Index := 0 to InstrMax do
  10453. begin
  10454. { If p_removed is true, then the original MOV/Z was removed
  10455. and removing the AND instruction may not be safe if it
  10456. appears first }
  10457. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10458. InternalError(2020112311);
  10459. if InstrList[Index].oper[0]^.typ = top_reg then
  10460. InstrList[Index].oper[0]^.reg := ThisReg;
  10461. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10462. InstrList[Index].opsize := MinSize;
  10463. end;
  10464. end;
  10465. Result := True;
  10466. end;
  10467. Exit;
  10468. end;
  10469. end;
  10470. A_SETcc:
  10471. begin
  10472. { This allows this Movx optimisation to work through the SETcc instructions
  10473. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10474. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10475. skip over these SETcc instructions). }
  10476. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10477. { Of course, break out if the current register is used }
  10478. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10479. Break
  10480. else
  10481. { We must use Continue so the instruction doesn't get added
  10482. to InstrList }
  10483. Continue;
  10484. end;
  10485. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10486. begin
  10487. if
  10488. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10489. { Has to be an exact match on the register }
  10490. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10491. (
  10492. (
  10493. (taicpu(hp1).oper[0]^.typ = top_const) and
  10494. (
  10495. (
  10496. (taicpu(hp1).opcode = A_SHL) and
  10497. (
  10498. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10499. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10500. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10501. )
  10502. ) or (
  10503. (taicpu(hp1).opcode <> A_SHL) and
  10504. (
  10505. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10506. { Is it in the negative range? }
  10507. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10508. )
  10509. )
  10510. )
  10511. ) or (
  10512. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10513. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10514. )
  10515. ) then
  10516. Break;
  10517. { Only process OR and XOR if there are only bitwise operations,
  10518. since otherwise they can too easily fool the data flow
  10519. analysis (they can cause non-linear behaviour) }
  10520. case taicpu(hp1).opcode of
  10521. A_ADD:
  10522. begin
  10523. if OrXorUsed then
  10524. { Too high a risk of non-linear behaviour that breaks DFA here }
  10525. Break
  10526. else
  10527. BitwiseOnly := False;
  10528. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10529. begin
  10530. TestValMin := TestValMin * 2;
  10531. TestValMax := TestValMax * 2;
  10532. TestValSignedMax := TestValSignedMax * 2;
  10533. end
  10534. else
  10535. begin
  10536. WorkingValue := taicpu(hp1).oper[0]^.val;
  10537. TestValMin := TestValMin + WorkingValue;
  10538. TestValMax := TestValMax + WorkingValue;
  10539. TestValSignedMax := TestValSignedMax + WorkingValue;
  10540. end;
  10541. end;
  10542. A_SUB:
  10543. begin
  10544. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10545. begin
  10546. TestValMin := 0;
  10547. TestValMax := 0;
  10548. TestValSignedMax := 0;
  10549. end
  10550. else
  10551. begin
  10552. if OrXorUsed then
  10553. { Too high a risk of non-linear behaviour that breaks DFA here }
  10554. Break
  10555. else
  10556. BitwiseOnly := False;
  10557. WorkingValue := taicpu(hp1).oper[0]^.val;
  10558. TestValMin := TestValMin - WorkingValue;
  10559. TestValMax := TestValMax - WorkingValue;
  10560. TestValSignedMax := TestValSignedMax - WorkingValue;
  10561. end;
  10562. end;
  10563. A_AND:
  10564. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10565. begin
  10566. { we might be able to go smaller if AND appears first }
  10567. if InstrMax = -1 then
  10568. case MinSize of
  10569. S_B:
  10570. ;
  10571. S_W:
  10572. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10573. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10574. begin
  10575. TryShiftDown := S_B;
  10576. TryShiftDownLimit := $FF;
  10577. end;
  10578. S_L:
  10579. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10580. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10581. begin
  10582. TryShiftDown := S_B;
  10583. TryShiftDownLimit := $FF;
  10584. end
  10585. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10586. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10587. begin
  10588. TryShiftDown := S_W;
  10589. TryShiftDownLimit := $FFFF;
  10590. end;
  10591. else
  10592. InternalError(2020112320);
  10593. end;
  10594. WorkingValue := taicpu(hp1).oper[0]^.val;
  10595. TestValMin := TestValMin and WorkingValue;
  10596. TestValMax := TestValMax and WorkingValue;
  10597. TestValSignedMax := TestValSignedMax and WorkingValue;
  10598. end;
  10599. A_OR:
  10600. begin
  10601. if not BitwiseOnly then
  10602. Break;
  10603. OrXorUsed := True;
  10604. WorkingValue := taicpu(hp1).oper[0]^.val;
  10605. TestValMin := TestValMin or WorkingValue;
  10606. TestValMax := TestValMax or WorkingValue;
  10607. TestValSignedMax := TestValSignedMax or WorkingValue;
  10608. end;
  10609. A_XOR:
  10610. begin
  10611. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10612. begin
  10613. TestValMin := 0;
  10614. TestValMax := 0;
  10615. TestValSignedMax := 0;
  10616. end
  10617. else
  10618. begin
  10619. if not BitwiseOnly then
  10620. Break;
  10621. OrXorUsed := True;
  10622. WorkingValue := taicpu(hp1).oper[0]^.val;
  10623. TestValMin := TestValMin xor WorkingValue;
  10624. TestValMax := TestValMax xor WorkingValue;
  10625. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10626. end;
  10627. end;
  10628. A_SHL:
  10629. begin
  10630. BitwiseOnly := False;
  10631. WorkingValue := taicpu(hp1).oper[0]^.val;
  10632. TestValMin := TestValMin shl WorkingValue;
  10633. TestValMax := TestValMax shl WorkingValue;
  10634. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10635. end;
  10636. A_SHR,
  10637. { The first instruction was MOVZX, so the value won't be negative }
  10638. A_SAR:
  10639. begin
  10640. if InstrMax <> -1 then
  10641. BitwiseOnly := False
  10642. else
  10643. { we might be able to go smaller if SHR appears first }
  10644. case MinSize of
  10645. S_B:
  10646. ;
  10647. S_W:
  10648. if (taicpu(hp1).oper[0]^.val >= 8) then
  10649. begin
  10650. TryShiftDown := S_B;
  10651. TryShiftDownLimit := $FF;
  10652. TryShiftDownSignedLimit := $7F;
  10653. TryShiftDownSignedLimitLower := -128;
  10654. end;
  10655. S_L:
  10656. if (taicpu(hp1).oper[0]^.val >= 24) then
  10657. begin
  10658. TryShiftDown := S_B;
  10659. TryShiftDownLimit := $FF;
  10660. TryShiftDownSignedLimit := $7F;
  10661. TryShiftDownSignedLimitLower := -128;
  10662. end
  10663. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10664. begin
  10665. TryShiftDown := S_W;
  10666. TryShiftDownLimit := $FFFF;
  10667. TryShiftDownSignedLimit := $7FFF;
  10668. TryShiftDownSignedLimitLower := -32768;
  10669. end;
  10670. else
  10671. InternalError(2020112321);
  10672. end;
  10673. WorkingValue := taicpu(hp1).oper[0]^.val;
  10674. if taicpu(hp1).opcode = A_SAR then
  10675. begin
  10676. TestValMin := SarInt64(TestValMin, WorkingValue);
  10677. TestValMax := SarInt64(TestValMax, WorkingValue);
  10678. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10679. end
  10680. else
  10681. begin
  10682. TestValMin := TestValMin shr WorkingValue;
  10683. TestValMax := TestValMax shr WorkingValue;
  10684. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10685. end;
  10686. end;
  10687. else
  10688. InternalError(2020112303);
  10689. end;
  10690. end;
  10691. (*
  10692. A_IMUL:
  10693. case taicpu(hp1).ops of
  10694. 2:
  10695. begin
  10696. if not MatchOpType(hp1, top_reg, top_reg) or
  10697. { Has to be an exact match on the register }
  10698. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10699. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10700. Break;
  10701. TestValMin := TestValMin * TestValMin;
  10702. TestValMax := TestValMax * TestValMax;
  10703. TestValSignedMax := TestValSignedMax * TestValMax;
  10704. end;
  10705. 3:
  10706. begin
  10707. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10708. { Has to be an exact match on the register }
  10709. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10710. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10711. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10712. { Is it in the negative range? }
  10713. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10714. Break;
  10715. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10716. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10717. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10718. end;
  10719. else
  10720. Break;
  10721. end;
  10722. A_IDIV:
  10723. case taicpu(hp1).ops of
  10724. 3:
  10725. begin
  10726. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10727. { Has to be an exact match on the register }
  10728. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10729. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10730. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10731. { Is it in the negative range? }
  10732. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10733. Break;
  10734. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10735. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10736. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10737. end;
  10738. else
  10739. Break;
  10740. end;
  10741. *)
  10742. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10743. begin
  10744. { If there are no instructions in between, then we might be able to make a saving }
  10745. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10746. Break;
  10747. { We have something like:
  10748. movzbw %dl,%dx
  10749. ...
  10750. movswl %dx,%edx
  10751. Change the latter to a zero-extension then enter the
  10752. A_MOVZX case branch.
  10753. }
  10754. {$ifdef x86_64}
  10755. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10756. begin
  10757. { this becomes a zero extension from 32-bit to 64-bit, but
  10758. the upper 32 bits are already zero, so just delete the
  10759. instruction }
  10760. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10761. RemoveInstruction(hp1);
  10762. Result := True;
  10763. Exit;
  10764. end
  10765. else
  10766. {$endif x86_64}
  10767. begin
  10768. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10769. taicpu(hp1).opcode := A_MOVZX;
  10770. {$ifdef x86_64}
  10771. case taicpu(hp1).opsize of
  10772. S_BQ:
  10773. begin
  10774. taicpu(hp1).opsize := S_BL;
  10775. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10776. end;
  10777. S_WQ:
  10778. begin
  10779. taicpu(hp1).opsize := S_WL;
  10780. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10781. end;
  10782. S_LQ:
  10783. begin
  10784. taicpu(hp1).opcode := A_MOV;
  10785. taicpu(hp1).opsize := S_L;
  10786. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10787. { In this instance, we need to break out because the
  10788. instruction is no longer MOVZX or MOVSXD }
  10789. Result := True;
  10790. Exit;
  10791. end;
  10792. else
  10793. ;
  10794. end;
  10795. {$endif x86_64}
  10796. Result := CompressInstructions;
  10797. Exit;
  10798. end;
  10799. end;
  10800. A_MOVZX:
  10801. begin
  10802. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10803. Break;
  10804. if (InstrMax = -1) then
  10805. begin
  10806. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10807. begin
  10808. { Optimise around i40003 }
  10809. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10810. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10811. {$ifndef x86_64}
  10812. and (
  10813. (taicpu(p).oper[0]^.typ <> top_reg) or
  10814. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10815. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10816. )
  10817. {$endif not x86_64}
  10818. then
  10819. begin
  10820. if (taicpu(p).oper[0]^.typ = top_reg) then
  10821. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10822. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10823. taicpu(p).opsize := S_BL;
  10824. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10825. RemoveInstruction(hp1);
  10826. Result := True;
  10827. Exit;
  10828. end;
  10829. end
  10830. else
  10831. begin
  10832. { Will return false if the second parameter isn't ThisReg
  10833. (can happen on -O2 and under) }
  10834. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10835. begin
  10836. { The two MOVZX instructions are adjacent, so remove the first one }
  10837. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10838. RemoveCurrentP(p);
  10839. Result := True;
  10840. Exit;
  10841. end;
  10842. Break;
  10843. end;
  10844. end;
  10845. Result := CompressInstructions;
  10846. Exit;
  10847. end;
  10848. else
  10849. { This includes ADC, SBB and IDIV }
  10850. Break;
  10851. end;
  10852. if not CheckOverflowConditions then
  10853. Break;
  10854. { Contains highest index (so instruction count - 1) }
  10855. Inc(InstrMax);
  10856. if InstrMax > High(InstrList) then
  10857. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10858. InstrList[InstrMax] := taicpu(hp1);
  10859. end;
  10860. end;
  10861. {$pop}
  10862. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10863. var
  10864. hp1 : tai;
  10865. begin
  10866. Result:=false;
  10867. if (taicpu(p).ops >= 2) and
  10868. ((taicpu(p).oper[0]^.typ = top_const) or
  10869. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10870. (taicpu(p).oper[1]^.typ = top_reg) and
  10871. ((taicpu(p).ops = 2) or
  10872. ((taicpu(p).oper[2]^.typ = top_reg) and
  10873. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10874. GetLastInstruction(p,hp1) and
  10875. MatchInstruction(hp1,A_MOV,[]) and
  10876. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10877. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10878. begin
  10879. TransferUsedRegs(TmpUsedRegs);
  10880. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10881. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10882. { change
  10883. mov reg1,reg2
  10884. imul y,reg2 to imul y,reg1,reg2 }
  10885. begin
  10886. taicpu(p).ops := 3;
  10887. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10888. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10889. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10890. RemoveInstruction(hp1);
  10891. result:=true;
  10892. end;
  10893. end;
  10894. end;
  10895. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10896. var
  10897. ThisLabel: TAsmLabel;
  10898. begin
  10899. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10900. ThisLabel.decrefs;
  10901. taicpu(p).condition := C_None;
  10902. taicpu(p).opcode := A_RET;
  10903. taicpu(p).is_jmp := false;
  10904. taicpu(p).ops := taicpu(ret_p).ops;
  10905. case taicpu(ret_p).ops of
  10906. 0:
  10907. taicpu(p).clearop(0);
  10908. 1:
  10909. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10910. else
  10911. internalerror(2016041301);
  10912. end;
  10913. { If the original label is now dead, it might turn out that the label
  10914. immediately follows p. As a result, everything beyond it, which will
  10915. be just some final register configuration and a RET instruction, is
  10916. now dead code. [Kit] }
  10917. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10918. running RemoveDeadCodeAfterJump for each RET instruction, because
  10919. this optimisation rarely happens and most RETs appear at the end of
  10920. routines where there is nothing that can be stripped. [Kit] }
  10921. if not ThisLabel.is_used then
  10922. RemoveDeadCodeAfterJump(p);
  10923. end;
  10924. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10925. var
  10926. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10927. Unconditional, PotentialModified: Boolean;
  10928. OperPtr: POper;
  10929. NewRef: TReference;
  10930. InstrList: array of taicpu;
  10931. InstrMax, Index: Integer;
  10932. const
  10933. {$ifdef DEBUG_AOPTCPU}
  10934. SNoFlags: shortstring = ' so the flags aren''t modified';
  10935. {$else DEBUG_AOPTCPU}
  10936. SNoFlags = '';
  10937. {$endif DEBUG_AOPTCPU}
  10938. begin
  10939. Result:=false;
  10940. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10941. begin
  10942. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10943. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10944. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10945. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10946. GetNextInstruction(hp1, hp2) and
  10947. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10948. { Change from: To:
  10949. set(C) %reg j(~C) label
  10950. test %reg,%reg/cmp $0,%reg
  10951. je label
  10952. set(C) %reg j(C) label
  10953. test %reg,%reg/cmp $0,%reg
  10954. jne label
  10955. (Also do something similar with sete/setne instead of je/jne)
  10956. }
  10957. begin
  10958. { Before we do anything else, we need to check the instructions
  10959. in between SETcc and TEST to make sure they don't modify the
  10960. FLAGS register - if -O2 or under, there won't be any
  10961. instructions between SET and TEST }
  10962. TransferUsedRegs(TmpUsedRegs);
  10963. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10964. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10965. begin
  10966. next := p;
  10967. SetLength(InstrList, 0);
  10968. InstrMax := -1;
  10969. PotentialModified := False;
  10970. { Make a note of every instruction that modifies the FLAGS
  10971. register }
  10972. while GetNextInstruction(next, next) and (next <> hp1) do
  10973. begin
  10974. if next.typ <> ait_instruction then
  10975. { GetNextInstructionUsingReg should have returned False }
  10976. InternalError(2021051701);
  10977. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10978. begin
  10979. case taicpu(next).opcode of
  10980. A_SETcc,
  10981. A_CMOVcc,
  10982. A_Jcc:
  10983. begin
  10984. if PotentialModified then
  10985. { Not safe because the flags were modified earlier }
  10986. Exit
  10987. else
  10988. { Condition is the same as the initial SETcc, so this is safe
  10989. (don't add to instruction list though) }
  10990. Continue;
  10991. end;
  10992. A_ADD:
  10993. begin
  10994. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  10995. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  10996. (taicpu(next).oper[1]^.typ <> top_reg) or
  10997. { Must write to a register }
  10998. (taicpu(next).oper[0]^.typ = top_ref) then
  10999. { Require a constant or a register }
  11000. Exit;
  11001. PotentialModified := True;
  11002. end;
  11003. A_SUB:
  11004. begin
  11005. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11006. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11007. (taicpu(next).oper[1]^.typ <> top_reg) or
  11008. { Must write to a register }
  11009. (taicpu(next).oper[0]^.typ <> top_const) or
  11010. (taicpu(next).oper[0]^.val = $80000000) then
  11011. { Can't subtract a register with LEA - also
  11012. check that the value isn't -2^31, as this
  11013. can't be negated }
  11014. Exit;
  11015. PotentialModified := True;
  11016. end;
  11017. A_SAL,
  11018. A_SHL:
  11019. begin
  11020. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11021. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11022. (taicpu(next).oper[1]^.typ <> top_reg) or
  11023. { Must write to a register }
  11024. (taicpu(next).oper[0]^.typ <> top_const) or
  11025. (taicpu(next).oper[0]^.val < 0) or
  11026. (taicpu(next).oper[0]^.val > 3) then
  11027. Exit;
  11028. PotentialModified := True;
  11029. end;
  11030. A_IMUL:
  11031. begin
  11032. if (taicpu(next).ops <> 3) or
  11033. (taicpu(next).oper[1]^.typ <> top_reg) or
  11034. { Must write to a register }
  11035. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  11036. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  11037. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  11038. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  11039. Exit
  11040. else
  11041. PotentialModified := True;
  11042. end;
  11043. else
  11044. { Don't know how to change this, so abort }
  11045. Exit;
  11046. end;
  11047. { Contains highest index (so instruction count - 1) }
  11048. Inc(InstrMax);
  11049. if InstrMax > High(InstrList) then
  11050. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11051. InstrList[InstrMax] := taicpu(next);
  11052. end;
  11053. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  11054. end;
  11055. if not Assigned(next) or (next <> hp1) then
  11056. { It should be equal to hp1 }
  11057. InternalError(2021051702);
  11058. { Cycle through each instruction and check to see if we can
  11059. change them to versions that don't modify the flags }
  11060. if (InstrMax >= 0) then
  11061. begin
  11062. for Index := 0 to InstrMax do
  11063. case InstrList[Index].opcode of
  11064. A_ADD:
  11065. begin
  11066. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  11067. InstrList[Index].opcode := A_LEA;
  11068. reference_reset(NewRef, 1, []);
  11069. NewRef.base := InstrList[Index].oper[1]^.reg;
  11070. if InstrList[Index].oper[0]^.typ = top_reg then
  11071. begin
  11072. NewRef.index := InstrList[Index].oper[0]^.reg;
  11073. NewRef.scalefactor := 1;
  11074. end
  11075. else
  11076. NewRef.offset := InstrList[Index].oper[0]^.val;
  11077. InstrList[Index].loadref(0, NewRef);
  11078. end;
  11079. A_SUB:
  11080. begin
  11081. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  11082. InstrList[Index].opcode := A_LEA;
  11083. reference_reset(NewRef, 1, []);
  11084. NewRef.base := InstrList[Index].oper[1]^.reg;
  11085. NewRef.offset := -InstrList[Index].oper[0]^.val;
  11086. InstrList[Index].loadref(0, NewRef);
  11087. end;
  11088. A_SHL,
  11089. A_SAL:
  11090. begin
  11091. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  11092. InstrList[Index].opcode := A_LEA;
  11093. reference_reset(NewRef, 1, []);
  11094. NewRef.index := InstrList[Index].oper[1]^.reg;
  11095. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  11096. InstrList[Index].loadref(0, NewRef);
  11097. end;
  11098. A_IMUL:
  11099. begin
  11100. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  11101. InstrList[Index].opcode := A_LEA;
  11102. reference_reset(NewRef, 1, []);
  11103. NewRef.index := InstrList[Index].oper[1]^.reg;
  11104. case InstrList[Index].oper[0]^.val of
  11105. 2, 4, 8:
  11106. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  11107. else {3, 5 and 9}
  11108. begin
  11109. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  11110. NewRef.base := InstrList[Index].oper[1]^.reg;
  11111. end;
  11112. end;
  11113. InstrList[Index].loadref(0, NewRef);
  11114. end;
  11115. else
  11116. InternalError(2021051710);
  11117. end;
  11118. end;
  11119. { Mark the FLAGS register as used across this whole block }
  11120. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  11121. end;
  11122. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11123. JumpC := taicpu(hp2).condition;
  11124. Unconditional := False;
  11125. if conditions_equal(JumpC, C_E) then
  11126. SetC := inverse_cond(taicpu(p).condition)
  11127. else if conditions_equal(JumpC, C_NE) then
  11128. SetC := taicpu(p).condition
  11129. else
  11130. { We've got something weird here (and inefficent) }
  11131. begin
  11132. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  11133. SetC := C_NONE;
  11134. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  11135. if condition_in(C_AE, JumpC) then
  11136. Unconditional := True
  11137. else
  11138. { Not sure what to do with this jump - drop out }
  11139. Exit;
  11140. end;
  11141. RemoveInstruction(hp1);
  11142. if Unconditional then
  11143. MakeUnconditional(taicpu(hp2))
  11144. else
  11145. begin
  11146. if SetC = C_NONE then
  11147. InternalError(2018061402);
  11148. taicpu(hp2).SetCondition(SetC);
  11149. end;
  11150. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11151. TmpUsedRegs }
  11152. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11153. begin
  11154. RemoveCurrentp(p, hp2);
  11155. if taicpu(hp2).opcode = A_SETcc then
  11156. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11157. else
  11158. begin
  11159. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11160. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11161. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11162. end;
  11163. end
  11164. else
  11165. if taicpu(hp2).opcode = A_SETcc then
  11166. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11167. else
  11168. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11169. Result := True;
  11170. end
  11171. else if
  11172. { Make sure the instructions are adjacent }
  11173. (
  11174. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11175. GetNextInstruction(p, hp1)
  11176. ) and
  11177. MatchInstruction(hp1, A_MOV, [S_B]) and
  11178. { Writing to memory is allowed }
  11179. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11180. begin
  11181. {
  11182. Watch out for sequences such as:
  11183. set(c)b %regb
  11184. movb %regb,(ref)
  11185. movb $0,1(ref)
  11186. movb $0,2(ref)
  11187. movb $0,3(ref)
  11188. Much more efficient to turn it into:
  11189. movl $0,%regl
  11190. set(c)b %regb
  11191. movl %regl,(ref)
  11192. Or:
  11193. set(c)b %regb
  11194. movzbl %regb,%regl
  11195. movl %regl,(ref)
  11196. }
  11197. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11198. GetNextInstruction(hp1, hp2) and
  11199. MatchInstruction(hp2, A_MOV, [S_B]) and
  11200. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11201. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11202. begin
  11203. { Don't do anything else except set Result to True }
  11204. end
  11205. else
  11206. begin
  11207. if taicpu(p).oper[0]^.typ = top_reg then
  11208. begin
  11209. TransferUsedRegs(TmpUsedRegs);
  11210. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11211. end;
  11212. { If it's not a register, it's a memory address }
  11213. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11214. begin
  11215. { Even if the register is still in use, we can minimise the
  11216. pipeline stall by changing the MOV into another SETcc. }
  11217. taicpu(hp1).opcode := A_SETcc;
  11218. taicpu(hp1).condition := taicpu(p).condition;
  11219. if taicpu(hp1).oper[1]^.typ = top_ref then
  11220. begin
  11221. { Swapping the operand pointers like this is probably a
  11222. bit naughty, but it is far faster than using loadoper
  11223. to transfer the reference from oper[1] to oper[0] if
  11224. you take into account the extra procedure calls and
  11225. the memory allocation and deallocation required }
  11226. OperPtr := taicpu(hp1).oper[1];
  11227. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11228. taicpu(hp1).oper[0] := OperPtr;
  11229. end
  11230. else
  11231. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11232. taicpu(hp1).clearop(1);
  11233. taicpu(hp1).ops := 1;
  11234. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11235. end
  11236. else
  11237. begin
  11238. if taicpu(hp1).oper[1]^.typ = top_reg then
  11239. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11240. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11241. RemoveInstruction(hp1);
  11242. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11243. end
  11244. end;
  11245. Result := True;
  11246. end;
  11247. end;
  11248. end;
  11249. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11250. var
  11251. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11252. TargetReg: TRegister;
  11253. condition, inverted_condition: TAsmCond;
  11254. FoundMOV: Boolean;
  11255. begin
  11256. Result := False;
  11257. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11258. create the most optimial instructions possible due to limited
  11259. register availability, and there are situations where two
  11260. complementary "simple" CMOV blocks are created which, after the fact
  11261. can be merged into a "double" block. For example:
  11262. movw $257,%ax
  11263. movw $2,%r8w
  11264. xorl r9d,%r9d
  11265. testw $16,18(%rcx)
  11266. cmovew %ax,%dx
  11267. cmovew %r8w,%bx
  11268. cmovel %r9d,%r14d
  11269. movw $1283,%ax
  11270. movw $4,%r8w
  11271. movl $9,%r9d
  11272. cmovnew %ax,%dx
  11273. cmovnew %r8w,%bx
  11274. cmovnel %r9d,%r14d
  11275. The CMOVNE instructions at the end can be removed, and the
  11276. destination registers copied into the MOV instructions directly
  11277. above them, before finally being moved to before the first CMOVE
  11278. instructions, to produce:
  11279. movw $257,%ax
  11280. movw $2,%r8w
  11281. xorl r9d,%r9d
  11282. testw $16,18(%rcx)
  11283. movw $1283,%dx
  11284. movw $4,%bx
  11285. movl $9,%r14d
  11286. cmovew %ax,%dx
  11287. cmovew %r8w,%bx
  11288. cmovel %r9d,%r14d
  11289. Which can then be later optimised to:
  11290. movw $257,%ax
  11291. movw $2,%r8w
  11292. xorl r9d,%r9d
  11293. movw $1283,%dx
  11294. movw $4,%bx
  11295. movl $9,%r14d
  11296. testw $16,18(%rcx)
  11297. cmovew %ax,%dx
  11298. cmovew %r8w,%bx
  11299. cmovel %r9d,%r14d
  11300. }
  11301. TargetReg := taicpu(hp1).oper[1]^.reg;
  11302. condition := taicpu(hp1).condition;
  11303. inverted_condition := inverse_cond(condition);
  11304. pFirstMov := nil;
  11305. pLastMov := nil;
  11306. pCMOV := nil;
  11307. if (p.typ = ait_instruction) then
  11308. pCond := p
  11309. else if not GetNextInstruction(p, pCond) then
  11310. InternalError(2024012501);
  11311. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11312. { We should get the CMP or TEST instructeion }
  11313. InternalError(2024012502);
  11314. if (
  11315. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11316. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11317. ) then
  11318. begin
  11319. { We have to tread carefully here, hence why we're not using
  11320. GetNextInstructionUsingReg... we can only accept MOV and other
  11321. CMOV instructions. Anything else and we must drop out}
  11322. hp2 := hp1;
  11323. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11324. begin
  11325. if (hp2.typ <> ait_instruction) then
  11326. Exit;
  11327. case taicpu(hp2).opcode of
  11328. A_MOV:
  11329. begin
  11330. if not Assigned(pFirstMov) then
  11331. pFirstMov := hp2;
  11332. pLastMOV := hp2;
  11333. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11334. { Something different - drop out }
  11335. Exit;
  11336. { Otherwise, leave it for now }
  11337. end;
  11338. A_CMOVcc:
  11339. begin
  11340. if taicpu(hp2).condition = inverted_condition then
  11341. begin
  11342. { We found what we're looking for }
  11343. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11344. begin
  11345. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11346. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11347. begin
  11348. pCMOV := hp2;
  11349. Break;
  11350. end
  11351. else
  11352. { Unsafe reference - drop out }
  11353. Exit;
  11354. end;
  11355. end
  11356. else if taicpu(hp2).condition <> condition then
  11357. { Something weird - drop out }
  11358. Exit;
  11359. end;
  11360. else
  11361. { Invalid }
  11362. Exit;
  11363. end;
  11364. end;
  11365. if not Assigned(pCMOV) then
  11366. { No complementary CMOV found }
  11367. Exit;
  11368. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11369. begin
  11370. { Don't need to do anything special or search for a matching MOV }
  11371. Asml.Remove(pCMOV);
  11372. if RegInInstruction(TargetReg, pCond) then
  11373. { Make sure we don't overwrite the register if it's being used in the condition }
  11374. Asml.InsertAfter(pCMOV, pCond)
  11375. else
  11376. Asml.InsertBefore(pCMOV, pCond);
  11377. taicpu(pCMOV).opcode := A_MOV;
  11378. taicpu(pCMOV).condition := C_None;
  11379. { Don't need to worry about allocating new registers in these cases }
  11380. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11381. Result := True;
  11382. Exit;
  11383. end
  11384. else
  11385. begin
  11386. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11387. FoundMOV := False;
  11388. { Search for the MOV that sets the target register }
  11389. hp2 := pFirstMov;
  11390. repeat
  11391. if (taicpu(hp2).opcode = A_MOV) and
  11392. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11393. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11394. begin
  11395. { Change the destination }
  11396. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11397. if not FoundMOV then
  11398. begin
  11399. FoundMOV := True;
  11400. { Make sure the register is allocated }
  11401. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11402. end;
  11403. hp1 := tai(hp2.Previous);
  11404. Asml.Remove(hp2);
  11405. if RegInInstruction(TargetReg, pCond) then
  11406. { Make sure we don't overwrite the register if it's being used in the condition }
  11407. Asml.InsertAfter(hp2, pCond)
  11408. else
  11409. Asml.InsertBefore(hp2, pCond);
  11410. if (hp2 = pLastMov) then
  11411. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11412. Break;
  11413. hp2 := hp1;
  11414. end;
  11415. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11416. if FoundMOV then
  11417. { Delete the CMOV }
  11418. RemoveInstruction(pCMOV)
  11419. else
  11420. begin
  11421. { If no MOV was found, we have to actually move and transmute the CMOV }
  11422. Asml.Remove(pCMOV);
  11423. if RegInInstruction(TargetReg, pCond) then
  11424. { Make sure we don't overwrite the register if it's being used in the condition }
  11425. Asml.InsertAfter(pCMOV, pCond)
  11426. else
  11427. Asml.InsertBefore(pCMOV, pCond);
  11428. taicpu(pCMOV).opcode := A_MOV;
  11429. taicpu(pCMOV).condition := C_None;
  11430. end;
  11431. Result := True;
  11432. Exit;
  11433. end;
  11434. end;
  11435. end;
  11436. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11437. var
  11438. hp1, hp2, pCond: tai;
  11439. begin
  11440. Result := False;
  11441. { Search ahead for CMOV instructions }
  11442. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11443. begin
  11444. hp1 := p;
  11445. hp2 := p;
  11446. pCond := nil; { To prevent compiler warnings }
  11447. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11448. DEFAULTFLAGS }
  11449. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11450. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11451. pCond := p;
  11452. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11453. begin
  11454. if (hp1.typ <> ait_instruction) then
  11455. { Break out on markers and labels etc. }
  11456. Break;
  11457. case taicpu(hp1).opcode of
  11458. A_MOV:
  11459. { Ignore regular MOVs unless they are obviously not related
  11460. to a CMOV block }
  11461. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11462. Break;
  11463. A_CMOVcc:
  11464. if TryCmpCMovOpts(pCond, hp1) then
  11465. begin
  11466. hp1 := hp2;
  11467. { p itself isn't changed, and we're still inside a
  11468. while loop to catch subsequent CMOVs, so just flag
  11469. a new iteration }
  11470. Include(OptsToCheck, aoc_ForceNewIteration);
  11471. Continue;
  11472. end;
  11473. else
  11474. { Drop out if we find anything else }
  11475. Break;
  11476. end;
  11477. hp2 := hp1;
  11478. end;
  11479. end;
  11480. end;
  11481. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11482. var
  11483. hp1, hp2, pCond: tai;
  11484. SourceReg, TargetReg: TRegister;
  11485. begin
  11486. Result := False;
  11487. { In some situations, we end up with an inefficient arrangement of
  11488. instructions in the form of:
  11489. or %reg1,%reg2
  11490. (%reg1 deallocated)
  11491. test %reg2,%reg2
  11492. mov x,%reg2
  11493. we may be able to swap and rearrange the registers to produce:
  11494. or %reg2,%reg1
  11495. mov x,%reg2
  11496. test %reg1,%reg1
  11497. (%reg1 deallocated)
  11498. }
  11499. if (cs_opt_level3 in current_settings.optimizerswitches) and
  11500. (taicpu(p).oper[1]^.typ = top_reg) and
  11501. (
  11502. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  11503. MatchOperand(taicpu(p).oper[0]^, -1)
  11504. ) and
  11505. GetNextInstruction(p, hp1) and
  11506. MatchInstruction(hp1, A_MOV, []) and
  11507. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11508. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  11509. begin
  11510. TargetReg := taicpu(p).oper[1]^.reg;
  11511. { Now look backwards to find a simple commutative operation: ADD,
  11512. IMUL (2-register version), OR, AND or XOR - whose destination
  11513. register is the same as TEST }
  11514. hp2 := p;
  11515. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  11516. if RegInInstruction(TargetReg, hp2) then
  11517. begin
  11518. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  11519. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11520. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  11521. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  11522. begin
  11523. SourceReg := taicpu(hp2).oper[0]^.reg;
  11524. if
  11525. { Make sure the MOV doesn't use the other register }
  11526. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  11527. { And make sure the source register is not used afterwards }
  11528. not RegInUsedRegs(SourceReg, UsedRegs) then
  11529. begin
  11530. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  11531. taicpu(hp2).oper[0]^.reg := TargetReg;
  11532. taicpu(hp2).oper[1]^.reg := SourceReg;
  11533. if taicpu(p).oper[0]^.typ = top_reg then
  11534. taicpu(p).oper[0]^.reg := SourceReg;
  11535. taicpu(p).oper[1]^.reg := SourceReg;
  11536. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  11537. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  11538. Include(OptsToCheck, aoc_ForceNewIteration);
  11539. { We can still check the following optimisations since
  11540. the instruction is still a TEST }
  11541. end;
  11542. end;
  11543. Break;
  11544. end;
  11545. end;
  11546. { Search ahead3 for CMOV instructions }
  11547. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11548. begin
  11549. hp1 := p;
  11550. hp2 := p;
  11551. pCond := nil; { To prevent compiler warnings }
  11552. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11553. DEFAULTFLAGS }
  11554. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11555. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11556. pCond := p;
  11557. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11558. begin
  11559. if (hp1.typ <> ait_instruction) then
  11560. { Break out on markers and labels etc. }
  11561. Break;
  11562. case taicpu(hp1).opcode of
  11563. A_MOV:
  11564. { Ignore regular MOVs unless they are obviously not related
  11565. to a CMOV block }
  11566. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11567. Break;
  11568. A_CMOVcc:
  11569. if TryCmpCMovOpts(pCond, hp1) then
  11570. begin
  11571. hp1 := hp2;
  11572. { p itself isn't changed, and we're still inside a
  11573. while loop to catch subsequent CMOVs, so just flag
  11574. a new iteration }
  11575. Include(OptsToCheck, aoc_ForceNewIteration);
  11576. Continue;
  11577. end;
  11578. else
  11579. { Drop out if we find anything else }
  11580. Break;
  11581. end;
  11582. hp2 := hp1;
  11583. end;
  11584. end;
  11585. end;
  11586. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11587. var
  11588. hp1: tai;
  11589. Count: Integer;
  11590. OrigLabel: TAsmLabel;
  11591. begin
  11592. result := False;
  11593. { Sometimes, the optimisations below can permit this }
  11594. RemoveDeadCodeAfterJump(p);
  11595. 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
  11596. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11597. begin
  11598. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11599. { Also a side-effect of optimisations }
  11600. if CollapseZeroDistJump(p, OrigLabel) then
  11601. begin
  11602. Result := True;
  11603. Exit;
  11604. end;
  11605. hp1 := GetLabelWithSym(OrigLabel);
  11606. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11607. begin
  11608. if taicpu(hp1).opcode = A_RET then
  11609. begin
  11610. {
  11611. change
  11612. jmp .L1
  11613. ...
  11614. .L1:
  11615. ret
  11616. into
  11617. ret
  11618. }
  11619. begin
  11620. ConvertJumpToRET(p, hp1);
  11621. result:=true;
  11622. end;
  11623. end
  11624. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11625. not (cs_opt_size in current_settings.optimizerswitches) and
  11626. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11627. begin
  11628. Result := True;
  11629. Exit;
  11630. end;
  11631. end;
  11632. end;
  11633. end;
  11634. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11635. begin
  11636. Result := assigned(p) and
  11637. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11638. (taicpu(p).oper[1]^.typ = top_reg) and
  11639. (
  11640. (taicpu(p).oper[0]^.typ = top_reg) or
  11641. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11642. it is not expected that this can cause a seg. violation }
  11643. (
  11644. (taicpu(p).oper[0]^.typ = top_ref) and
  11645. { TODO: Can we detect which references become constants at this
  11646. stage so we don't have to do a blanket ban? }
  11647. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11648. (
  11649. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11650. (
  11651. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11652. not RefModified and
  11653. { If the reference also appears in the condition, then we know it's safe, otherwise
  11654. any kind of access violation would have occurred already }
  11655. Assigned(cond_p) and
  11656. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11657. (cond_p.typ = ait_instruction) and
  11658. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11659. { Just consider 2-operand comparison instructions for now to be safe }
  11660. (taicpu(cond_p).ops = 2) and
  11661. (
  11662. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11663. (
  11664. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11665. { Don't risk identical registers but different offsets, as we may have constructs
  11666. such as buffer streams with things like length fields that indicate whether
  11667. any more data follows. And there are probably some contrived examples where
  11668. writing to offsets behind the one being read also lead to access violations }
  11669. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11670. (
  11671. { Check that we're not modifying a register that appears in the reference }
  11672. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11673. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11674. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11675. )
  11676. )
  11677. )
  11678. )
  11679. )
  11680. )
  11681. );
  11682. end;
  11683. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11684. begin
  11685. { Update integer registers, ignoring deallocations }
  11686. repeat
  11687. while assigned(p) and
  11688. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11689. (p.typ = ait_label) or
  11690. ((p.typ = ait_marker) and
  11691. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11692. p := tai(p.next);
  11693. while assigned(p) and
  11694. (p.typ=ait_RegAlloc) Do
  11695. begin
  11696. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11697. begin
  11698. case tai_regalloc(p).ratype of
  11699. ra_alloc :
  11700. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11701. else
  11702. ;
  11703. end;
  11704. end;
  11705. p := tai(p.next);
  11706. end;
  11707. until not(assigned(p)) or
  11708. (not(p.typ in SkipInstr) and
  11709. not((p.typ = ait_label) and
  11710. labelCanBeSkipped(tai_label(p))));
  11711. end;
  11712. {$ifndef 8086}
  11713. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11714. begin
  11715. Result := False;
  11716. EndJump := nil;
  11717. BlockStop := nil;
  11718. while (BlockStart <> fOptimizer.BlockEnd) and
  11719. { stop on labels }
  11720. (BlockStart.typ <> ait_label) do
  11721. begin
  11722. { Keep track of all integer registers that are used }
  11723. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11724. if BlockStart.typ = ait_instruction then
  11725. begin
  11726. if (taicpu(BlockStart).opcode = A_JMP) then
  11727. begin
  11728. if not IsJumpToLabel(taicpu(BlockStart)) or
  11729. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11730. Exit;
  11731. EndJump := BlockStart;
  11732. Break;
  11733. end
  11734. { Check to see if we have a valid MOV instruction instead }
  11735. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11736. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11737. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11738. begin
  11739. Exit;
  11740. end
  11741. else
  11742. { This will be a valid MOV }
  11743. fAllocationRange := BlockStart;
  11744. end;
  11745. OneBeforeBlock := BlockStart;
  11746. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11747. end;
  11748. if (BlockStart = fOptimizer.BlockEnd) then
  11749. Exit;
  11750. BlockStop := BlockStart;
  11751. Result := True;
  11752. end;
  11753. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  11754. var
  11755. hp1: tai;
  11756. RefModified: Boolean;
  11757. begin
  11758. Result := 0;
  11759. hp1 := BlockStart;
  11760. RefModified := False; { As long as the condition is inverted, this can be reset }
  11761. while assigned(hp1) and
  11762. (hp1 <> BlockStop) do
  11763. begin
  11764. case hp1.typ of
  11765. ait_instruction:
  11766. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11767. begin
  11768. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  11769. begin
  11770. Inc(Result);
  11771. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11772. Assigned(fCondition) and
  11773. { Will have 2 operands }
  11774. (
  11775. (
  11776. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  11777. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  11778. ) or
  11779. (
  11780. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  11781. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  11782. )
  11783. ) then
  11784. { It is no longer safe to use the reference in the condition.
  11785. this prevents problems such as:
  11786. mov (%reg),%reg
  11787. mov (%reg),...
  11788. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11789. (fixes #40165)
  11790. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11791. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11792. }
  11793. RefModified := True;
  11794. end
  11795. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11796. { CMOV with constants grows the code size }
  11797. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  11798. begin
  11799. { Register was reserved by TryCMOVConst and
  11800. stored on ConstRegs }
  11801. end
  11802. else
  11803. begin
  11804. Result := -1;
  11805. Exit;
  11806. end;
  11807. end
  11808. else
  11809. begin
  11810. Result := -1;
  11811. Exit;
  11812. end;
  11813. else
  11814. { Most likely an align };
  11815. end;
  11816. fOptimizer.GetNextInstruction(hp1, hp1);
  11817. end;
  11818. end;
  11819. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  11820. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  11821. (this is done as a separate stage because the double types are extensions of the branching type,
  11822. but we can't discount the conditional jump until the last step) }
  11823. procedure EvaluateBranchingType;
  11824. begin
  11825. Inc(CMOVScore);
  11826. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  11827. { Too many instructions to be worthwhile }
  11828. fState := tsInvalid;
  11829. end;
  11830. var
  11831. hp1: tai;
  11832. Count: Integer;
  11833. begin
  11834. { Table of valid CMOV block types
  11835. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  11836. ---------- --------- --------- --------- --------- ---------
  11837. tsSimple X Yes X X X
  11838. tsDetour = 1st X X X X
  11839. tsBranching <> Mid Yes X X X
  11840. tsDouble End-label Yes * Yes X Yes
  11841. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  11842. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  11843. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  11844. * Only one reference allowed
  11845. }
  11846. hp1 := nil; { To prevent compiler warnings }
  11847. Optimizer.CopyUsedRegs(RegisterTracking);
  11848. fOptimizer := Optimizer;
  11849. fLabel := AFirstLabel;
  11850. CMOVScore := 0;
  11851. ConstCount := 0;
  11852. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11853. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11854. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11855. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11856. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11857. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11858. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11859. fInsertionPoint := p_initialjump;
  11860. fCondition := nil;
  11861. fInitialJump := p_initialjump;
  11862. fFirstMovBlock := p_initialmov;
  11863. fFirstMovBlockStop := nil;
  11864. fSecondJump := nil;
  11865. fSecondMovBlock := nil;
  11866. fSecondMovBlockStop := nil;
  11867. fMidLabel := nil;
  11868. fSecondJump := nil;
  11869. fSecondMovBlock := nil;
  11870. fEndLabel := nil;
  11871. fAllocationRange := nil;
  11872. { Assume it all goes horribly wrong! }
  11873. fState := tsInvalid;
  11874. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  11875. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  11876. 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
  11877. begin
  11878. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11879. for Count := 0 to 1 do
  11880. with taicpu(fCondition).oper[Count]^ do
  11881. case typ of
  11882. top_reg:
  11883. if getregtype(reg) = R_INTREGISTER then
  11884. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11885. top_ref:
  11886. begin
  11887. if
  11888. {$ifdef x86_64}
  11889. (ref^.base <> NR_RIP) and
  11890. {$endif x86_64}
  11891. (ref^.base <> NR_NO) then
  11892. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11893. if (ref^.index <> NR_NO) then
  11894. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11895. end
  11896. else
  11897. ;
  11898. end;
  11899. { When inserting instructions before hp_prev, try to insert them
  11900. before the allocation of the FLAGS register }
  11901. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  11902. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  11903. { If not found, set it equal to the condition so it's something sensible }
  11904. fInsertionPoint := fCondition;
  11905. { When dealing with a comparison against zero, take note of the
  11906. instruction before it to see if we can move instructions further
  11907. back in order to benefit PostPeepholeOptTestOr.
  11908. }
  11909. if (
  11910. (
  11911. (taicpu(fCondition).opcode = A_CMP) and
  11912. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  11913. ) or
  11914. (
  11915. (taicpu(fCondition).opcode = A_TEST) and
  11916. (
  11917. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  11918. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  11919. )
  11920. )
  11921. ) and
  11922. Optimizer.GetLastInstruction(fCondition, hp1) then
  11923. begin
  11924. { These instructions set the zero flag if the result is zero }
  11925. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11926. begin
  11927. fInsertionPoint := hp1;
  11928. { Also mark all the registers in this previous instruction
  11929. as 'in use', even if they've just been deallocated }
  11930. for Count := 0 to 1 do
  11931. with taicpu(hp1).oper[Count]^ do
  11932. case typ of
  11933. top_reg:
  11934. if getregtype(reg) = R_INTREGISTER then
  11935. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11936. top_ref:
  11937. begin
  11938. if
  11939. {$ifdef x86_64}
  11940. (ref^.base <> NR_RIP) and
  11941. {$endif x86_64}
  11942. (ref^.base <> NR_NO) then
  11943. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11944. if (ref^.index <> NR_NO) then
  11945. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11946. end
  11947. else
  11948. ;
  11949. end;
  11950. end;
  11951. end;
  11952. end
  11953. else
  11954. fCondition := nil;
  11955. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  11956. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  11957. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  11958. { If not found, set it equal to p so it's something sensible }
  11959. fInsertionPoint := hp1;
  11960. hp1 := p_initialmov;
  11961. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  11962. Exit;
  11963. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  11964. if (hp1.typ <> ait_label) then { should be on a jump }
  11965. begin
  11966. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  11967. { Need a label afterwards }
  11968. Exit;
  11969. end
  11970. else
  11971. fMidLabel := hp1;
  11972. if tai_label(fMidLabel).labsym <> AFirstLabel then
  11973. { Not the correct label }
  11974. fMidLabel := nil;
  11975. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  11976. { If there's neither a 2nd jump nor correct label, then it's invalid
  11977. (see above table) }
  11978. Exit;
  11979. { Analyse the first block of MOVs more closely }
  11980. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  11981. if Assigned(fSecondJump) then
  11982. begin
  11983. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  11984. begin
  11985. fState := tsDetour
  11986. end
  11987. else
  11988. begin
  11989. { Need the correct mid-label for this one }
  11990. if not Assigned(fMidLabel) then
  11991. Exit;
  11992. fState := tsBranching;
  11993. end;
  11994. end
  11995. else
  11996. { No jump. but mid-label is present }
  11997. fState := tsSimple;
  11998. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  11999. begin
  12000. { Invalid or too many instructions to be worthwhile }
  12001. fState := tsInvalid;
  12002. Exit;
  12003. end;
  12004. { check further for
  12005. jCC xxx
  12006. <several movs 1>
  12007. jmp yyy
  12008. xxx:
  12009. <several movs 2>
  12010. yyy:
  12011. etc.
  12012. }
  12013. if (fState = tsBranching) and
  12014. { Estimate for required savings for extra jump }
  12015. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  12016. { Only one reference is allowed for double blocks }
  12017. (AFirstLabel.getrefs = 1) then
  12018. begin
  12019. Optimizer.GetNextInstruction(fMidLabel, hp1);
  12020. fSecondMovBlock := hp1;
  12021. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  12022. begin
  12023. EvaluateBranchingType;
  12024. Exit;
  12025. end;
  12026. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  12027. if (hp1.typ <> ait_label) then { should be on a jump }
  12028. begin
  12029. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  12030. begin
  12031. { Need a label afterwards }
  12032. EvaluateBranchingType;
  12033. Exit;
  12034. end;
  12035. end
  12036. else
  12037. fEndLabel := hp1;
  12038. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  12039. { Second jump doesn't go to the end }
  12040. fEndLabel := nil;
  12041. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  12042. begin
  12043. { If there's neither a 3rd jump nor correct end label, then it's
  12044. not a invalid double block, but is a valid single branching
  12045. block (see above table) }
  12046. EvaluateBranchingType;
  12047. Exit;
  12048. end;
  12049. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  12050. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  12051. { Invalid or too many instructions to be worthwhile }
  12052. Exit;
  12053. Inc(CMOVScore, Count);
  12054. if Assigned(fThirdJump) then
  12055. begin
  12056. if not Assigned(fSecondJump) then
  12057. fState := tsDoubleSecondBranching
  12058. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  12059. fState := tsDoubleBranchSame
  12060. else
  12061. fState := tsDoubleBranchDifferent;
  12062. end
  12063. else
  12064. fState := tsDouble;
  12065. end;
  12066. if fState = tsBranching then
  12067. EvaluateBranchingType;
  12068. end;
  12069. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  12070. new register to store the constant }
  12071. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  12072. var
  12073. RegSize: TSubRegister;
  12074. CurrentVal: TCGInt;
  12075. ANewReg: TRegister;
  12076. X: ShortInt;
  12077. begin
  12078. Result := False;
  12079. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12080. Exit;
  12081. if ConstCount >= MAX_CMOV_REGISTERS then
  12082. { Arrays are full }
  12083. Exit;
  12084. { Remember that CMOV can't encode 8-bit registers }
  12085. case taicpu(p).opsize of
  12086. S_W:
  12087. RegSize := R_SUBW;
  12088. S_L:
  12089. RegSize := R_SUBD;
  12090. {$ifdef x86_64}
  12091. S_Q:
  12092. RegSize := R_SUBQ;
  12093. {$endif x86_64}
  12094. else
  12095. InternalError(2021100401);
  12096. end;
  12097. { See if the value has already been reserved for another CMOV instruction }
  12098. CurrentVal := taicpu(p).oper[0]^.val;
  12099. for X := 0 to ConstCount - 1 do
  12100. if ConstVals[X] = CurrentVal then
  12101. begin
  12102. ConstRegs[ConstCount] := ConstRegs[X];
  12103. ConstSizes[ConstCount] := RegSize;
  12104. ConstVals[ConstCount] := CurrentVal;
  12105. Inc(ConstCount);
  12106. Inc(Count);
  12107. Result := True;
  12108. Exit;
  12109. end;
  12110. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  12111. if ANewReg = NR_NO then
  12112. { No free registers }
  12113. Exit;
  12114. { Reserve the register so subsequent TryCMOVConst calls don't all end
  12115. up vying for the same register }
  12116. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  12117. ConstRegs[ConstCount] := ANewReg;
  12118. ConstSizes[ConstCount] := RegSize;
  12119. ConstVals[ConstCount] := CurrentVal;
  12120. Inc(ConstCount);
  12121. Inc(Count);
  12122. Result := True;
  12123. end;
  12124. destructor TCMOVTracking.Done;
  12125. begin
  12126. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  12127. end;
  12128. procedure TCMOVTracking.Process(out new_p: tai);
  12129. var
  12130. Count, Writes: LongInt;
  12131. RegMatch: Boolean;
  12132. hp1, hp_new: tai;
  12133. inverted_condition, condition: TAsmCond;
  12134. begin
  12135. if (fState in [tsInvalid, tsProcessed]) then
  12136. InternalError(2023110701);
  12137. { Repurpose RegisterTracking to mark registers that we've defined }
  12138. RegisterTracking[R_INTREGISTER].Clear;
  12139. Count := 0;
  12140. Writes := 0;
  12141. condition := taicpu(fInitialJump).condition;
  12142. inverted_condition := inverse_cond(condition);
  12143. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12144. doesn't get CMOVs in this case }
  12145. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12146. begin
  12147. { Include the jump in the flag tracking }
  12148. if Assigned(fThirdJump) then
  12149. begin
  12150. if (fState = tsDoubleBranchSame) then
  12151. begin
  12152. { Will be an unconditional jump, so track to the instruction before it }
  12153. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12154. InternalError(2023110710);
  12155. end
  12156. else
  12157. hp1 := fThirdJump;
  12158. end
  12159. else
  12160. hp1 := fSecondMovBlockStop;
  12161. end
  12162. else
  12163. begin
  12164. { Include a conditional jump in the flag tracking }
  12165. if Assigned(fSecondJump) then
  12166. begin
  12167. if (fState = tsDetour) then
  12168. begin
  12169. { Will be an unconditional jump, so track to the instruction before it }
  12170. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12171. InternalError(2023110711);
  12172. end
  12173. else
  12174. hp1 := fSecondJump;
  12175. end
  12176. else
  12177. hp1 := fFirstMovBlockStop;
  12178. end;
  12179. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12180. { Process the second set of MOVs first, because if a destination
  12181. register is shared between the first and second MOV sets, it is more
  12182. efficient to turn the first one into a MOV instruction and place it
  12183. before the CMP if possible, but we won't know which registers are
  12184. shared until we've processed at least one list, so we might as well
  12185. make it the second one since that won't be modified again. }
  12186. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12187. begin
  12188. hp1 := fSecondMovBlock;
  12189. repeat
  12190. if not Assigned(hp1) then
  12191. InternalError(2018062902);
  12192. if (hp1.typ = ait_instruction) then
  12193. begin
  12194. { Extra safeguard }
  12195. if (taicpu(hp1).opcode <> A_MOV) then
  12196. InternalError(2018062903);
  12197. { Note: tsDoubleBranchDifferent is essentially identical to
  12198. tsBranching and the 2nd block is best left largely
  12199. untouched, but we need to evaluate which registers the MOVs
  12200. write to in order to track what would be complementary CMOV
  12201. pairs that can be further optimised. [Kit] }
  12202. if fState <> tsDoubleBranchDifferent then
  12203. begin
  12204. if taicpu(hp1).oper[0]^.typ = top_const then
  12205. begin
  12206. RegMatch := False;
  12207. for Count := 0 to ConstCount - 1 do
  12208. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12209. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12210. begin
  12211. RegMatch := True;
  12212. { If it's in RegisterTracking, then this register
  12213. is being used more than once and hence has
  12214. already had its value defined (it gets added to
  12215. UsedRegs through AllocRegBetween below) }
  12216. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12217. begin
  12218. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12219. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12220. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12221. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12222. ConstMovs[Count] := hp_new;
  12223. end
  12224. else
  12225. { We just need an instruction between hp_prev and hp1
  12226. where we know the register is marked as in use }
  12227. hp_new := fSecondMovBlock;
  12228. { Keep track of largest write for this register so it can be optimised later }
  12229. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12230. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12231. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12232. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12233. Break;
  12234. end;
  12235. if not RegMatch then
  12236. InternalError(2021100411);
  12237. end;
  12238. taicpu(hp1).opcode := A_CMOVcc;
  12239. taicpu(hp1).condition := condition;
  12240. end;
  12241. { Store these writes to search for duplicates later on }
  12242. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12243. Inc(Writes);
  12244. end;
  12245. fOptimizer.GetNextInstruction(hp1, hp1);
  12246. until (hp1 = fSecondMovBlockStop);
  12247. end;
  12248. { Now do the first set of MOVs }
  12249. hp1 := fFirstMovBlock;
  12250. repeat
  12251. if not Assigned(hp1) then
  12252. InternalError(2018062904);
  12253. if (hp1.typ = ait_instruction) then
  12254. begin
  12255. RegMatch := False;
  12256. { Extra safeguard }
  12257. if (taicpu(hp1).opcode <> A_MOV) then
  12258. InternalError(2018062905);
  12259. { Search through the RegWrites list to see if there are any
  12260. opposing CMOV pairs that write to the same register }
  12261. for Count := 0 to Writes - 1 do
  12262. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12263. begin
  12264. { We have a match. Keep this as a MOV }
  12265. { Move ahead in preparation }
  12266. fOptimizer.GetNextInstruction(hp1, hp1);
  12267. RegMatch := True;
  12268. Break;
  12269. end;
  12270. if RegMatch then
  12271. Continue;
  12272. if taicpu(hp1).oper[0]^.typ = top_const then
  12273. begin
  12274. for Count := 0 to ConstCount - 1 do
  12275. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12276. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12277. begin
  12278. RegMatch := True;
  12279. { If it's in RegisterTracking, then this register is
  12280. being used more than once and hence has already had
  12281. its value defined (it gets added to UsedRegs through
  12282. AllocRegBetween below) }
  12283. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12284. begin
  12285. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12286. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12287. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12288. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12289. ConstMovs[Count] := hp_new;
  12290. end
  12291. else
  12292. { We just need an instruction between hp_prev and hp1
  12293. where we know the register is marked as in use }
  12294. hp_new := fFirstMovBlock;
  12295. { Keep track of largest write for this register so it can be optimised later }
  12296. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12297. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12298. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12299. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12300. Break;
  12301. end;
  12302. if not RegMatch then
  12303. InternalError(2021100412);
  12304. end;
  12305. taicpu(hp1).opcode := A_CMOVcc;
  12306. taicpu(hp1).condition := inverted_condition;
  12307. if (fState = tsDoubleBranchDifferent) then
  12308. begin
  12309. { Store these writes to search for duplicates later on }
  12310. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12311. Inc(Writes);
  12312. end;
  12313. end;
  12314. fOptimizer.GetNextInstruction(hp1, hp1);
  12315. until (hp1 = fFirstMovBlockStop);
  12316. { Update initialisation MOVs to the smallest possible size }
  12317. for Count := 0 to ConstCount - 1 do
  12318. if Assigned(ConstMovs[Count]) then
  12319. begin
  12320. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12321. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12322. end;
  12323. case fState of
  12324. tsSimple:
  12325. begin
  12326. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12327. { No branch to delete }
  12328. end;
  12329. tsDetour:
  12330. begin
  12331. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12332. { Preserve jump }
  12333. end;
  12334. tsBranching, tsDoubleBranchDifferent:
  12335. begin
  12336. if (fState = tsBranching) then
  12337. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12338. else
  12339. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12340. taicpu(fSecondJump).opcode := A_JCC;
  12341. taicpu(fSecondJump).condition := inverted_condition;
  12342. end;
  12343. tsDouble, tsDoubleBranchSame:
  12344. begin
  12345. if (fState = tsDouble) then
  12346. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12347. else
  12348. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12349. { Delete second jump }
  12350. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12351. fOptimizer.RemoveInstruction(fSecondJump);
  12352. end;
  12353. tsDoubleSecondBranching:
  12354. begin
  12355. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12356. { Delete second jump, preserve third jump as conditional }
  12357. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12358. fOptimizer.RemoveInstruction(fSecondJump);
  12359. taicpu(fThirdJump).opcode := A_JCC;
  12360. taicpu(fThirdJump).condition := condition;
  12361. end;
  12362. else
  12363. InternalError(2023110720);
  12364. end;
  12365. { Now we can safely decrement the reference count }
  12366. tasmlabel(fLabel).decrefs;
  12367. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12368. { Remove the original jump }
  12369. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12370. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12371. fState := tsProcessed;
  12372. end;
  12373. {$endif 8086}
  12374. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12375. var
  12376. hp1,hp2: tai;
  12377. carryadd_opcode : TAsmOp;
  12378. symbol: TAsmSymbol;
  12379. increg, tmpreg: TRegister;
  12380. {$ifndef i8086}
  12381. CMOVTracking: PCMOVTracking;
  12382. hp3,hp4,hp5: tai;
  12383. {$endif i8086}
  12384. TempBool: Boolean;
  12385. begin
  12386. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12387. DoJumpOptimizations(p, TempBool) then
  12388. Exit(True);
  12389. result:=false;
  12390. if GetNextInstruction(p,hp1) then
  12391. begin
  12392. if (hp1.typ=ait_label) then
  12393. begin
  12394. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12395. Exit;
  12396. end
  12397. else if (hp1.typ<>ait_instruction) then
  12398. Exit;
  12399. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12400. if (
  12401. (
  12402. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12403. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12404. (Taicpu(hp1).oper[0]^.val=1)
  12405. ) or
  12406. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12407. ) and
  12408. GetNextInstruction(hp1,hp2) and
  12409. (hp2.typ = ait_label) and
  12410. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  12411. { jb @@1 cmc
  12412. inc/dec operand --> adc/sbb operand,0
  12413. @@1:
  12414. ... and ...
  12415. jnb @@1
  12416. inc/dec operand --> adc/sbb operand,0
  12417. @@1: }
  12418. begin
  12419. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12420. begin
  12421. case taicpu(hp1).opcode of
  12422. A_INC,
  12423. A_ADD:
  12424. carryadd_opcode:=A_ADC;
  12425. A_DEC,
  12426. A_SUB:
  12427. carryadd_opcode:=A_SBB;
  12428. else
  12429. InternalError(2021011001);
  12430. end;
  12431. Taicpu(p).clearop(0);
  12432. Taicpu(p).ops:=0;
  12433. Taicpu(p).is_jmp:=false;
  12434. Taicpu(p).opcode:=A_CMC;
  12435. Taicpu(p).condition:=C_NONE;
  12436. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12437. Taicpu(hp1).ops:=2;
  12438. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12439. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12440. else
  12441. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12442. Taicpu(hp1).loadconst(0,0);
  12443. Taicpu(hp1).opcode:=carryadd_opcode;
  12444. result:=true;
  12445. exit;
  12446. end
  12447. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12448. begin
  12449. case taicpu(hp1).opcode of
  12450. A_INC,
  12451. A_ADD:
  12452. carryadd_opcode:=A_ADC;
  12453. A_DEC,
  12454. A_SUB:
  12455. carryadd_opcode:=A_SBB;
  12456. else
  12457. InternalError(2021011002);
  12458. end;
  12459. Taicpu(hp1).ops:=2;
  12460. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12461. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12462. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12463. else
  12464. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12465. Taicpu(hp1).loadconst(0,0);
  12466. Taicpu(hp1).opcode:=carryadd_opcode;
  12467. RemoveCurrentP(p, hp1);
  12468. result:=true;
  12469. exit;
  12470. end
  12471. {
  12472. jcc @@1 setcc tmpreg
  12473. inc/dec/add/sub operand -> (movzx tmpreg)
  12474. @@1: add/sub tmpreg,operand
  12475. While this increases code size slightly, it makes the code much faster if the
  12476. jump is unpredictable
  12477. }
  12478. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12479. begin
  12480. { search for an available register which is volatile }
  12481. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12482. if increg <> NR_NO then
  12483. begin
  12484. { We don't need to check if tmpreg is in hp1 or not, because
  12485. it will be marked as in use at p (if not, this is
  12486. indictive of a compiler bug). }
  12487. TAsmLabel(symbol).decrefs;
  12488. Taicpu(p).clearop(0);
  12489. Taicpu(p).ops:=1;
  12490. Taicpu(p).is_jmp:=false;
  12491. Taicpu(p).opcode:=A_SETcc;
  12492. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12493. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12494. Taicpu(p).loadreg(0,increg);
  12495. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12496. begin
  12497. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12498. R_SUBW:
  12499. begin
  12500. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12501. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12502. end;
  12503. R_SUBD:
  12504. begin
  12505. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12506. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12507. end;
  12508. {$ifdef x86_64}
  12509. R_SUBQ:
  12510. begin
  12511. { MOVZX doesn't have a 64-bit variant, because
  12512. the 32-bit version implicitly zeroes the
  12513. upper 32-bits of the destination register }
  12514. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12515. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12516. setsubreg(tmpreg, R_SUBQ);
  12517. end;
  12518. {$endif x86_64}
  12519. else
  12520. Internalerror(2020030601);
  12521. end;
  12522. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12523. asml.InsertAfter(hp2,p);
  12524. end
  12525. else
  12526. tmpreg := increg;
  12527. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12528. begin
  12529. Taicpu(hp1).ops:=2;
  12530. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12531. end;
  12532. Taicpu(hp1).loadreg(0,tmpreg);
  12533. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12534. Result := True;
  12535. { p is no longer a Jcc instruction, so exit }
  12536. Exit;
  12537. end;
  12538. end;
  12539. end;
  12540. { Detect the following:
  12541. jmp<cond> @Lbl1
  12542. jmp @Lbl2
  12543. ...
  12544. @Lbl1:
  12545. ret
  12546. Change to:
  12547. jmp<inv_cond> @Lbl2
  12548. ret
  12549. }
  12550. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12551. begin
  12552. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12553. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12554. MatchInstruction(hp2,A_RET,[S_NO]) then
  12555. begin
  12556. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12557. { Change label address to that of the unconditional jump }
  12558. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12559. TAsmLabel(symbol).DecRefs;
  12560. taicpu(hp1).opcode := A_RET;
  12561. taicpu(hp1).is_jmp := false;
  12562. taicpu(hp1).ops := taicpu(hp2).ops;
  12563. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12564. case taicpu(hp2).ops of
  12565. 0:
  12566. taicpu(hp1).clearop(0);
  12567. 1:
  12568. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12569. else
  12570. internalerror(2016041302);
  12571. end;
  12572. end;
  12573. {$ifndef i8086}
  12574. end
  12575. {
  12576. convert
  12577. j<c> .L1
  12578. mov 1,reg
  12579. jmp .L2
  12580. .L1
  12581. mov 0,reg
  12582. .L2
  12583. into
  12584. mov 0,reg
  12585. set<not(c)> reg
  12586. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12587. would destroy the flag contents
  12588. }
  12589. else if MatchInstruction(hp1,A_MOV,[]) and
  12590. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12591. {$ifdef i386}
  12592. (
  12593. { Under i386, ESI, EDI, EBP and ESP
  12594. don't have an 8-bit representation }
  12595. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12596. ) and
  12597. {$endif i386}
  12598. (taicpu(hp1).oper[0]^.val=1) and
  12599. GetNextInstruction(hp1,hp2) and
  12600. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12601. GetNextInstruction(hp2,hp3) and
  12602. (hp3.typ=ait_label) and
  12603. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12604. (tai_label(hp3).labsym.getrefs=1) and
  12605. GetNextInstruction(hp3,hp4) and
  12606. MatchInstruction(hp4,A_MOV,[]) and
  12607. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12608. (taicpu(hp4).oper[0]^.val=0) and
  12609. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12610. GetNextInstruction(hp4,hp5) and
  12611. (hp5.typ=ait_label) and
  12612. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12613. (tai_label(hp5).labsym.getrefs=1) then
  12614. begin
  12615. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12616. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12617. { remove last label }
  12618. RemoveInstruction(hp5);
  12619. { remove second label }
  12620. RemoveInstruction(hp3);
  12621. { remove jmp }
  12622. RemoveInstruction(hp2);
  12623. if taicpu(hp1).opsize=S_B then
  12624. RemoveInstruction(hp1)
  12625. else
  12626. taicpu(hp1).loadconst(0,0);
  12627. taicpu(hp4).opcode:=A_SETcc;
  12628. taicpu(hp4).opsize:=S_B;
  12629. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12630. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12631. taicpu(hp4).opercnt:=1;
  12632. taicpu(hp4).ops:=1;
  12633. taicpu(hp4).freeop(1);
  12634. RemoveCurrentP(p);
  12635. Result:=true;
  12636. exit;
  12637. end
  12638. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12639. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12640. begin
  12641. { check for
  12642. jCC xxx
  12643. <several movs>
  12644. xxx:
  12645. Also spot:
  12646. Jcc xxx
  12647. <several movs>
  12648. jmp xxx
  12649. Change to:
  12650. <several cmovs with inverted condition>
  12651. jmp xxx (only for the 2nd case)
  12652. }
  12653. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12654. if CMOVTracking^.State <> tsInvalid then
  12655. begin
  12656. CMovTracking^.Process(p);
  12657. Result := True;
  12658. end;
  12659. CMOVTracking^.Done;
  12660. {$endif i8086}
  12661. end;
  12662. end;
  12663. end;
  12664. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12665. var
  12666. hp1,hp2,hp3: tai;
  12667. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12668. NewSize: TOpSize;
  12669. NewRegSize: TSubRegister;
  12670. Limit: TCgInt;
  12671. SwapOper: POper;
  12672. begin
  12673. result:=false;
  12674. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12675. GetNextInstruction(p,hp1) and
  12676. (hp1.typ = ait_instruction);
  12677. if reg_and_hp1_is_instr and
  12678. (
  12679. (taicpu(hp1).opcode <> A_LEA) or
  12680. { If the LEA instruction can be converted into an arithmetic instruction,
  12681. it may be possible to then fold it. }
  12682. (
  12683. { If the flags register is in use, don't change the instruction
  12684. to an ADD otherwise this will scramble the flags. [Kit] }
  12685. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12686. ConvertLEA(taicpu(hp1))
  12687. )
  12688. ) and
  12689. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12690. GetNextInstruction(hp1,hp2) and
  12691. MatchInstruction(hp2,A_MOV,[]) and
  12692. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12693. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12694. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12695. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12696. {$ifdef i386}
  12697. { not all registers have byte size sub registers on i386 }
  12698. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12699. {$endif i386}
  12700. (((taicpu(hp1).ops=2) and
  12701. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12702. ((taicpu(hp1).ops=1) and
  12703. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12704. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12705. begin
  12706. { change movsX/movzX reg/ref, reg2
  12707. add/sub/or/... reg3/$const, reg2
  12708. mov reg2 reg/ref
  12709. to add/sub/or/... reg3/$const, reg/ref }
  12710. { by example:
  12711. movswl %si,%eax movswl %si,%eax p
  12712. decl %eax addl %edx,%eax hp1
  12713. movw %ax,%si movw %ax,%si hp2
  12714. ->
  12715. movswl %si,%eax movswl %si,%eax p
  12716. decw %eax addw %edx,%eax hp1
  12717. movw %ax,%si movw %ax,%si hp2
  12718. }
  12719. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12720. {
  12721. ->
  12722. movswl %si,%eax movswl %si,%eax p
  12723. decw %si addw %dx,%si hp1
  12724. movw %ax,%si movw %ax,%si hp2
  12725. }
  12726. case taicpu(hp1).ops of
  12727. 1:
  12728. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12729. 2:
  12730. begin
  12731. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12732. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12733. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12734. end;
  12735. else
  12736. internalerror(2008042702);
  12737. end;
  12738. {
  12739. ->
  12740. decw %si addw %dx,%si p
  12741. }
  12742. DebugMsg(SPeepholeOptimization + 'var3',p);
  12743. RemoveCurrentP(p, hp1);
  12744. RemoveInstruction(hp2);
  12745. Result := True;
  12746. Exit;
  12747. end;
  12748. if reg_and_hp1_is_instr and
  12749. (taicpu(hp1).opcode = A_MOV) and
  12750. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12751. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12752. {$ifdef x86_64}
  12753. { check for implicit extension to 64 bit }
  12754. or
  12755. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12756. (taicpu(hp1).opsize=S_Q) and
  12757. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  12758. )
  12759. {$endif x86_64}
  12760. )
  12761. then
  12762. begin
  12763. { change
  12764. movx %reg1,%reg2
  12765. mov %reg2,%reg3
  12766. dealloc %reg2
  12767. into
  12768. movx %reg,%reg3
  12769. }
  12770. TransferUsedRegs(TmpUsedRegs);
  12771. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12772. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  12773. begin
  12774. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  12775. {$ifdef x86_64}
  12776. if (taicpu(p).opsize in [S_BL,S_WL]) and
  12777. (taicpu(hp1).opsize=S_Q) then
  12778. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  12779. else
  12780. {$endif x86_64}
  12781. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  12782. RemoveInstruction(hp1);
  12783. Result := True;
  12784. Exit;
  12785. end;
  12786. end;
  12787. if reg_and_hp1_is_instr and
  12788. ((taicpu(hp1).opcode=A_MOV) or
  12789. (taicpu(hp1).opcode=A_ADD) or
  12790. (taicpu(hp1).opcode=A_SUB) or
  12791. (taicpu(hp1).opcode=A_CMP) or
  12792. (taicpu(hp1).opcode=A_OR) or
  12793. (taicpu(hp1).opcode=A_XOR) or
  12794. (taicpu(hp1).opcode=A_AND)
  12795. ) and
  12796. (taicpu(hp1).oper[1]^.typ = top_reg) then
  12797. begin
  12798. AndTest := (taicpu(hp1).opcode=A_AND) and
  12799. GetNextInstruction(hp1, hp2) and
  12800. (hp2.typ = ait_instruction) and
  12801. (
  12802. (
  12803. (taicpu(hp2).opcode=A_TEST) and
  12804. (
  12805. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  12806. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  12807. (
  12808. { If the AND and TEST instructions share a constant, this is also valid }
  12809. (taicpu(hp1).oper[0]^.typ = top_const) and
  12810. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  12811. )
  12812. ) and
  12813. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12814. ) or
  12815. (
  12816. (taicpu(hp2).opcode=A_CMP) and
  12817. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  12818. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12819. )
  12820. );
  12821. { change
  12822. movx (oper),%reg2
  12823. and $x,%reg2
  12824. test %reg2,%reg2
  12825. dealloc %reg2
  12826. into
  12827. op %reg1,%reg3
  12828. if the second op accesses only the bits stored in reg1
  12829. }
  12830. if ((taicpu(p).oper[0]^.typ=top_reg) or
  12831. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  12832. (taicpu(hp1).oper[0]^.typ = top_const) and
  12833. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12834. AndTest then
  12835. begin
  12836. { Check if the AND constant is in range }
  12837. case taicpu(p).opsize of
  12838. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12839. begin
  12840. NewSize := S_B;
  12841. Limit := $FF;
  12842. end;
  12843. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12844. begin
  12845. NewSize := S_W;
  12846. Limit := $FFFF;
  12847. end;
  12848. {$ifdef x86_64}
  12849. S_LQ:
  12850. begin
  12851. NewSize := S_L;
  12852. Limit := $FFFFFFFF;
  12853. end;
  12854. {$endif x86_64}
  12855. else
  12856. InternalError(2021120303);
  12857. end;
  12858. if (
  12859. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  12860. { Check for negative operands }
  12861. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  12862. ) and
  12863. GetNextInstruction(hp2,hp3) and
  12864. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  12865. (taicpu(hp3).condition in [C_E,C_NE]) then
  12866. begin
  12867. TransferUsedRegs(TmpUsedRegs);
  12868. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12869. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12870. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  12871. begin
  12872. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  12873. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12874. taicpu(hp1).opcode := A_TEST;
  12875. taicpu(hp1).opsize := NewSize;
  12876. RemoveInstruction(hp2);
  12877. RemoveCurrentP(p, hp1);
  12878. Result:=true;
  12879. exit;
  12880. end;
  12881. end;
  12882. end;
  12883. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12884. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  12885. (taicpu(hp1).opsize=S_B)) or
  12886. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  12887. (taicpu(hp1).opsize=S_W))
  12888. {$ifdef x86_64}
  12889. or ((taicpu(p).opsize=S_LQ) and
  12890. (taicpu(hp1).opsize=S_L))
  12891. {$endif x86_64}
  12892. ) and
  12893. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  12894. begin
  12895. { change
  12896. movx %reg1,%reg2
  12897. op %reg2,%reg3
  12898. dealloc %reg2
  12899. into
  12900. op %reg1,%reg3
  12901. if the second op accesses only the bits stored in reg1
  12902. }
  12903. TransferUsedRegs(TmpUsedRegs);
  12904. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12905. if AndTest then
  12906. begin
  12907. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12908. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12909. end
  12910. else
  12911. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12912. if not RegUsed then
  12913. begin
  12914. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  12915. if taicpu(p).oper[0]^.typ=top_reg then
  12916. begin
  12917. case taicpu(hp1).opsize of
  12918. S_B:
  12919. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  12920. S_W:
  12921. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  12922. S_L:
  12923. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  12924. else
  12925. Internalerror(2020102301);
  12926. end;
  12927. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  12928. end
  12929. else
  12930. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  12931. RemoveCurrentP(p);
  12932. if AndTest then
  12933. RemoveInstruction(hp2);
  12934. result:=true;
  12935. exit;
  12936. end;
  12937. end
  12938. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12939. (
  12940. { Bitwise operations only }
  12941. (taicpu(hp1).opcode=A_AND) or
  12942. (taicpu(hp1).opcode=A_TEST) or
  12943. (
  12944. (taicpu(hp1).oper[0]^.typ = top_const) and
  12945. (
  12946. (taicpu(hp1).opcode=A_OR) or
  12947. (taicpu(hp1).opcode=A_XOR)
  12948. )
  12949. )
  12950. ) and
  12951. (
  12952. (taicpu(hp1).oper[0]^.typ = top_const) or
  12953. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  12954. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  12955. ) then
  12956. begin
  12957. { change
  12958. movx %reg2,%reg2
  12959. op const,%reg2
  12960. into
  12961. op const,%reg2 (smaller version)
  12962. movx %reg2,%reg2
  12963. also change
  12964. movx %reg1,%reg2
  12965. and/test (oper),%reg2
  12966. dealloc %reg2
  12967. into
  12968. and/test (oper),%reg1
  12969. }
  12970. case taicpu(p).opsize of
  12971. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12972. begin
  12973. NewSize := S_B;
  12974. NewRegSize := R_SUBL;
  12975. Limit := $FF;
  12976. end;
  12977. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12978. begin
  12979. NewSize := S_W;
  12980. NewRegSize := R_SUBW;
  12981. Limit := $FFFF;
  12982. end;
  12983. {$ifdef x86_64}
  12984. S_LQ:
  12985. begin
  12986. NewSize := S_L;
  12987. NewRegSize := R_SUBD;
  12988. Limit := $FFFFFFFF;
  12989. end;
  12990. {$endif x86_64}
  12991. else
  12992. Internalerror(2021120302);
  12993. end;
  12994. TransferUsedRegs(TmpUsedRegs);
  12995. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12996. if AndTest then
  12997. begin
  12998. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12999. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13000. end
  13001. else
  13002. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13003. if
  13004. (
  13005. (taicpu(p).opcode = A_MOVZX) and
  13006. (
  13007. (taicpu(hp1).opcode=A_AND) or
  13008. (taicpu(hp1).opcode=A_TEST)
  13009. ) and
  13010. not (
  13011. { If both are references, then the final instruction will have
  13012. both operands as references, which is not allowed }
  13013. (taicpu(p).oper[0]^.typ = top_ref) and
  13014. (taicpu(hp1).oper[0]^.typ = top_ref)
  13015. ) and
  13016. not RegUsed
  13017. ) or
  13018. (
  13019. (
  13020. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  13021. not RegUsed
  13022. ) and
  13023. (taicpu(p).oper[0]^.typ = top_reg) and
  13024. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13025. (taicpu(hp1).oper[0]^.typ = top_const) and
  13026. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  13027. ) then
  13028. begin
  13029. {$if defined(i386) or defined(i8086)}
  13030. { If the target size is 8-bit, make sure we can actually encode it }
  13031. 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
  13032. Exit;
  13033. {$endif i386 or i8086}
  13034. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  13035. taicpu(hp1).opsize := NewSize;
  13036. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13037. if AndTest then
  13038. begin
  13039. RemoveInstruction(hp2);
  13040. if not RegUsed then
  13041. begin
  13042. taicpu(hp1).opcode := A_TEST;
  13043. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  13044. begin
  13045. { Make sure the reference is the second operand }
  13046. SwapOper := taicpu(hp1).oper[0];
  13047. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  13048. taicpu(hp1).oper[1] := SwapOper;
  13049. end;
  13050. end;
  13051. end;
  13052. case taicpu(hp1).oper[0]^.typ of
  13053. top_reg:
  13054. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  13055. top_const:
  13056. { For the AND/TEST case }
  13057. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  13058. else
  13059. ;
  13060. end;
  13061. if RegUsed then
  13062. begin
  13063. AsmL.Remove(p);
  13064. AsmL.InsertAfter(p, hp1);
  13065. p := hp1;
  13066. end
  13067. else
  13068. RemoveCurrentP(p, hp1);
  13069. result:=true;
  13070. exit;
  13071. end;
  13072. end;
  13073. end;
  13074. if reg_and_hp1_is_instr and
  13075. (taicpu(p).oper[0]^.typ = top_reg) and
  13076. (
  13077. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  13078. ) and
  13079. (taicpu(hp1).oper[0]^.typ = top_const) and
  13080. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13081. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13082. { Minimum shift value allowed is the bit difference between the sizes }
  13083. (taicpu(hp1).oper[0]^.val >=
  13084. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13085. 8 * (
  13086. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  13087. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13088. )
  13089. ) then
  13090. begin
  13091. { For:
  13092. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  13093. shl/sal ##, %reg1
  13094. Remove the movsx/movzx instruction if the shift overwrites the
  13095. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  13096. }
  13097. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  13098. RemoveCurrentP(p, hp1);
  13099. Result := True;
  13100. Exit;
  13101. end
  13102. else if reg_and_hp1_is_instr and
  13103. (taicpu(p).oper[0]^.typ = top_reg) and
  13104. (
  13105. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  13106. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  13107. ) and
  13108. (taicpu(hp1).oper[0]^.typ = top_const) and
  13109. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13110. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13111. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  13112. (taicpu(hp1).oper[0]^.val <
  13113. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13114. 8 * (
  13115. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13116. )
  13117. ) then
  13118. begin
  13119. { For:
  13120. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  13121. sar ##, %reg1 shr ##, %reg1
  13122. Move the shift to before the movx instruction if the shift value
  13123. is not too large.
  13124. }
  13125. asml.Remove(hp1);
  13126. asml.InsertBefore(hp1, p);
  13127. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13128. case taicpu(p).opsize of
  13129. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  13130. taicpu(hp1).opsize := S_B;
  13131. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  13132. taicpu(hp1).opsize := S_W;
  13133. {$ifdef x86_64}
  13134. S_LQ:
  13135. taicpu(hp1).opsize := S_L;
  13136. {$endif}
  13137. else
  13138. InternalError(2020112401);
  13139. end;
  13140. if (taicpu(hp1).opcode = A_SHR) then
  13141. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13142. else
  13143. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13144. Result := True;
  13145. end;
  13146. if reg_and_hp1_is_instr and
  13147. (taicpu(p).oper[0]^.typ = top_reg) and
  13148. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13149. (
  13150. (taicpu(hp1).opcode = taicpu(p).opcode)
  13151. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13152. {$ifdef x86_64}
  13153. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13154. {$endif x86_64}
  13155. ) then
  13156. begin
  13157. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13158. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13159. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13160. begin
  13161. {
  13162. For example:
  13163. movzbw %al,%ax
  13164. movzwl %ax,%eax
  13165. Compress into:
  13166. movzbl %al,%eax
  13167. }
  13168. RegUsed := False;
  13169. case taicpu(p).opsize of
  13170. S_BW:
  13171. case taicpu(hp1).opsize of
  13172. S_WL:
  13173. begin
  13174. taicpu(p).opsize := S_BL;
  13175. RegUsed := True;
  13176. end;
  13177. {$ifdef x86_64}
  13178. S_WQ:
  13179. begin
  13180. if taicpu(p).opcode = A_MOVZX then
  13181. begin
  13182. taicpu(p).opsize := S_BL;
  13183. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13184. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13185. end
  13186. else
  13187. taicpu(p).opsize := S_BQ;
  13188. RegUsed := True;
  13189. end;
  13190. {$endif x86_64}
  13191. else
  13192. ;
  13193. end;
  13194. {$ifdef x86_64}
  13195. S_BL:
  13196. case taicpu(hp1).opsize of
  13197. S_LQ:
  13198. begin
  13199. if taicpu(p).opcode = A_MOVZX then
  13200. begin
  13201. taicpu(p).opsize := S_BL;
  13202. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13203. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13204. end
  13205. else
  13206. taicpu(p).opsize := S_BQ;
  13207. RegUsed := True;
  13208. end;
  13209. else
  13210. ;
  13211. end;
  13212. S_WL:
  13213. case taicpu(hp1).opsize of
  13214. S_LQ:
  13215. begin
  13216. if taicpu(p).opcode = A_MOVZX then
  13217. begin
  13218. taicpu(p).opsize := S_WL;
  13219. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13220. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13221. end
  13222. else
  13223. taicpu(p).opsize := S_WQ;
  13224. RegUsed := True;
  13225. end;
  13226. else
  13227. ;
  13228. end;
  13229. {$endif x86_64}
  13230. else
  13231. ;
  13232. end;
  13233. if RegUsed then
  13234. begin
  13235. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13236. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13237. RemoveInstruction(hp1);
  13238. Result := True;
  13239. Exit;
  13240. end;
  13241. end;
  13242. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13243. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13244. GetNextInstruction(hp1, hp2) and
  13245. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13246. (
  13247. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13248. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13249. {$ifdef x86_64}
  13250. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13251. {$endif x86_64}
  13252. ) and
  13253. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13254. (
  13255. (
  13256. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13257. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13258. ) or
  13259. (
  13260. { Only allow the operands in reverse order for TEST instructions }
  13261. (taicpu(hp2).opcode = A_TEST) and
  13262. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13263. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13264. )
  13265. ) then
  13266. begin
  13267. {
  13268. For example:
  13269. movzbl %al,%eax
  13270. movzbl (ref),%edx
  13271. andl %edx,%eax
  13272. (%edx deallocated)
  13273. Change to:
  13274. andb (ref),%al
  13275. movzbl %al,%eax
  13276. Rules are:
  13277. - First two instructions have the same opcode and opsize
  13278. - First instruction's operands are the same super-register
  13279. - Second instruction operates on a different register
  13280. - Third instruction is AND, OR, XOR or TEST
  13281. - Third instruction's operands are the destination registers of the first two instructions
  13282. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13283. - Second instruction's destination register is deallocated afterwards
  13284. }
  13285. TransferUsedRegs(TmpUsedRegs);
  13286. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13287. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13288. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13289. begin
  13290. case taicpu(p).opsize of
  13291. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13292. NewSize := S_B;
  13293. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13294. NewSize := S_W;
  13295. {$ifdef x86_64}
  13296. S_LQ:
  13297. NewSize := S_L;
  13298. {$endif x86_64}
  13299. else
  13300. InternalError(2021120301);
  13301. end;
  13302. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13303. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13304. taicpu(hp2).opsize := NewSize;
  13305. RemoveInstruction(hp1);
  13306. { With TEST, it's best to keep the MOVX instruction at the top }
  13307. if (taicpu(hp2).opcode <> A_TEST) then
  13308. begin
  13309. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13310. asml.Remove(p);
  13311. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13312. asml.InsertAfter(p, hp2);
  13313. p := hp2;
  13314. end
  13315. else
  13316. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13317. Result := True;
  13318. Exit;
  13319. end;
  13320. end;
  13321. end;
  13322. if taicpu(p).opcode=A_MOVZX then
  13323. begin
  13324. { removes superfluous And's after movzx's }
  13325. if reg_and_hp1_is_instr and
  13326. (taicpu(hp1).opcode = A_AND) and
  13327. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13328. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13329. {$ifdef x86_64}
  13330. { check for implicit extension to 64 bit }
  13331. or
  13332. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13333. (taicpu(hp1).opsize=S_Q) and
  13334. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13335. )
  13336. {$endif x86_64}
  13337. )
  13338. then
  13339. begin
  13340. case taicpu(p).opsize Of
  13341. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13342. if (taicpu(hp1).oper[0]^.val = $ff) then
  13343. begin
  13344. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13345. RemoveInstruction(hp1);
  13346. Result:=true;
  13347. exit;
  13348. end;
  13349. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13350. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13351. begin
  13352. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13353. RemoveInstruction(hp1);
  13354. Result:=true;
  13355. exit;
  13356. end;
  13357. {$ifdef x86_64}
  13358. S_LQ:
  13359. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13360. begin
  13361. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13362. RemoveInstruction(hp1);
  13363. Result:=true;
  13364. exit;
  13365. end;
  13366. {$endif x86_64}
  13367. else
  13368. ;
  13369. end;
  13370. { we cannot get rid of the and, but can we get rid of the movz ?}
  13371. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13372. begin
  13373. case taicpu(p).opsize Of
  13374. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13375. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13376. begin
  13377. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13378. RemoveCurrentP(p,hp1);
  13379. Result:=true;
  13380. exit;
  13381. end;
  13382. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13383. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13384. begin
  13385. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13386. RemoveCurrentP(p,hp1);
  13387. Result:=true;
  13388. exit;
  13389. end;
  13390. {$ifdef x86_64}
  13391. S_LQ:
  13392. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13393. begin
  13394. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13395. RemoveCurrentP(p,hp1);
  13396. Result:=true;
  13397. exit;
  13398. end;
  13399. {$endif x86_64}
  13400. else
  13401. ;
  13402. end;
  13403. end;
  13404. end;
  13405. { changes some movzx constructs to faster synonyms (all examples
  13406. are given with eax/ax, but are also valid for other registers)}
  13407. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13408. begin
  13409. case taicpu(p).opsize of
  13410. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13411. (the machine code is equivalent to movzbl %al,%eax), but the
  13412. code generator still generates that assembler instruction and
  13413. it is silently converted. This should probably be checked.
  13414. [Kit] }
  13415. S_BW:
  13416. begin
  13417. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13418. (
  13419. not IsMOVZXAcceptable
  13420. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13421. or (
  13422. (cs_opt_size in current_settings.optimizerswitches) and
  13423. (taicpu(p).oper[1]^.reg = NR_AX)
  13424. )
  13425. ) then
  13426. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13427. begin
  13428. DebugMsg(SPeepholeOptimization + 'var7',p);
  13429. taicpu(p).opcode := A_AND;
  13430. taicpu(p).changeopsize(S_W);
  13431. taicpu(p).loadConst(0,$ff);
  13432. Result := True;
  13433. end
  13434. else if not IsMOVZXAcceptable and
  13435. GetNextInstruction(p, hp1) and
  13436. (tai(hp1).typ = ait_instruction) and
  13437. (taicpu(hp1).opcode = A_AND) and
  13438. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13439. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13440. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13441. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13442. begin
  13443. DebugMsg(SPeepholeOptimization + 'var8',p);
  13444. taicpu(p).opcode := A_MOV;
  13445. taicpu(p).changeopsize(S_W);
  13446. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13447. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13448. Result := True;
  13449. end;
  13450. end;
  13451. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13452. S_BL:
  13453. if not IsMOVZXAcceptable then
  13454. begin
  13455. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13456. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13457. begin
  13458. DebugMsg(SPeepholeOptimization + 'var9',p);
  13459. taicpu(p).opcode := A_AND;
  13460. taicpu(p).changeopsize(S_L);
  13461. taicpu(p).loadConst(0,$ff);
  13462. Result := True;
  13463. end
  13464. else if GetNextInstruction(p, hp1) and
  13465. (tai(hp1).typ = ait_instruction) and
  13466. (taicpu(hp1).opcode = A_AND) and
  13467. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13468. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13469. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13470. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13471. begin
  13472. DebugMsg(SPeepholeOptimization + 'var10',p);
  13473. taicpu(p).opcode := A_MOV;
  13474. taicpu(p).changeopsize(S_L);
  13475. { do not use R_SUBWHOLE
  13476. as movl %rdx,%eax
  13477. is invalid in assembler PM }
  13478. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13479. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13480. Result := True;
  13481. end;
  13482. end;
  13483. {$endif i8086}
  13484. S_WL:
  13485. if not IsMOVZXAcceptable then
  13486. begin
  13487. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13488. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13489. begin
  13490. DebugMsg(SPeepholeOptimization + 'var11',p);
  13491. taicpu(p).opcode := A_AND;
  13492. taicpu(p).changeopsize(S_L);
  13493. taicpu(p).loadConst(0,$ffff);
  13494. Result := True;
  13495. end
  13496. else if GetNextInstruction(p, hp1) and
  13497. (tai(hp1).typ = ait_instruction) and
  13498. (taicpu(hp1).opcode = A_AND) and
  13499. (taicpu(hp1).oper[0]^.typ = top_const) and
  13500. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13501. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13502. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13503. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13504. begin
  13505. DebugMsg(SPeepholeOptimization + 'var12',p);
  13506. taicpu(p).opcode := A_MOV;
  13507. taicpu(p).changeopsize(S_L);
  13508. { do not use R_SUBWHOLE
  13509. as movl %rdx,%eax
  13510. is invalid in assembler PM }
  13511. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13512. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13513. Result := True;
  13514. end;
  13515. end;
  13516. else
  13517. InternalError(2017050705);
  13518. end;
  13519. end
  13520. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13521. begin
  13522. if GetNextInstruction(p, hp1) and
  13523. (tai(hp1).typ = ait_instruction) and
  13524. (taicpu(hp1).opcode = A_AND) and
  13525. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13526. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13527. begin
  13528. case taicpu(p).opsize Of
  13529. S_BL:
  13530. if (taicpu(hp1).opsize <> S_L) or
  13531. (taicpu(hp1).oper[0]^.val > $FF) then
  13532. begin
  13533. DebugMsg(SPeepholeOptimization + 'var13',p);
  13534. taicpu(hp1).changeopsize(S_L);
  13535. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13536. Include(OptsToCheck, aoc_ForceNewIteration);
  13537. end;
  13538. S_WL:
  13539. if (taicpu(hp1).opsize <> S_L) or
  13540. (taicpu(hp1).oper[0]^.val > $FFFF) then
  13541. begin
  13542. DebugMsg(SPeepholeOptimization + 'var14',p);
  13543. taicpu(hp1).changeopsize(S_L);
  13544. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13545. Include(OptsToCheck, aoc_ForceNewIteration);
  13546. end;
  13547. S_BW:
  13548. if (taicpu(hp1).opsize <> S_W) or
  13549. (taicpu(hp1).oper[0]^.val > $FF) then
  13550. begin
  13551. DebugMsg(SPeepholeOptimization + 'var15',p);
  13552. taicpu(hp1).changeopsize(S_W);
  13553. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13554. Include(OptsToCheck, aoc_ForceNewIteration);
  13555. end;
  13556. else
  13557. Internalerror(2017050704)
  13558. end;
  13559. end;
  13560. end;
  13561. end;
  13562. end;
  13563. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13564. var
  13565. hp1, hp2 : tai;
  13566. MaskLength : Cardinal;
  13567. MaskedBits : TCgInt;
  13568. ActiveReg : TRegister;
  13569. begin
  13570. Result:=false;
  13571. { There are no optimisations for reference targets }
  13572. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13573. Exit;
  13574. while GetNextInstruction(p, hp1) and
  13575. (hp1.typ = ait_instruction) do
  13576. begin
  13577. if (taicpu(p).oper[0]^.typ = top_const) then
  13578. begin
  13579. case taicpu(hp1).opcode of
  13580. A_AND:
  13581. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13582. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13583. { the second register must contain the first one, so compare their subreg types }
  13584. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13585. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13586. { change
  13587. and const1, reg
  13588. and const2, reg
  13589. to
  13590. and (const1 and const2), reg
  13591. }
  13592. begin
  13593. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13594. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13595. RemoveCurrentP(p, hp1);
  13596. Result:=true;
  13597. exit;
  13598. end;
  13599. A_CMP:
  13600. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13601. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13602. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13603. { Just check that the condition on the next instruction is compatible }
  13604. GetNextInstruction(hp1, hp2) and
  13605. (hp2.typ = ait_instruction) and
  13606. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13607. then
  13608. { change
  13609. and 2^n, reg
  13610. cmp 2^n, reg
  13611. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13612. to
  13613. and 2^n, reg
  13614. test reg, reg
  13615. j(~c) / set(~c) / cmov(~c)
  13616. }
  13617. begin
  13618. { Keep TEST instruction in, rather than remove it, because
  13619. it may trigger other optimisations such as MovAndTest2Test }
  13620. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13621. taicpu(hp1).opcode := A_TEST;
  13622. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13623. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13624. Result := True;
  13625. Exit;
  13626. end
  13627. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13628. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13629. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13630. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13631. { change
  13632. and $ff/$ff/$ffff, reg
  13633. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13634. dealloc reg
  13635. to
  13636. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13637. }
  13638. begin
  13639. TransferUsedRegs(TmpUsedRegs);
  13640. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13641. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13642. begin
  13643. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13644. case taicpu(p).oper[0]^.val of
  13645. $ff:
  13646. begin
  13647. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13648. taicpu(hp1).opsize:=S_B;
  13649. end;
  13650. $ffff:
  13651. begin
  13652. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13653. taicpu(hp1).opsize:=S_W;
  13654. end;
  13655. $ffffffff:
  13656. begin
  13657. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13658. taicpu(hp1).opsize:=S_L;
  13659. end;
  13660. else
  13661. Internalerror(2023030401);
  13662. end;
  13663. RemoveCurrentP(p);
  13664. Result := True;
  13665. Exit;
  13666. end;
  13667. end;
  13668. A_MOVZX:
  13669. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13670. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13671. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13672. (
  13673. (
  13674. (taicpu(p).opsize=S_W) and
  13675. (taicpu(hp1).opsize=S_BW)
  13676. ) or
  13677. (
  13678. (taicpu(p).opsize=S_L) and
  13679. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13680. )
  13681. {$ifdef x86_64}
  13682. or
  13683. (
  13684. (taicpu(p).opsize=S_Q) and
  13685. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13686. )
  13687. {$endif x86_64}
  13688. ) then
  13689. begin
  13690. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13691. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13692. ) or
  13693. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13694. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13695. then
  13696. begin
  13697. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13698. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13699. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13700. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13701. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13702. }
  13703. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13704. RemoveInstruction(hp1);
  13705. { See if there are other optimisations possible }
  13706. Continue;
  13707. end;
  13708. end;
  13709. A_SHL:
  13710. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13711. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13712. begin
  13713. {$ifopt R+}
  13714. {$define RANGE_WAS_ON}
  13715. {$R-}
  13716. {$endif}
  13717. { get length of potential and mask }
  13718. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13719. { really a mask? }
  13720. {$ifdef RANGE_WAS_ON}
  13721. {$R+}
  13722. {$endif}
  13723. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13724. { unmasked part shifted out? }
  13725. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13726. begin
  13727. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13728. RemoveCurrentP(p, hp1);
  13729. Result:=true;
  13730. exit;
  13731. end;
  13732. end;
  13733. A_SHR:
  13734. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13735. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13736. (taicpu(hp1).oper[0]^.val <= 63) then
  13737. begin
  13738. { Does SHR combined with the AND cover all the bits?
  13739. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13740. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13741. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13742. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13743. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13744. begin
  13745. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13746. RemoveCurrentP(p, hp1);
  13747. Result := True;
  13748. Exit;
  13749. end;
  13750. end;
  13751. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13752. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13753. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13754. begin
  13755. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13756. (
  13757. (
  13758. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13759. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  13760. ) or (
  13761. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13762. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  13763. {$ifdef x86_64}
  13764. ) or (
  13765. (taicpu(hp1).opsize = S_LQ) and
  13766. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  13767. {$endif x86_64}
  13768. )
  13769. ) then
  13770. begin
  13771. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  13772. begin
  13773. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  13774. RemoveInstruction(hp1);
  13775. { See if there are other optimisations possible }
  13776. Continue;
  13777. end;
  13778. { The super-registers are the same though.
  13779. Note that this change by itself doesn't improve
  13780. code speed, but it opens up other optimisations. }
  13781. {$ifdef x86_64}
  13782. { Convert 64-bit register to 32-bit }
  13783. case taicpu(hp1).opsize of
  13784. S_BQ:
  13785. begin
  13786. taicpu(hp1).opsize := S_BL;
  13787. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13788. end;
  13789. S_WQ:
  13790. begin
  13791. taicpu(hp1).opsize := S_WL;
  13792. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13793. end
  13794. else
  13795. ;
  13796. end;
  13797. {$endif x86_64}
  13798. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  13799. taicpu(hp1).opcode := A_MOVZX;
  13800. { See if there are other optimisations possible }
  13801. Continue;
  13802. end;
  13803. end;
  13804. else
  13805. ;
  13806. end;
  13807. end
  13808. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  13809. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13810. begin
  13811. {$ifdef x86_64}
  13812. if (taicpu(p).opsize = S_Q) then
  13813. begin
  13814. { Never necessary }
  13815. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  13816. RemoveCurrentP(p, hp1);
  13817. Result := True;
  13818. Exit;
  13819. end;
  13820. {$endif x86_64}
  13821. { Forward check to determine necessity of and %reg,%reg }
  13822. TransferUsedRegs(TmpUsedRegs);
  13823. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13824. { Saves on a bunch of dereferences }
  13825. ActiveReg := taicpu(p).oper[1]^.reg;
  13826. case taicpu(hp1).opcode of
  13827. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13828. if (
  13829. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13830. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13831. ) and
  13832. (
  13833. (taicpu(hp1).opcode <> A_MOV) or
  13834. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  13835. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  13836. ) and
  13837. not (
  13838. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  13839. (taicpu(hp1).opcode = A_MOV) and
  13840. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  13841. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  13842. ) and
  13843. (
  13844. (
  13845. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13846. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  13847. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  13848. ) or
  13849. (
  13850. {$ifdef x86_64}
  13851. (
  13852. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  13853. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  13854. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  13855. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  13856. ) and
  13857. {$endif x86_64}
  13858. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  13859. )
  13860. ) then
  13861. begin
  13862. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  13863. RemoveCurrentP(p, hp1);
  13864. Result := True;
  13865. Exit;
  13866. end;
  13867. A_ADD,
  13868. A_AND,
  13869. A_BSF,
  13870. A_BSR,
  13871. A_BTC,
  13872. A_BTR,
  13873. A_BTS,
  13874. A_OR,
  13875. A_SUB,
  13876. A_XOR:
  13877. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  13878. if (
  13879. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13880. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13881. ) and
  13882. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  13883. begin
  13884. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  13885. RemoveCurrentP(p, hp1);
  13886. Result := True;
  13887. Exit;
  13888. end;
  13889. A_CMP,
  13890. A_TEST:
  13891. if (
  13892. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13893. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13894. ) and
  13895. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  13896. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  13897. begin
  13898. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  13899. RemoveCurrentP(p, hp1);
  13900. Result := True;
  13901. Exit;
  13902. end;
  13903. A_BSWAP,
  13904. A_NEG,
  13905. A_NOT:
  13906. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  13907. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  13908. begin
  13909. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  13910. RemoveCurrentP(p, hp1);
  13911. Result := True;
  13912. Exit;
  13913. end;
  13914. else
  13915. ;
  13916. end;
  13917. end;
  13918. if (taicpu(hp1).is_jmp) and
  13919. (taicpu(hp1).opcode<>A_JMP) and
  13920. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  13921. begin
  13922. { change
  13923. and x, reg
  13924. jxx
  13925. to
  13926. test x, reg
  13927. jxx
  13928. if reg is deallocated before the
  13929. jump, but only if it's a conditional jump (PFV)
  13930. }
  13931. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  13932. taicpu(p).opcode := A_TEST;
  13933. Exit;
  13934. end;
  13935. Break;
  13936. end;
  13937. { Lone AND tests }
  13938. if (taicpu(p).oper[0]^.typ = top_const) then
  13939. begin
  13940. {
  13941. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  13942. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  13943. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  13944. }
  13945. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  13946. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  13947. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  13948. begin
  13949. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  13950. if taicpu(p).opsize = S_L then
  13951. begin
  13952. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  13953. Result := True;
  13954. end;
  13955. end;
  13956. end;
  13957. { Backward check to determine necessity of and %reg,%reg }
  13958. if (taicpu(p).oper[0]^.typ = top_reg) and
  13959. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13960. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13961. GetLastInstruction(p, hp2) and
  13962. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  13963. { Check size of adjacent instruction to determine if the AND is
  13964. effectively a null operation }
  13965. (
  13966. (taicpu(p).opsize = taicpu(hp2).opsize) or
  13967. { Note: Don't include S_Q }
  13968. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  13969. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  13970. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  13971. ) then
  13972. begin
  13973. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  13974. { If GetNextInstruction returned False, hp1 will be nil }
  13975. RemoveCurrentP(p, hp1);
  13976. Result := True;
  13977. Exit;
  13978. end;
  13979. end;
  13980. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  13981. var
  13982. hp1, hp2: tai;
  13983. NewRef: TReference;
  13984. Distance: Cardinal;
  13985. TempTracking: TAllUsedRegs;
  13986. { This entire nested function is used in an if-statement below, but we
  13987. want to avoid all the used reg transfers and GetNextInstruction calls
  13988. until we really have to check }
  13989. function MemRegisterNotUsedLater: Boolean; inline;
  13990. var
  13991. hp2: tai;
  13992. begin
  13993. TransferUsedRegs(TmpUsedRegs);
  13994. hp2 := p;
  13995. repeat
  13996. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13997. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13998. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  13999. end;
  14000. begin
  14001. Result := False;
  14002. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14003. (taicpu(p).oper[1]^.typ = top_reg) then
  14004. begin
  14005. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14006. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14007. (hp1.typ <> ait_instruction) or
  14008. not
  14009. (
  14010. (cs_opt_level3 in current_settings.optimizerswitches) or
  14011. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14012. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14013. ) then
  14014. Exit;
  14015. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14016. addq $x, %rax
  14017. movq %rax, %rdx
  14018. sarq $63, %rdx
  14019. (%rax still in use)
  14020. ...letting OptPass2ADD run its course (and without -Os) will produce:
  14021. leaq $x(%rax),%rdx
  14022. addq $x, %rax
  14023. sarq $63, %rdx
  14024. ...which is okay since it breaks the dependency chain between
  14025. addq and movq, but if OptPass2MOV is called first:
  14026. addq $x, %rax
  14027. cqto
  14028. ...which is better in all ways, taking only 2 cycles to execute
  14029. and much smaller in code size.
  14030. }
  14031. { The extra register tracking is quite strenuous }
  14032. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14033. MatchInstruction(hp1, A_MOV, []) then
  14034. begin
  14035. { Update the register tracking to the MOV instruction }
  14036. CopyUsedRegs(TempTracking);
  14037. hp2 := p;
  14038. repeat
  14039. UpdateUsedRegs(tai(hp2.Next));
  14040. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14041. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14042. OptPass2ADD get called again }
  14043. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  14044. begin
  14045. { Reset the tracking to the current instruction }
  14046. RestoreUsedRegs(TempTracking);
  14047. ReleaseUsedRegs(TempTracking);
  14048. Result := True;
  14049. Exit;
  14050. end;
  14051. { Reset the tracking to the current instruction }
  14052. RestoreUsedRegs(TempTracking);
  14053. ReleaseUsedRegs(TempTracking);
  14054. { If OptPass2MOV returned True, we don't need to set Result to
  14055. True if hp1 didn't change because the ADD instruction didn't
  14056. get modified and we'll be evaluating hp1 again when the
  14057. peephole optimizer reaches it }
  14058. end;
  14059. { Change:
  14060. add %reg2,%reg1
  14061. (%reg2 not modified in between)
  14062. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  14063. To:
  14064. mov/s/z #(%reg1,%reg2),%reg1
  14065. }
  14066. if (taicpu(p).oper[0]^.typ = top_reg) and
  14067. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  14068. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  14069. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  14070. (
  14071. (
  14072. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  14073. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  14074. { r/esp cannot be an index }
  14075. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  14076. ) or (
  14077. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  14078. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  14079. )
  14080. ) and (
  14081. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  14082. (
  14083. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  14084. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14085. MemRegisterNotUsedLater
  14086. )
  14087. ) then
  14088. begin
  14089. if (
  14090. { Instructions are guaranteed to be adjacent on -O2 and under }
  14091. (cs_opt_level3 in current_settings.optimizerswitches) and
  14092. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  14093. ) then
  14094. begin
  14095. { If the other register is used in between, move the MOV
  14096. instruction to right after the ADD instruction so a
  14097. saving can still be made }
  14098. Asml.Remove(hp1);
  14099. Asml.InsertAfter(hp1, p);
  14100. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14101. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14102. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  14103. RemoveCurrentp(p, hp1);
  14104. end
  14105. else
  14106. begin
  14107. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  14108. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14109. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14110. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  14111. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14112. { hp1 may not be the immediate next instruction under -O3 }
  14113. RemoveCurrentp(p)
  14114. else
  14115. RemoveCurrentp(p, hp1);
  14116. end;
  14117. Result := True;
  14118. Exit;
  14119. end;
  14120. { Change:
  14121. addl/q $x,%reg1
  14122. movl/q %reg1,%reg2
  14123. To:
  14124. leal/q $x(%reg1),%reg2
  14125. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14126. Breaks the dependency chain.
  14127. }
  14128. if (taicpu(p).oper[0]^.typ = top_const) and
  14129. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14130. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14131. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14132. (
  14133. { Instructions are guaranteed to be adjacent on -O2 and under }
  14134. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14135. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14136. ) then
  14137. begin
  14138. TransferUsedRegs(TmpUsedRegs);
  14139. hp2 := p;
  14140. repeat
  14141. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14142. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14143. if (
  14144. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  14145. not (cs_opt_size in current_settings.optimizerswitches) or
  14146. (
  14147. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14148. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14149. )
  14150. ) then
  14151. begin
  14152. { Change the MOV instruction to a LEA instruction, and update the
  14153. first operand }
  14154. reference_reset(NewRef, 1, []);
  14155. NewRef.base := taicpu(p).oper[1]^.reg;
  14156. NewRef.scalefactor := 1;
  14157. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14158. taicpu(hp1).opcode := A_LEA;
  14159. taicpu(hp1).loadref(0, NewRef);
  14160. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14161. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14162. begin
  14163. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14164. { Move what is now the LEA instruction to before the ADD instruction }
  14165. Asml.Remove(hp1);
  14166. Asml.InsertBefore(hp1, p);
  14167. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14168. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14169. p := hp1;
  14170. end
  14171. else
  14172. begin
  14173. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14174. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14175. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14176. { hp1 may not be the immediate next instruction under -O3 }
  14177. RemoveCurrentp(p)
  14178. else
  14179. RemoveCurrentp(p, hp1);
  14180. end;
  14181. Result := True;
  14182. end;
  14183. end;
  14184. end;
  14185. end;
  14186. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14187. var
  14188. SubReg: TSubRegister;
  14189. hp1, hp2: tai;
  14190. CallJmp: Boolean;
  14191. begin
  14192. Result := False;
  14193. CallJmp := False;
  14194. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14195. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14196. with taicpu(p).oper[0]^.ref^ do
  14197. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14198. if (offset = 0) then
  14199. begin
  14200. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14201. begin
  14202. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14203. taicpu(p).opcode := A_ADD;
  14204. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14205. Result := True;
  14206. end
  14207. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14208. begin
  14209. if (base <> NR_NO) then
  14210. begin
  14211. if (scalefactor <= 1) then
  14212. begin
  14213. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14214. taicpu(p).opcode := A_ADD;
  14215. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14216. Result := True;
  14217. end;
  14218. end
  14219. else
  14220. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14221. if (scalefactor in [2, 4, 8]) then
  14222. begin
  14223. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14224. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14225. taicpu(p).opcode := A_SHL;
  14226. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14227. Result := True;
  14228. end;
  14229. end;
  14230. end
  14231. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14232. lot of latency, so break off the offset if %reg3 is used soon
  14233. afterwards }
  14234. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14235. { If 3-component addresses don't have additional latency, don't
  14236. perform this optimisation }
  14237. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14238. GetNextInstruction(p, hp1) and
  14239. (hp1.typ = ait_instruction) and
  14240. (
  14241. (
  14242. { Permit jumps and calls since they have a larger degree of overhead }
  14243. (
  14244. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14245. (
  14246. { ... unless the register specifies the location }
  14247. (taicpu(hp1).ops > 0) and
  14248. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14249. )
  14250. ) and
  14251. (
  14252. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14253. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14254. )
  14255. )
  14256. or
  14257. (
  14258. { Check up to two instructions ahead }
  14259. GetNextInstruction(hp1, hp2) and
  14260. (hp2.typ = ait_instruction) and
  14261. (
  14262. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14263. (
  14264. { Same as above }
  14265. (taicpu(hp2).ops > 0) and
  14266. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14267. )
  14268. ) and
  14269. (
  14270. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14271. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14272. )
  14273. )
  14274. ) then
  14275. begin
  14276. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14277. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14278. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14279. offset := 0;
  14280. if Assigned(symbol) or Assigned(relsymbol) then
  14281. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14282. else
  14283. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14284. { Inserting before the next instruction rather than after the
  14285. current instruction gives more accurate register tracking }
  14286. asml.InsertBefore(hp2, hp1);
  14287. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14288. Result := True;
  14289. end;
  14290. end;
  14291. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14292. var
  14293. hp1, hp2: tai;
  14294. NewRef: TReference;
  14295. Distance: Cardinal;
  14296. TempTracking: TAllUsedRegs;
  14297. begin
  14298. Result := False;
  14299. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14300. MatchOpType(taicpu(p),top_const,top_reg) then
  14301. begin
  14302. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14303. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14304. (hp1.typ <> ait_instruction) or
  14305. not
  14306. (
  14307. (cs_opt_level3 in current_settings.optimizerswitches) or
  14308. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14309. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14310. ) then
  14311. Exit;
  14312. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14313. subq $x, %rax
  14314. movq %rax, %rdx
  14315. sarq $63, %rdx
  14316. (%rax still in use)
  14317. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14318. leaq $-x(%rax),%rdx
  14319. movq $x, %rax
  14320. sarq $63, %rdx
  14321. ...which is okay since it breaks the dependency chain between
  14322. subq and movq, but if OptPass2MOV is called first:
  14323. subq $x, %rax
  14324. cqto
  14325. ...which is better in all ways, taking only 2 cycles to execute
  14326. and much smaller in code size.
  14327. }
  14328. { The extra register tracking is quite strenuous }
  14329. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14330. MatchInstruction(hp1, A_MOV, []) then
  14331. begin
  14332. { Update the register tracking to the MOV instruction }
  14333. CopyUsedRegs(TempTracking);
  14334. hp2 := p;
  14335. repeat
  14336. UpdateUsedRegs(tai(hp2.Next));
  14337. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14338. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14339. OptPass2SUB get called again }
  14340. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  14341. begin
  14342. { Reset the tracking to the current instruction }
  14343. RestoreUsedRegs(TempTracking);
  14344. ReleaseUsedRegs(TempTracking);
  14345. Result := True;
  14346. Exit;
  14347. end;
  14348. { Reset the tracking to the current instruction }
  14349. RestoreUsedRegs(TempTracking);
  14350. ReleaseUsedRegs(TempTracking);
  14351. { If OptPass2MOV returned True, we don't need to set Result to
  14352. True if hp1 didn't change because the SUB instruction didn't
  14353. get modified and we'll be evaluating hp1 again when the
  14354. peephole optimizer reaches it }
  14355. end;
  14356. { Change:
  14357. subl/q $x,%reg1
  14358. movl/q %reg1,%reg2
  14359. To:
  14360. leal/q $-x(%reg1),%reg2
  14361. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14362. Breaks the dependency chain and potentially permits the removal of
  14363. a CMP instruction if one follows.
  14364. }
  14365. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14366. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14367. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14368. (
  14369. { Instructions are guaranteed to be adjacent on -O2 and under }
  14370. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14371. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14372. ) then
  14373. begin
  14374. TransferUsedRegs(TmpUsedRegs);
  14375. hp2 := p;
  14376. repeat
  14377. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14378. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14379. if (
  14380. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14381. not (cs_opt_size in current_settings.optimizerswitches) or
  14382. (
  14383. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14384. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14385. )
  14386. ) then
  14387. begin
  14388. { Change the MOV instruction to a LEA instruction, and update the
  14389. first operand }
  14390. reference_reset(NewRef, 1, []);
  14391. NewRef.base := taicpu(p).oper[1]^.reg;
  14392. NewRef.scalefactor := 1;
  14393. NewRef.offset := -taicpu(p).oper[0]^.val;
  14394. taicpu(hp1).opcode := A_LEA;
  14395. taicpu(hp1).loadref(0, NewRef);
  14396. TransferUsedRegs(TmpUsedRegs);
  14397. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14398. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14399. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14400. begin
  14401. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14402. { Move what is now the LEA instruction to before the SUB instruction }
  14403. Asml.Remove(hp1);
  14404. Asml.InsertBefore(hp1, p);
  14405. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14406. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14407. p := hp1;
  14408. end
  14409. else
  14410. begin
  14411. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14412. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14413. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14414. { hp1 may not be the immediate next instruction under -O3 }
  14415. RemoveCurrentp(p)
  14416. else
  14417. RemoveCurrentp(p, hp1);
  14418. end;
  14419. Result := True;
  14420. end;
  14421. end;
  14422. end;
  14423. end;
  14424. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14425. begin
  14426. { we can skip all instructions not messing with the stack pointer }
  14427. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14428. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14429. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14430. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14431. ({(taicpu(hp1).ops=0) or }
  14432. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14433. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14434. ) and }
  14435. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14436. )
  14437. ) do
  14438. GetNextInstruction(hp1,hp1);
  14439. Result:=assigned(hp1);
  14440. end;
  14441. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14442. var
  14443. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14444. begin
  14445. Result:=false;
  14446. hp5:=nil;
  14447. hp6:=nil;
  14448. hp7:=nil;
  14449. hp8:=nil;
  14450. { replace
  14451. leal(q) x(<stackpointer>),<stackpointer>
  14452. <optional .seh_stackalloc ...>
  14453. <optional .seh_endprologue ...>
  14454. call procname
  14455. <optional NOP>
  14456. leal(q) -x(<stackpointer>),<stackpointer>
  14457. <optional VZEROUPPER>
  14458. ret
  14459. by
  14460. jmp procname
  14461. but do it only on level 4 because it destroys stack back traces
  14462. }
  14463. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14464. MatchOpType(taicpu(p),top_ref,top_reg) and
  14465. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14466. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14467. { the -8, -24, -40 are not required, but bail out early if possible,
  14468. higher values are unlikely }
  14469. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14470. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14471. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14472. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14473. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14474. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14475. GetNextInstruction(p, hp1) and
  14476. { Take a copy of hp1 }
  14477. SetAndTest(hp1, hp4) and
  14478. { trick to skip label }
  14479. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14480. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14481. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14482. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14483. SkipSimpleInstructions(hp1) and
  14484. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14485. GetNextInstruction(hp1, hp2) and
  14486. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14487. { skip nop instruction on win64 }
  14488. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14489. SetAndTest(hp2,hp6) and
  14490. GetNextInstruction(hp2,hp2) and
  14491. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14492. ) and
  14493. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14494. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14495. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14496. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14497. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14498. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14499. { Segment register will be NR_NO }
  14500. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14501. GetNextInstruction(hp2, hp3) and
  14502. { trick to skip label }
  14503. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14504. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14505. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14506. SetAndTest(hp3,hp5) and
  14507. GetNextInstruction(hp3,hp3) and
  14508. MatchInstruction(hp3,A_RET,[S_NO])
  14509. )
  14510. ) and
  14511. (taicpu(hp3).ops=0) then
  14512. begin
  14513. taicpu(hp1).opcode := A_JMP;
  14514. taicpu(hp1).is_jmp := true;
  14515. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14516. { search for the stackalloc directive and remove it }
  14517. hp7:=tai(p.next);
  14518. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14519. begin
  14520. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14521. begin
  14522. { sanity check }
  14523. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14524. Internalerror(2024012201);
  14525. hp8:=tai(hp7.next);
  14526. RemoveInstruction(tai(hp7));
  14527. hp7:=hp8;
  14528. break;
  14529. end
  14530. else
  14531. hp7:=tai(hp7.next);
  14532. end;
  14533. RemoveCurrentP(p, hp4);
  14534. RemoveInstruction(hp2);
  14535. RemoveInstruction(hp3);
  14536. { if there is a vzeroupper instruction then move it before the jmp }
  14537. if Assigned(hp5) then
  14538. begin
  14539. AsmL.Remove(hp5);
  14540. ASmL.InsertBefore(hp5,hp1)
  14541. end;
  14542. { remove nop on win64 }
  14543. if Assigned(hp6) then
  14544. RemoveInstruction(hp6);
  14545. Result:=true;
  14546. end;
  14547. end;
  14548. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14549. {$ifdef x86_64}
  14550. var
  14551. hp1, hp2, hp3, hp4, hp5: tai;
  14552. {$endif x86_64}
  14553. begin
  14554. Result:=false;
  14555. {$ifdef x86_64}
  14556. hp5:=nil;
  14557. { replace
  14558. push %rax
  14559. call procname
  14560. pop %rcx
  14561. ret
  14562. by
  14563. jmp procname
  14564. but do it only on level 4 because it destroys stack back traces
  14565. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14566. for all supported calling conventions
  14567. }
  14568. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14569. MatchOpType(taicpu(p),top_reg) and
  14570. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14571. GetNextInstruction(p, hp1) and
  14572. { Take a copy of hp1 }
  14573. SetAndTest(hp1, hp4) and
  14574. { trick to skip label }
  14575. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14576. SkipSimpleInstructions(hp1) and
  14577. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14578. GetNextInstruction(hp1, hp2) and
  14579. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14580. MatchOpType(taicpu(hp2),top_reg) and
  14581. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14582. GetNextInstruction(hp2, hp3) and
  14583. { trick to skip label }
  14584. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14585. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14586. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14587. SetAndTest(hp3,hp5) and
  14588. GetNextInstruction(hp3,hp3) and
  14589. MatchInstruction(hp3,A_RET,[S_NO])
  14590. )
  14591. ) and
  14592. (taicpu(hp3).ops=0) then
  14593. begin
  14594. taicpu(hp1).opcode := A_JMP;
  14595. taicpu(hp1).is_jmp := true;
  14596. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14597. RemoveCurrentP(p, hp4);
  14598. RemoveInstruction(hp2);
  14599. RemoveInstruction(hp3);
  14600. if Assigned(hp5) then
  14601. begin
  14602. AsmL.Remove(hp5);
  14603. ASmL.InsertBefore(hp5,hp1)
  14604. end;
  14605. Result:=true;
  14606. end;
  14607. {$endif x86_64}
  14608. end;
  14609. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14610. var
  14611. Value, RegName: string;
  14612. hp1: tai;
  14613. begin
  14614. Result:=false;
  14615. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14616. begin
  14617. case taicpu(p).oper[0]^.val of
  14618. 0:
  14619. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14620. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14621. (
  14622. { See if we can still convert the instruction }
  14623. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14624. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14625. ) then
  14626. begin
  14627. { change "mov $0,%reg" into "xor %reg,%reg" }
  14628. taicpu(p).opcode := A_XOR;
  14629. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14630. Result := True;
  14631. {$ifdef x86_64}
  14632. end
  14633. else if (taicpu(p).opsize = S_Q) then
  14634. begin
  14635. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14636. { The actual optimization }
  14637. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14638. taicpu(p).changeopsize(S_L);
  14639. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14640. Result := True;
  14641. end;
  14642. $1..$FFFFFFFF:
  14643. begin
  14644. { Code size reduction by J. Gareth "Kit" Moreton }
  14645. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14646. case taicpu(p).opsize of
  14647. S_Q:
  14648. begin
  14649. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14650. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14651. { The actual optimization }
  14652. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14653. taicpu(p).changeopsize(S_L);
  14654. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14655. Result := True;
  14656. end;
  14657. else
  14658. { Do nothing };
  14659. end;
  14660. {$endif x86_64}
  14661. end;
  14662. -1:
  14663. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14664. if (cs_opt_size in current_settings.optimizerswitches) and
  14665. (taicpu(p).opsize <> S_B) and
  14666. (
  14667. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14668. (
  14669. { See if we can still convert the instruction }
  14670. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14671. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14672. )
  14673. ) then
  14674. begin
  14675. { change "mov $-1,%reg" into "or $-1,%reg" }
  14676. { NOTES:
  14677. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14678. - This operation creates a false dependency on the register, so only do it when optimising for size
  14679. - 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
  14680. }
  14681. taicpu(p).opcode := A_OR;
  14682. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14683. Result := True;
  14684. end;
  14685. else
  14686. { Do nothing };
  14687. end;
  14688. end;
  14689. end;
  14690. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14691. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14692. begin
  14693. Result := False;
  14694. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14695. Exit;
  14696. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14697. so don't bother optimising }
  14698. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14699. Exit;
  14700. if (taicpu(p).oper[0]^.typ <> top_const) or
  14701. { If the value can fit into an 8-bit signed integer, a smaller
  14702. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14703. falls within this range }
  14704. (
  14705. (taicpu(p).oper[0]^.val > -128) and
  14706. (taicpu(p).oper[0]^.val <= 127)
  14707. ) then
  14708. Exit;
  14709. { If we're optimising for size, this is acceptable }
  14710. if (cs_opt_size in current_settings.optimizerswitches) then
  14711. Exit(True);
  14712. if (taicpu(p).oper[1]^.typ = top_reg) and
  14713. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14714. Exit(True);
  14715. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14716. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14717. Exit(True);
  14718. end;
  14719. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14720. var
  14721. hp1: tai;
  14722. Value: TCGInt;
  14723. begin
  14724. Result := False;
  14725. if MatchOpType(taicpu(p), top_const, top_reg) then
  14726. begin
  14727. { Detect:
  14728. andw x, %ax (0 <= x < $8000)
  14729. ...
  14730. movzwl %ax,%eax
  14731. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14732. }
  14733. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  14734. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  14735. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  14736. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  14737. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  14738. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  14739. begin
  14740. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  14741. taicpu(hp1).opcode := A_CWDE;
  14742. taicpu(hp1).clearop(0);
  14743. taicpu(hp1).clearop(1);
  14744. taicpu(hp1).ops := 0;
  14745. { A change was made, but not with p, so don't set Result, but
  14746. notify the compiler that a change was made }
  14747. Include(OptsToCheck, aoc_ForceNewIteration);
  14748. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  14749. end;
  14750. end;
  14751. { If "not x" is a power of 2 (popcnt = 1), change:
  14752. and $x, %reg/ref
  14753. To:
  14754. btr lb(x), %reg/ref
  14755. }
  14756. if IsBTXAcceptable(p) and
  14757. (
  14758. { Make sure a TEST doesn't follow that plays with the register }
  14759. not GetNextInstruction(p, hp1) or
  14760. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  14761. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  14762. ) then
  14763. begin
  14764. {$push}{$R-}{$Q-}
  14765. { Value is a sign-extended 32-bit integer - just correct it
  14766. if it's represented as an unsigned value. Also, IsBTXAcceptable
  14767. checks to see if this operand is an immediate. }
  14768. Value := not taicpu(p).oper[0]^.val;
  14769. {$pop}
  14770. {$ifdef x86_64}
  14771. if taicpu(p).opsize = S_L then
  14772. {$endif x86_64}
  14773. Value := Value and $FFFFFFFF;
  14774. if (PopCnt(QWord(Value)) = 1) then
  14775. begin
  14776. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  14777. taicpu(p).opcode := A_BTR;
  14778. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  14779. Result := True;
  14780. Exit;
  14781. end;
  14782. end;
  14783. end;
  14784. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  14785. begin
  14786. Result := False;
  14787. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  14788. Exit;
  14789. { Convert:
  14790. movswl %ax,%eax -> cwtl
  14791. movslq %eax,%rax -> cdqe
  14792. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  14793. refer to the same opcode and depends only on the assembler's
  14794. current operand-size attribute. [Kit]
  14795. }
  14796. with taicpu(p) do
  14797. case opsize of
  14798. S_WL:
  14799. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  14800. begin
  14801. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  14802. opcode := A_CWDE;
  14803. clearop(0);
  14804. clearop(1);
  14805. ops := 0;
  14806. Result := True;
  14807. end;
  14808. {$ifdef x86_64}
  14809. S_LQ:
  14810. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  14811. begin
  14812. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  14813. opcode := A_CDQE;
  14814. clearop(0);
  14815. clearop(1);
  14816. ops := 0;
  14817. Result := True;
  14818. end;
  14819. {$endif x86_64}
  14820. else
  14821. ;
  14822. end;
  14823. end;
  14824. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  14825. var
  14826. hp1, hp2: tai;
  14827. IdentityMask, Shift: TCGInt;
  14828. LimitSize: Topsize;
  14829. DoNotMerge: Boolean;
  14830. begin
  14831. Result := False;
  14832. { All these optimisations work on "shr const,%reg" }
  14833. if not MatchOpType(taicpu(p), top_const, top_reg) then
  14834. Exit;
  14835. DoNotMerge := False;
  14836. Shift := taicpu(p).oper[0]^.val;
  14837. LimitSize := taicpu(p).opsize;
  14838. hp1 := p;
  14839. repeat
  14840. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  14841. Break;
  14842. { Detect:
  14843. shr x, %reg
  14844. and y, %reg
  14845. If and y, %reg doesn't actually change the value of %reg (e.g. with
  14846. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  14847. }
  14848. case taicpu(hp1).opcode of
  14849. A_AND:
  14850. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  14851. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14852. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14853. begin
  14854. { Make sure the FLAGS register isn't in use }
  14855. TransferUsedRegs(TmpUsedRegs);
  14856. hp2 := p;
  14857. repeat
  14858. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14859. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14860. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14861. begin
  14862. { Generate the identity mask }
  14863. case taicpu(p).opsize of
  14864. S_B:
  14865. IdentityMask := $FF shr Shift;
  14866. S_W:
  14867. IdentityMask := $FFFF shr Shift;
  14868. S_L:
  14869. IdentityMask := $FFFFFFFF shr Shift;
  14870. {$ifdef x86_64}
  14871. S_Q:
  14872. { We need to force the operands to be unsigned 64-bit
  14873. integers otherwise the wrong value is generated }
  14874. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  14875. {$endif x86_64}
  14876. else
  14877. InternalError(2022081501);
  14878. end;
  14879. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  14880. begin
  14881. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  14882. { All the possible 1 bits are covered, so we can remove the AND }
  14883. hp2 := tai(hp1.Previous);
  14884. RemoveInstruction(hp1);
  14885. { p wasn't actually changed, so don't set Result to True,
  14886. but a change was nonetheless made elsewhere }
  14887. Include(OptsToCheck, aoc_ForceNewIteration);
  14888. { Do another pass in case other AND or MOVZX instructions
  14889. follow }
  14890. hp1 := hp2;
  14891. Continue;
  14892. end;
  14893. end;
  14894. end;
  14895. A_TEST, A_CMP, A_Jcc:
  14896. { Skip over conditional jumps and relevant comparisons }
  14897. Continue;
  14898. A_MOVZX:
  14899. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14900. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  14901. begin
  14902. { Since the original register is being read as is, subsequent
  14903. SHRs must not be merged at this point }
  14904. DoNotMerge := True;
  14905. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  14906. begin
  14907. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14908. begin
  14909. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  14910. { All the possible 1 bits are covered, so we can remove the AND }
  14911. hp2 := tai(hp1.Previous);
  14912. RemoveInstruction(hp1);
  14913. hp1 := hp2;
  14914. end
  14915. else { Different register target }
  14916. begin
  14917. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  14918. taicpu(hp1).opcode := A_MOV;
  14919. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  14920. case taicpu(hp1).opsize of
  14921. S_BW:
  14922. taicpu(hp1).opsize := S_W;
  14923. S_BL, S_WL:
  14924. taicpu(hp1).opsize := S_L;
  14925. else
  14926. InternalError(2022081503);
  14927. end;
  14928. end;
  14929. end
  14930. else if (Shift > 0) and
  14931. (taicpu(p).opsize = S_W) and
  14932. (taicpu(hp1).opsize = S_WL) and
  14933. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  14934. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  14935. begin
  14936. { Detect:
  14937. shr x, %ax (x > 0)
  14938. ...
  14939. movzwl %ax,%eax
  14940. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14941. }
  14942. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  14943. taicpu(hp1).opcode := A_CWDE;
  14944. taicpu(hp1).clearop(0);
  14945. taicpu(hp1).clearop(1);
  14946. taicpu(hp1).ops := 0;
  14947. end;
  14948. { Move onto the next instruction }
  14949. Continue;
  14950. end;
  14951. A_SHL, A_SAL, A_SHR:
  14952. if (taicpu(hp1).opsize <= LimitSize) and
  14953. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14954. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  14955. begin
  14956. { Make sure the sizes don't exceed the register size limit
  14957. (measured by the shift value falling below the limit) }
  14958. if taicpu(hp1).opsize < LimitSize then
  14959. LimitSize := taicpu(hp1).opsize;
  14960. if taicpu(hp1).opcode = A_SHR then
  14961. Inc(Shift, taicpu(hp1).oper[0]^.val)
  14962. else
  14963. begin
  14964. Dec(Shift, taicpu(hp1).oper[0]^.val);
  14965. DoNotMerge := True;
  14966. end;
  14967. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  14968. Break;
  14969. { Since we've established that the combined shift is within
  14970. limits, we can actually combine the adjacent SHR
  14971. instructions even if they're different sizes }
  14972. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  14973. begin
  14974. hp2 := tai(hp1.Previous);
  14975. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  14976. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  14977. RemoveInstruction(hp1);
  14978. hp1 := hp2;
  14979. end;
  14980. { Move onto the next instruction }
  14981. Continue;
  14982. end;
  14983. else
  14984. ;
  14985. end;
  14986. Break;
  14987. until False;
  14988. { Detect the following (looking backwards):
  14989. shr %cl,%reg
  14990. shr x, %reg
  14991. Swap the two SHR instructions to minimise a pipeline stall.
  14992. }
  14993. if GetLastInstruction(p, hp1) and
  14994. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  14995. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14996. { First operand will be %cl }
  14997. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  14998. { Just to be sure }
  14999. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  15000. begin
  15001. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  15002. { Moving the entries this way ensures the register tracking remains correct }
  15003. Asml.Remove(p);
  15004. Asml.InsertBefore(p, hp1);
  15005. p := hp1;
  15006. { Don't set Result to True because the current instruction is now
  15007. "shr %cl,%reg" and there's nothing more we can do with it }
  15008. end;
  15009. end;
  15010. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  15011. var
  15012. hp1, hp2: tai;
  15013. Opposite, SecondOpposite: TAsmOp;
  15014. NewCond: TAsmCond;
  15015. begin
  15016. Result := False;
  15017. { Change:
  15018. add/sub 128,(dest)
  15019. To:
  15020. sub/add -128,(dest)
  15021. This generaally takes fewer bytes to encode because -128 can be stored
  15022. in a signed byte, whereas +128 cannot.
  15023. }
  15024. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  15025. begin
  15026. if taicpu(p).opcode = A_ADD then
  15027. Opposite := A_SUB
  15028. else
  15029. Opposite := A_ADD;
  15030. { Be careful if the flags are in use, because the CF flag inverts
  15031. when changing from ADD to SUB and vice versa }
  15032. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  15033. GetNextInstruction(p, hp1) then
  15034. begin
  15035. TransferUsedRegs(TmpUsedRegs);
  15036. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  15037. hp2 := hp1;
  15038. { Scan ahead to check if everything's safe }
  15039. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  15040. begin
  15041. if (hp1.typ <> ait_instruction) then
  15042. { Probably unsafe since the flags are still in use }
  15043. Exit;
  15044. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  15045. { Stop searching at an unconditional jump }
  15046. Break;
  15047. if not
  15048. (
  15049. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  15050. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  15051. ) and
  15052. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  15053. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  15054. Exit;
  15055. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15056. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  15057. { Move to the next instruction }
  15058. GetNextInstruction(hp1, hp1);
  15059. end;
  15060. while Assigned(hp2) and (hp2 <> hp1) do
  15061. begin
  15062. NewCond := C_None;
  15063. case taicpu(hp2).condition of
  15064. C_A, C_NBE:
  15065. NewCond := C_BE;
  15066. C_B, C_C, C_NAE:
  15067. NewCond := C_AE;
  15068. C_AE, C_NB, C_NC:
  15069. NewCond := C_B;
  15070. C_BE, C_NA:
  15071. NewCond := C_A;
  15072. else
  15073. { No change needed };
  15074. end;
  15075. if NewCond <> C_None then
  15076. begin
  15077. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  15078. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  15079. taicpu(hp2).condition := NewCond;
  15080. end
  15081. else
  15082. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  15083. begin
  15084. { Because of the flipping of the carry bit, to ensure
  15085. the operation remains equivalent, ADC becomes SBB
  15086. and vice versa, and the constant is not-inverted.
  15087. If multiple ADCs or SBBs appear in a row, each one
  15088. changed causes the carry bit to invert, so they all
  15089. need to be flipped }
  15090. if taicpu(hp2).opcode = A_ADC then
  15091. SecondOpposite := A_SBB
  15092. else
  15093. SecondOpposite := A_ADC;
  15094. if taicpu(hp2).oper[0]^.typ <> top_const then
  15095. { Should have broken out of this optimisation already }
  15096. InternalError(2021112901);
  15097. 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]^) + ' -> ' +
  15098. 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);
  15099. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  15100. taicpu(hp2).opcode := SecondOpposite;
  15101. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  15102. end;
  15103. { Move to the next instruction }
  15104. GetNextInstruction(hp2, hp2);
  15105. end;
  15106. if (hp2 <> hp1) then
  15107. InternalError(2021111501);
  15108. end;
  15109. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  15110. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  15111. taicpu(p).opcode := Opposite;
  15112. taicpu(p).oper[0]^.val := -128;
  15113. { No further optimisations can be made on this instruction, so move
  15114. onto the next one to save time }
  15115. p := tai(p.Next);
  15116. UpdateUsedRegs(p);
  15117. Result := True;
  15118. Exit;
  15119. end;
  15120. { Detect:
  15121. add/sub %reg2,(dest)
  15122. add/sub x, (dest)
  15123. (dest can be a register or a reference)
  15124. Swap the instructions to minimise a pipeline stall. This reverses the
  15125. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  15126. optimisations could be made.
  15127. }
  15128. if (taicpu(p).oper[0]^.typ = top_reg) and
  15129. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  15130. (
  15131. (
  15132. (taicpu(p).oper[1]^.typ = top_reg) and
  15133. { We can try searching further ahead if we're writing to a register }
  15134. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  15135. ) or
  15136. (
  15137. (taicpu(p).oper[1]^.typ = top_ref) and
  15138. GetNextInstruction(p, hp1)
  15139. )
  15140. ) and
  15141. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  15142. (taicpu(hp1).oper[0]^.typ = top_const) and
  15143. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  15144. begin
  15145. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  15146. TransferUsedRegs(TmpUsedRegs);
  15147. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  15148. hp2 := p;
  15149. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15150. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15151. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15152. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15153. begin
  15154. asml.remove(hp1);
  15155. asml.InsertBefore(hp1, p);
  15156. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15157. Result := True;
  15158. end;
  15159. end;
  15160. end;
  15161. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15162. var
  15163. hp1: tai;
  15164. begin
  15165. Result:=false;
  15166. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15167. while GetNextInstruction(p, hp1) and
  15168. TrySwapMovCmp(p, hp1) do
  15169. begin
  15170. if MatchInstruction(hp1, A_MOV, []) then
  15171. begin
  15172. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15173. begin
  15174. { A little hacky, but since CMP doesn't read the flags, only
  15175. modify them, it's safe if they get scrambled by MOV -> XOR }
  15176. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15177. Result := PostPeepholeOptMov(hp1);
  15178. {$ifdef x86_64}
  15179. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15180. { Used to shrink instruction size }
  15181. PostPeepholeOptXor(hp1);
  15182. {$endif x86_64}
  15183. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15184. end
  15185. else
  15186. begin
  15187. Result := PostPeepholeOptMov(hp1);
  15188. {$ifdef x86_64}
  15189. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15190. { Used to shrink instruction size }
  15191. PostPeepholeOptXor(hp1);
  15192. {$endif x86_64}
  15193. end;
  15194. end;
  15195. { Enabling this flag is actually a null operation, but it marks
  15196. the code as 'modified' during this pass }
  15197. Include(OptsToCheck, aoc_ForceNewIteration);
  15198. end;
  15199. { change "cmp $0, %reg" to "test %reg, %reg" }
  15200. if MatchOpType(taicpu(p),top_const,top_reg) and
  15201. (taicpu(p).oper[0]^.val = 0) then
  15202. begin
  15203. taicpu(p).opcode := A_TEST;
  15204. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15205. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15206. Result:=true;
  15207. end;
  15208. end;
  15209. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15210. var
  15211. IsTestConstX, IsValid : Boolean;
  15212. hp1,hp2 : tai;
  15213. begin
  15214. Result:=false;
  15215. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15216. if (taicpu(p).opcode = A_TEST) then
  15217. while GetNextInstruction(p, hp1) and
  15218. TrySwapMovCmp(p, hp1) do
  15219. begin
  15220. if MatchInstruction(hp1, A_MOV, []) then
  15221. begin
  15222. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15223. begin
  15224. { A little hacky, but since TEST doesn't read the flags, only
  15225. modify them, it's safe if they get scrambled by MOV -> XOR }
  15226. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15227. Result := PostPeepholeOptMov(hp1);
  15228. {$ifdef x86_64}
  15229. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15230. { Used to shrink instruction size }
  15231. PostPeepholeOptXor(hp1);
  15232. {$endif x86_64}
  15233. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15234. end
  15235. else
  15236. begin
  15237. Result := PostPeepholeOptMov(hp1);
  15238. {$ifdef x86_64}
  15239. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15240. { Used to shrink instruction size }
  15241. PostPeepholeOptXor(hp1);
  15242. {$endif x86_64}
  15243. end;
  15244. end;
  15245. { Enabling this flag is actually a null operation, but it marks
  15246. the code as 'modified' during this pass }
  15247. Include(OptsToCheck, aoc_ForceNewIteration);
  15248. end;
  15249. { If x is a power of 2 (popcnt = 1), change:
  15250. or $x, %reg/ref
  15251. To:
  15252. bts lb(x), %reg/ref
  15253. }
  15254. if (taicpu(p).opcode = A_OR) and
  15255. IsBTXAcceptable(p) and
  15256. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15257. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15258. (
  15259. { Don't optimise if a test instruction follows }
  15260. not GetNextInstruction(p, hp1) or
  15261. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15262. ) then
  15263. begin
  15264. 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);
  15265. taicpu(p).opcode := A_BTS;
  15266. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15267. Result := True;
  15268. Exit;
  15269. end;
  15270. { If x is a power of 2 (popcnt = 1), change:
  15271. test $x, %reg/ref
  15272. je / sete / cmove (or jne / setne)
  15273. To:
  15274. bt lb(x), %reg/ref
  15275. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15276. }
  15277. if (taicpu(p).opcode = A_TEST) and
  15278. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15279. (taicpu(p).oper[0]^.typ = top_const) and
  15280. (
  15281. (cs_opt_size in current_settings.optimizerswitches) or
  15282. (
  15283. (taicpu(p).oper[1]^.typ = top_reg) and
  15284. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15285. ) or
  15286. (
  15287. (taicpu(p).oper[1]^.typ <> top_reg) and
  15288. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15289. )
  15290. ) and
  15291. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15292. { For sizes less than S_L, the byte size is equal or larger with BT,
  15293. so don't bother optimising }
  15294. (taicpu(p).opsize >= S_L) then
  15295. begin
  15296. IsValid := True;
  15297. { Check the next set of instructions, watching the FLAGS register
  15298. and the conditions used }
  15299. TransferUsedRegs(TmpUsedRegs);
  15300. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15301. hp1 := p;
  15302. hp2 := nil;
  15303. while GetNextInstruction(hp1, hp1) do
  15304. begin
  15305. if not Assigned(hp2) then
  15306. { The first instruction after TEST }
  15307. hp2 := hp1;
  15308. if (hp1.typ <> ait_instruction) then
  15309. begin
  15310. { If the flags are no longer in use, everything is fine }
  15311. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15312. IsValid := False;
  15313. Break;
  15314. end;
  15315. case taicpu(hp1).condition of
  15316. C_None:
  15317. begin
  15318. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  15319. not RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1) then
  15320. { Something is not quite normal, so play safe and don't change }
  15321. IsValid := False;
  15322. Break;
  15323. end;
  15324. C_E, C_Z, C_NE, C_NZ:
  15325. { This is fine };
  15326. else
  15327. begin
  15328. { Unsupported condition }
  15329. IsValid := False;
  15330. Break;
  15331. end;
  15332. end;
  15333. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15334. end;
  15335. if IsValid then
  15336. begin
  15337. while hp2 <> hp1 do
  15338. begin
  15339. case taicpu(hp2).condition of
  15340. C_Z, C_E:
  15341. taicpu(hp2).condition := C_NC;
  15342. C_NZ, C_NE:
  15343. taicpu(hp2).condition := C_C;
  15344. else
  15345. { Should not get this by this point }
  15346. InternalError(2022110701);
  15347. end;
  15348. GetNextInstruction(hp2, hp2);
  15349. end;
  15350. 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);
  15351. taicpu(p).opcode := A_BT;
  15352. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15353. Result := True;
  15354. Exit;
  15355. end;
  15356. end;
  15357. { removes the line marked with (x) from the sequence
  15358. and/or/xor/add/sub/... $x, %y
  15359. test/or %y, %y | test $-1, %y (x)
  15360. j(n)z _Label
  15361. as the first instruction already adjusts the ZF
  15362. %y operand may also be a reference }
  15363. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15364. MatchOperand(taicpu(p).oper[0]^,-1);
  15365. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15366. GetLastInstruction(p, hp1) and
  15367. (tai(hp1).typ = ait_instruction) and
  15368. GetNextInstruction(p,hp2) and
  15369. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15370. case taicpu(hp1).opcode Of
  15371. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15372. { These two instructions set the zero flag if the result is zero }
  15373. A_POPCNT, A_LZCNT:
  15374. begin
  15375. if (
  15376. { With POPCNT, an input of zero will set the zero flag
  15377. because the population count of zero is zero }
  15378. (taicpu(hp1).opcode = A_POPCNT) and
  15379. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15380. (
  15381. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15382. { Faster than going through the second half of the 'or'
  15383. condition below }
  15384. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15385. )
  15386. ) or (
  15387. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15388. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15389. { and in case of carry for A(E)/B(E)/C/NC }
  15390. (
  15391. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15392. (
  15393. (taicpu(hp1).opcode <> A_ADD) and
  15394. (taicpu(hp1).opcode <> A_SUB) and
  15395. (taicpu(hp1).opcode <> A_LZCNT)
  15396. )
  15397. )
  15398. ) then
  15399. begin
  15400. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15401. RemoveCurrentP(p, hp2);
  15402. Result:=true;
  15403. Exit;
  15404. end;
  15405. end;
  15406. A_SHL, A_SAL, A_SHR, A_SAR:
  15407. begin
  15408. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15409. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15410. { therefore, it's only safe to do this optimization for }
  15411. { shifts by a (nonzero) constant }
  15412. (taicpu(hp1).oper[0]^.typ = top_const) and
  15413. (taicpu(hp1).oper[0]^.val <> 0) and
  15414. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15415. { and in case of carry for A(E)/B(E)/C/NC }
  15416. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15417. begin
  15418. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15419. RemoveCurrentP(p, hp2);
  15420. Result:=true;
  15421. Exit;
  15422. end;
  15423. end;
  15424. A_DEC, A_INC, A_NEG:
  15425. begin
  15426. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15427. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15428. { and in case of carry for A(E)/B(E)/C/NC }
  15429. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15430. begin
  15431. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15432. RemoveCurrentP(p, hp2);
  15433. Result:=true;
  15434. Exit;
  15435. end;
  15436. end;
  15437. A_ANDN, A_BZHI:
  15438. begin
  15439. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15440. { Only the zero and sign flags are consistent with what the result is }
  15441. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15442. begin
  15443. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15444. RemoveCurrentP(p, hp2);
  15445. Result:=true;
  15446. Exit;
  15447. end;
  15448. end;
  15449. A_BEXTR:
  15450. begin
  15451. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15452. { Only the zero flag is set }
  15453. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15454. begin
  15455. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15456. RemoveCurrentP(p, hp2);
  15457. Result:=true;
  15458. Exit;
  15459. end;
  15460. end;
  15461. else
  15462. ;
  15463. end; { case }
  15464. { change "test $-1,%reg" into "test %reg,%reg" }
  15465. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15466. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15467. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15468. if MatchInstruction(p, A_OR, []) and
  15469. { Can only match if they're both registers }
  15470. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15471. begin
  15472. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15473. taicpu(p).opcode := A_TEST;
  15474. { No need to set Result to True, as we've done all the optimisations we can }
  15475. end;
  15476. end;
  15477. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15478. var
  15479. hp1,hp3 : tai;
  15480. {$ifndef x86_64}
  15481. hp2 : taicpu;
  15482. {$endif x86_64}
  15483. begin
  15484. Result:=false;
  15485. hp3:=nil;
  15486. {$ifndef x86_64}
  15487. { don't do this on modern CPUs, this really hurts them due to
  15488. broken call/ret pairing }
  15489. if (current_settings.optimizecputype < cpu_Pentium2) and
  15490. not(cs_create_pic in current_settings.moduleswitches) and
  15491. GetNextInstruction(p, hp1) and
  15492. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15493. MatchOpType(taicpu(hp1),top_ref) and
  15494. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15495. begin
  15496. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15497. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15498. InsertLLItem(p.previous, p, hp2);
  15499. taicpu(p).opcode := A_JMP;
  15500. taicpu(p).is_jmp := true;
  15501. RemoveInstruction(hp1);
  15502. Result:=true;
  15503. end
  15504. else
  15505. {$endif x86_64}
  15506. { replace
  15507. call procname
  15508. ret
  15509. by
  15510. jmp procname
  15511. but do it only on level 4 because it destroys stack back traces
  15512. else if the subroutine is marked as no return, remove the ret
  15513. }
  15514. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15515. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15516. GetNextInstruction(p, hp1) and
  15517. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15518. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15519. SetAndTest(hp1,hp3) and
  15520. GetNextInstruction(hp1,hp1) and
  15521. MatchInstruction(hp1,A_RET,[S_NO])
  15522. )
  15523. ) and
  15524. (taicpu(hp1).ops=0) then
  15525. begin
  15526. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15527. { we might destroy stack alignment here if we do not do a call }
  15528. (target_info.stackalign<=sizeof(SizeUInt)) then
  15529. begin
  15530. taicpu(p).opcode := A_JMP;
  15531. taicpu(p).is_jmp := true;
  15532. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15533. end
  15534. else
  15535. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15536. RemoveInstruction(hp1);
  15537. if Assigned(hp3) then
  15538. begin
  15539. AsmL.Remove(hp3);
  15540. AsmL.InsertBefore(hp3,p)
  15541. end;
  15542. Result:=true;
  15543. end;
  15544. end;
  15545. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15546. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15547. begin
  15548. case OpSize of
  15549. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15550. Result := (Val <= $FF) and (Val >= -128);
  15551. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15552. Result := (Val <= $FFFF) and (Val >= -32768);
  15553. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15554. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15555. else
  15556. Result := True;
  15557. end;
  15558. end;
  15559. var
  15560. hp1, hp2 : tai;
  15561. SizeChange: Boolean;
  15562. PreMessage: string;
  15563. begin
  15564. Result := False;
  15565. if (taicpu(p).oper[0]^.typ = top_reg) and
  15566. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15567. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15568. begin
  15569. { Change (using movzbl %al,%eax as an example):
  15570. movzbl %al, %eax movzbl %al, %eax
  15571. cmpl x, %eax testl %eax,%eax
  15572. To:
  15573. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15574. movzbl %al, %eax movzbl %al, %eax
  15575. Smaller instruction and minimises pipeline stall as the CPU
  15576. doesn't have to wait for the register to get zero-extended. [Kit]
  15577. Also allow if the smaller of the two registers is being checked,
  15578. as this still removes the false dependency.
  15579. }
  15580. if
  15581. (
  15582. (
  15583. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15584. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15585. ) or (
  15586. { If MatchOperand returns True, they must both be registers }
  15587. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15588. )
  15589. ) and
  15590. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15591. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15592. begin
  15593. 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);
  15594. asml.Remove(hp1);
  15595. asml.InsertBefore(hp1, p);
  15596. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15597. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15598. begin
  15599. taicpu(hp1).opcode := A_TEST;
  15600. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15601. end;
  15602. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15603. case taicpu(p).opsize of
  15604. S_BW, S_BL:
  15605. begin
  15606. SizeChange := taicpu(hp1).opsize <> S_B;
  15607. taicpu(hp1).changeopsize(S_B);
  15608. end;
  15609. S_WL:
  15610. begin
  15611. SizeChange := taicpu(hp1).opsize <> S_W;
  15612. taicpu(hp1).changeopsize(S_W);
  15613. end
  15614. else
  15615. InternalError(2020112701);
  15616. end;
  15617. UpdateUsedRegs(tai(p.Next));
  15618. { Check if the register is used aferwards - if not, we can
  15619. remove the movzx instruction completely }
  15620. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15621. begin
  15622. { Hp1 is a better position than p for debugging purposes }
  15623. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15624. RemoveCurrentp(p, hp1);
  15625. Result := True;
  15626. end;
  15627. if SizeChange then
  15628. DebugMsg(SPeepholeOptimization + PreMessage +
  15629. 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)
  15630. else
  15631. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15632. Exit;
  15633. end;
  15634. { Change (using movzwl %ax,%eax as an example):
  15635. movzwl %ax, %eax
  15636. movb %al, (dest) (Register is smaller than read register in movz)
  15637. To:
  15638. movb %al, (dest) (Move one back to avoid a false dependency)
  15639. movzwl %ax, %eax
  15640. }
  15641. if (taicpu(hp1).opcode = A_MOV) and
  15642. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15643. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15644. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15645. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15646. begin
  15647. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15648. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15649. asml.Remove(hp1);
  15650. asml.InsertBefore(hp1, p);
  15651. if taicpu(hp1).oper[1]^.typ = top_reg then
  15652. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15653. { Check if the register is used aferwards - if not, we can
  15654. remove the movzx instruction completely }
  15655. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15656. begin
  15657. { Hp1 is a better position than p for debugging purposes }
  15658. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15659. RemoveCurrentp(p, hp1);
  15660. Result := True;
  15661. end;
  15662. Exit;
  15663. end;
  15664. end;
  15665. end;
  15666. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15667. var
  15668. hp1: tai;
  15669. {$ifdef x86_64}
  15670. PreMessage, RegName: string;
  15671. {$endif x86_64}
  15672. begin
  15673. Result := False;
  15674. { If x is a power of 2 (popcnt = 1), change:
  15675. xor $x, %reg/ref
  15676. To:
  15677. btc lb(x), %reg/ref
  15678. }
  15679. if IsBTXAcceptable(p) and
  15680. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15681. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15682. (
  15683. { Don't optimise if a test instruction follows }
  15684. not GetNextInstruction(p, hp1) or
  15685. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15686. ) then
  15687. begin
  15688. 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);
  15689. taicpu(p).opcode := A_BTC;
  15690. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15691. Result := True;
  15692. Exit;
  15693. end;
  15694. {$ifdef x86_64}
  15695. { Code size reduction by J. Gareth "Kit" Moreton }
  15696. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15697. as this removes the REX prefix }
  15698. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15699. Exit;
  15700. if taicpu(p).oper[0]^.typ <> top_reg then
  15701. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15702. InternalError(2018011500);
  15703. case taicpu(p).opsize of
  15704. S_Q:
  15705. begin
  15706. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15707. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15708. { The actual optimization }
  15709. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15710. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15711. taicpu(p).changeopsize(S_L);
  15712. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15713. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15714. end;
  15715. else
  15716. ;
  15717. end;
  15718. {$endif x86_64}
  15719. end;
  15720. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15721. var
  15722. XReg: TRegister;
  15723. begin
  15724. Result := False;
  15725. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15726. Smaller encoding and slightly faster on some platforms (also works for
  15727. ZMM-sized registers) }
  15728. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15729. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15730. begin
  15731. XReg := taicpu(p).oper[0]^.reg;
  15732. if (taicpu(p).oper[1]^.reg = XReg) then
  15733. begin
  15734. taicpu(p).changeopsize(S_XMM);
  15735. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15736. if (cs_opt_size in current_settings.optimizerswitches) then
  15737. begin
  15738. { Change input registers to %xmm0 to reduce size. Note that
  15739. there's a risk of a false dependency doing this, so only
  15740. optimise for size here }
  15741. XReg := NR_XMM0;
  15742. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15743. end
  15744. else
  15745. begin
  15746. setsubreg(XReg, R_SUBMMX);
  15747. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15748. end;
  15749. taicpu(p).oper[0]^.reg := XReg;
  15750. taicpu(p).oper[1]^.reg := XReg;
  15751. Result := True;
  15752. end;
  15753. end;
  15754. end;
  15755. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15756. var
  15757. OperIdx: Integer;
  15758. begin
  15759. for OperIdx := 0 to p.ops - 1 do
  15760. if p.oper[OperIdx]^.typ = top_ref then
  15761. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15762. end;
  15763. end.