aoptx86.pas 575 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  46. potentially allowing further optimisation (although it might need to know if
  47. it crossed a conditional jump. }
  48. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  49. {
  50. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  51. the use of a register by allocs/dealloc, so it can ignore calls.
  52. In the following example, GetNextInstructionUsingReg will return the second movq,
  53. GetNextInstructionUsingRegTrackingUse won't.
  54. movq %rdi,%rax
  55. # Register rdi released
  56. # Register rdi allocated
  57. movq %rax,%rdi
  58. While in this example:
  59. movq %rdi,%rax
  60. call proc
  61. movq %rdi,%rax
  62. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  63. won't.
  64. }
  65. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  66. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  67. private
  68. function SkipSimpleInstructions(var hp1: tai): Boolean;
  69. protected
  70. class function IsMOVZXAcceptable: Boolean; static; inline;
  71. { Attempts to allocate a volatile integer register for use between p and hp,
  72. using AUsedRegs for the current register usage information. Returns NR_NO
  73. if no free register could be found }
  74. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  75. { Attempts to allocate a volatile MM register for use between p and hp,
  76. using AUsedRegs for the current register usage information. Returns NR_NO
  77. if no free register could be found }
  78. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  79. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  80. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  81. { checks whether reading the value in reg1 depends on the value of reg2. This
  82. is very similar to SuperRegisterEquals, except it takes into account that
  83. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  84. depend on the value in AH). }
  85. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  86. { Replaces all references to AOldReg in a memory reference to ANewReg }
  87. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  88. { Replaces all references to AOldReg in an operand to ANewReg }
  89. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  90. { Replaces all references to AOldReg in an instruction to ANewReg,
  91. except where the register is being written }
  92. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  93. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  94. or writes to a global symbol }
  95. class function IsRefSafe(const ref: PReference): Boolean; static;
  96. { Returns true if the given MOV instruction can be safely converted to CMOV }
  97. class function CanBeCMOV(p : tai) : boolean; static;
  98. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  99. conversion was successful }
  100. function ConvertLEA(const p : taicpu): Boolean;
  101. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  102. procedure DebugMsg(const s : string; p : tai);inline;
  103. class function IsExitCode(p : tai) : boolean; static;
  104. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  105. procedure RemoveLastDeallocForFuncRes(p : tai);
  106. function DoSubAddOpt(var p : tai) : Boolean;
  107. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  108. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  109. function PrePeepholeOptSxx(var p : tai) : boolean;
  110. function PrePeepholeOptIMUL(var p : tai) : boolean;
  111. function PrePeepholeOptAND(var p : tai) : boolean;
  112. function OptPass1Test(var p: tai): boolean;
  113. function OptPass1Add(var p: tai): boolean;
  114. function OptPass1AND(var p : tai) : boolean;
  115. function OptPass1_V_MOVAP(var p : tai) : boolean;
  116. function OptPass1VOP(var p : tai) : boolean;
  117. function OptPass1MOV(var p : tai) : boolean;
  118. function OptPass1Movx(var p : tai) : boolean;
  119. function OptPass1MOVXX(var p : tai) : boolean;
  120. function OptPass1OP(var p : tai) : boolean;
  121. function OptPass1LEA(var p : tai) : boolean;
  122. function OptPass1Sub(var p : tai) : boolean;
  123. function OptPass1SHLSAL(var p : tai) : boolean;
  124. function OptPass1FSTP(var p : tai) : boolean;
  125. function OptPass1FLD(var p : tai) : boolean;
  126. function OptPass1Cmp(var p : tai) : boolean;
  127. function OptPass1PXor(var p : tai) : boolean;
  128. function OptPass1VPXor(var p: tai): boolean;
  129. function OptPass1Imul(var p : tai) : boolean;
  130. function OptPass1Jcc(var p : tai) : boolean;
  131. function OptPass1SHXX(var p: tai): boolean;
  132. function OptPass1VMOVDQ(var p: tai): Boolean;
  133. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  134. function OptPass2Movx(var p : tai): Boolean;
  135. function OptPass2MOV(var p : tai) : boolean;
  136. function OptPass2Imul(var p : tai) : boolean;
  137. function OptPass2Jmp(var p : tai) : boolean;
  138. function OptPass2Jcc(var p : tai) : boolean;
  139. function OptPass2Lea(var p: tai): Boolean;
  140. function OptPass2SUB(var p: tai): Boolean;
  141. function OptPass2ADD(var p : tai): Boolean;
  142. function OptPass2SETcc(var p : tai) : boolean;
  143. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  144. function PostPeepholeOptMov(var p : tai) : Boolean;
  145. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  146. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  147. function PostPeepholeOptXor(var p : tai) : Boolean;
  148. {$endif x86_64}
  149. function PostPeepholeOptAnd(var p : tai) : boolean;
  150. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  151. function PostPeepholeOptCmp(var p : tai) : Boolean;
  152. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  153. function PostPeepholeOptCall(var p : tai) : Boolean;
  154. function PostPeepholeOptLea(var p : tai) : Boolean;
  155. function PostPeepholeOptPush(var p: tai): Boolean;
  156. function PostPeepholeOptShr(var p : tai) : boolean;
  157. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  158. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  159. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  160. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  161. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  162. { Processor-dependent reference optimisation }
  163. class procedure OptimizeRefs(var p: taicpu); static;
  164. end;
  165. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  166. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  167. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  168. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  169. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  170. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  171. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  172. {$if max_operands>2}
  173. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  174. {$endif max_operands>2}
  175. function RefsEqual(const r1, r2: treference): boolean;
  176. { Note that Result is set to True if the references COULD overlap but the
  177. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  178. might still overlap because %reg2 could be equal to %reg1-4 }
  179. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  180. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  181. { returns true, if ref is a reference using only the registers passed as base and index
  182. and having an offset }
  183. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  184. implementation
  185. uses
  186. cutils,verbose,
  187. systems,
  188. globals,
  189. cpuinfo,
  190. procinfo,
  191. paramgr,
  192. aasmbase,
  193. aoptbase,aoptutils,
  194. symconst,symsym,
  195. cgx86,
  196. itcpugas;
  197. {$ifdef DEBUG_AOPTCPU}
  198. const
  199. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  200. {$else DEBUG_AOPTCPU}
  201. { Empty strings help the optimizer to remove string concatenations that won't
  202. ever appear to the user on release builds. [Kit] }
  203. const
  204. SPeepholeOptimization = '';
  205. {$endif DEBUG_AOPTCPU}
  206. LIST_STEP_SIZE = 4;
  207. type
  208. TJumpTrackingItem = class(TLinkedListItem)
  209. private
  210. FSymbol: TAsmSymbol;
  211. FRefs: LongInt;
  212. public
  213. constructor Create(ASymbol: TAsmSymbol);
  214. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  215. property Symbol: TAsmSymbol read FSymbol;
  216. property Refs: LongInt read FRefs;
  217. end;
  218. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  219. begin
  220. inherited Create;
  221. FSymbol := ASymbol;
  222. FRefs := 0;
  223. end;
  224. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  225. begin
  226. Inc(FRefs);
  227. end;
  228. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  229. begin
  230. result :=
  231. (instr.typ = ait_instruction) and
  232. (taicpu(instr).opcode = op) and
  233. ((opsize = []) or (taicpu(instr).opsize in opsize));
  234. end;
  235. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  236. begin
  237. result :=
  238. (instr.typ = ait_instruction) and
  239. ((taicpu(instr).opcode = op1) or
  240. (taicpu(instr).opcode = op2)
  241. ) and
  242. ((opsize = []) or (taicpu(instr).opsize in opsize));
  243. end;
  244. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  245. begin
  246. result :=
  247. (instr.typ = ait_instruction) and
  248. ((taicpu(instr).opcode = op1) or
  249. (taicpu(instr).opcode = op2) or
  250. (taicpu(instr).opcode = op3)
  251. ) and
  252. ((opsize = []) or (taicpu(instr).opsize in opsize));
  253. end;
  254. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  255. const opsize : topsizes) : boolean;
  256. var
  257. op : TAsmOp;
  258. begin
  259. result:=false;
  260. if (instr.typ <> ait_instruction) or
  261. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  262. exit;
  263. for op in ops do
  264. begin
  265. if taicpu(instr).opcode = op then
  266. begin
  267. result:=true;
  268. exit;
  269. end;
  270. end;
  271. end;
  272. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  273. begin
  274. result := (oper.typ = top_reg) and (oper.reg = reg);
  275. end;
  276. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  277. begin
  278. result := (oper.typ = top_const) and (oper.val = a);
  279. end;
  280. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  281. begin
  282. result := oper1.typ = oper2.typ;
  283. if result then
  284. case oper1.typ of
  285. top_const:
  286. Result:=oper1.val = oper2.val;
  287. top_reg:
  288. Result:=oper1.reg = oper2.reg;
  289. top_ref:
  290. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  291. else
  292. internalerror(2013102801);
  293. end
  294. end;
  295. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  296. begin
  297. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  298. if result then
  299. case oper1.typ of
  300. top_const:
  301. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  302. top_reg:
  303. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  304. top_ref:
  305. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  306. else
  307. internalerror(2020052401);
  308. end
  309. end;
  310. function RefsEqual(const r1, r2: treference): boolean;
  311. begin
  312. RefsEqual :=
  313. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  314. (r1.relsymbol = r2.relsymbol) and
  315. (r1.segment = r2.segment) and (r1.base = r2.base) and
  316. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  317. (r1.offset = r2.offset) and
  318. (r1.volatility + r2.volatility = []);
  319. end;
  320. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  321. begin
  322. if (r1.symbol<>r2.symbol) then
  323. { If the index registers are different, there's a chance one could
  324. be set so it equals the other symbol }
  325. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  326. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  327. (r1.relsymbol = r2.relsymbol) and
  328. (r1.segment = r2.segment) and (r1.base = r2.base) and
  329. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  330. (r1.volatility + r2.volatility = []) then
  331. { In this case, it all depends on the offsets }
  332. Exit(abs(r1.offset - r2.offset) < Range);
  333. { There's a chance things MIGHT overlap, so take no chances }
  334. Result := True;
  335. end;
  336. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  337. begin
  338. Result:=(ref.offset=0) and
  339. (ref.scalefactor in [0,1]) and
  340. (ref.segment=NR_NO) and
  341. (ref.symbol=nil) and
  342. (ref.relsymbol=nil) and
  343. ((base=NR_INVALID) or
  344. (ref.base=base)) and
  345. ((index=NR_INVALID) or
  346. (ref.index=index)) and
  347. (ref.volatility=[]);
  348. end;
  349. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  350. begin
  351. Result:=(ref.scalefactor in [0,1]) and
  352. (ref.segment=NR_NO) and
  353. (ref.symbol=nil) and
  354. (ref.relsymbol=nil) and
  355. ((base=NR_INVALID) or
  356. (ref.base=base)) and
  357. ((index=NR_INVALID) or
  358. (ref.index=index)) and
  359. (ref.volatility=[]);
  360. end;
  361. function InstrReadsFlags(p: tai): boolean;
  362. begin
  363. InstrReadsFlags := true;
  364. case p.typ of
  365. ait_instruction:
  366. if InsProp[taicpu(p).opcode].Ch*
  367. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  368. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  369. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  370. exit;
  371. ait_label:
  372. exit;
  373. else
  374. ;
  375. end;
  376. InstrReadsFlags := false;
  377. end;
  378. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  379. begin
  380. Next:=Current;
  381. repeat
  382. Result:=GetNextInstruction(Next,Next);
  383. until not (Result) or
  384. not(cs_opt_level3 in current_settings.optimizerswitches) or
  385. (Next.typ<>ait_instruction) or
  386. RegInInstruction(reg,Next) or
  387. is_calljmp(taicpu(Next).opcode);
  388. end;
  389. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  390. procedure TrackJump(Symbol: TAsmSymbol);
  391. var
  392. Search: TJumpTrackingItem;
  393. begin
  394. { See if an entry already exists in our jump tracking list
  395. (faster to search backwards due to the higher chance of
  396. matching destinations) }
  397. Search := TJumpTrackingItem(JumpTracking.Last);
  398. while Assigned(Search) do
  399. begin
  400. if Search.Symbol = Symbol then
  401. begin
  402. { Found it - remove it so it can be pushed to the front }
  403. JumpTracking.Remove(Search);
  404. Break;
  405. end;
  406. Search := TJumpTrackingItem(Search.Previous);
  407. end;
  408. if not Assigned(Search) then
  409. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  410. JumpTracking.Concat(Search);
  411. Search.IncRefs;
  412. end;
  413. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  414. var
  415. Search: TJumpTrackingItem;
  416. begin
  417. Result := False;
  418. { See if this label appears in the tracking list }
  419. Search := TJumpTrackingItem(JumpTracking.Last);
  420. while Assigned(Search) do
  421. begin
  422. if Search.Symbol = Symbol then
  423. begin
  424. { Found it - let's see what we can discover }
  425. if Search.Symbol.getrefs = Search.Refs then
  426. begin
  427. { Success - all the references are accounted for }
  428. JumpTracking.Remove(Search);
  429. Search.Free;
  430. { It is logically impossible for CrossJump to be false here
  431. because we must have run into a conditional jump for
  432. this label at some point }
  433. if not CrossJump then
  434. InternalError(2022041710);
  435. if JumpTracking.First = nil then
  436. { Tracking list is now empty - no more cross jumps }
  437. CrossJump := False;
  438. Result := True;
  439. Exit;
  440. end;
  441. { If the references don't match, it's possible to enter
  442. this label through other means, so drop out }
  443. Exit;
  444. end;
  445. Search := TJumpTrackingItem(Search.Previous);
  446. end;
  447. end;
  448. var
  449. Next_Label: tai;
  450. begin
  451. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  452. Next := Current;
  453. repeat
  454. Result := GetNextInstruction(Next,Next);
  455. if not Result then
  456. Break;
  457. if Next.typ = ait_align then
  458. Result := SkipAligns(Next, Next);
  459. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  460. if is_calljmpuncondret(taicpu(Next).opcode) then
  461. begin
  462. if (taicpu(Next).opcode = A_JMP) and
  463. { Remove dead code now to save time }
  464. RemoveDeadCodeAfterJump(taicpu(Next)) then
  465. { A jump was removed, but not the current instruction, and
  466. Result doesn't necessarily translate into an optimisation
  467. routine's Result, so use the "Force New Iteration" flag so
  468. mark a new pass }
  469. Include(OptsToCheck, aoc_ForceNewIteration);
  470. if not Assigned(JumpTracking) then
  471. begin
  472. { Cross-label optimisations often causes other optimisations
  473. to perform worse because they're not given the chance to
  474. optimise locally. In this case, don't do the cross-label
  475. optimisations yet, but flag them as a potential possibility
  476. for the next iteration of Pass 1 }
  477. if not NotFirstIteration then
  478. Include(OptsToCheck, aoc_ForceNewIteration);
  479. end
  480. else if IsJumpToLabel(taicpu(Next)) and
  481. GetNextInstruction(Next, Next_Label) and
  482. SkipAligns(Next_Label, Next_Label) then
  483. begin
  484. { If we have JMP .lbl, and the label after it has all of its
  485. references tracked, then this is probably an if-else style of
  486. block and we can keep tracking. If the label for this jump
  487. then appears later and is fully tracked, then it's the end
  488. of the if-else blocks and the code paths converge (thus
  489. marking the end of the cross-jump) }
  490. if (Next_Label.typ = ait_label) then
  491. begin
  492. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  493. begin
  494. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  495. Next := Next_Label;
  496. { CrossJump gets set to false by LabelAccountedFor if the
  497. list is completely emptied (as it indicates that all
  498. code paths have converged). We could avoid this nuance
  499. by moving the TrackJump call to before the
  500. LabelAccountedFor call, but this is slower in situations
  501. where LabelAccountedFor would return False due to the
  502. creation of a new object that is not used and destroyed
  503. soon after. }
  504. CrossJump := True;
  505. Continue;
  506. end;
  507. end
  508. else if (Next_Label.typ <> ait_marker) then
  509. { We just did a RemoveDeadCodeAfterJump, so either we find
  510. a label, the end of the procedure or some kind of marker}
  511. InternalError(2022041720);
  512. end;
  513. Result := False;
  514. Exit;
  515. end
  516. else
  517. begin
  518. if not Assigned(JumpTracking) then
  519. begin
  520. { Cross-label optimisations often causes other optimisations
  521. to perform worse because they're not given the chance to
  522. optimise locally. In this case, don't do the cross-label
  523. optimisations yet, but flag them as a potential possibility
  524. for the next iteration of Pass 1 }
  525. if not NotFirstIteration then
  526. Include(OptsToCheck, aoc_ForceNewIteration);
  527. end
  528. else if IsJumpToLabel(taicpu(Next)) then
  529. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  530. else
  531. { Conditional jumps should always be a jump to label }
  532. InternalError(2022041701);
  533. CrossJump := True;
  534. Continue;
  535. end;
  536. if Next.typ = ait_label then
  537. begin
  538. if not Assigned(JumpTracking) then
  539. begin
  540. { Cross-label optimisations often causes other optimisations
  541. to perform worse because they're not given the chance to
  542. optimise locally. In this case, don't do the cross-label
  543. optimisations yet, but flag them as a potential possibility
  544. for the next iteration of Pass 1 }
  545. if not NotFirstIteration then
  546. Include(OptsToCheck, aoc_ForceNewIteration);
  547. end
  548. else if LabelAccountedFor(tai_label(Next).labsym) then
  549. Continue;
  550. { If we reach here, we're at a label that hasn't been seen before
  551. (or JumpTracking was nil) }
  552. Break;
  553. end;
  554. until not Result or
  555. not (cs_opt_level3 in current_settings.optimizerswitches) or
  556. not (Next.typ in [ait_label, ait_instruction]) or
  557. RegInInstruction(reg,Next);
  558. end;
  559. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  560. begin
  561. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  562. begin
  563. Result:=GetNextInstruction(Current,Next);
  564. exit;
  565. end;
  566. Next:=tai(Current.Next);
  567. Result:=false;
  568. while assigned(Next) do
  569. begin
  570. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  571. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  572. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  573. exit
  574. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  575. begin
  576. Result:=true;
  577. exit;
  578. end;
  579. Next:=tai(Next.Next);
  580. end;
  581. end;
  582. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  583. begin
  584. Result:=RegReadByInstruction(reg,hp);
  585. end;
  586. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  587. var
  588. p: taicpu;
  589. opcount: longint;
  590. begin
  591. RegReadByInstruction := false;
  592. if hp.typ <> ait_instruction then
  593. exit;
  594. p := taicpu(hp);
  595. case p.opcode of
  596. A_CALL:
  597. regreadbyinstruction := true;
  598. A_IMUL:
  599. case p.ops of
  600. 1:
  601. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  602. (
  603. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  604. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  605. );
  606. 2,3:
  607. regReadByInstruction :=
  608. reginop(reg,p.oper[0]^) or
  609. reginop(reg,p.oper[1]^);
  610. else
  611. InternalError(2019112801);
  612. end;
  613. A_MUL:
  614. begin
  615. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  616. (
  617. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  618. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  619. );
  620. end;
  621. A_IDIV,A_DIV:
  622. begin
  623. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  624. (
  625. (getregtype(reg)=R_INTREGISTER) and
  626. (
  627. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  628. )
  629. );
  630. end;
  631. else
  632. begin
  633. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  634. begin
  635. RegReadByInstruction := false;
  636. exit;
  637. end;
  638. for opcount := 0 to p.ops-1 do
  639. if (p.oper[opCount]^.typ = top_ref) and
  640. RegInRef(reg,p.oper[opcount]^.ref^) then
  641. begin
  642. RegReadByInstruction := true;
  643. exit
  644. end;
  645. { special handling for SSE MOVSD }
  646. if (p.opcode=A_MOVSD) and (p.ops>0) then
  647. begin
  648. if p.ops<>2 then
  649. internalerror(2017042702);
  650. regReadByInstruction := reginop(reg,p.oper[0]^) or
  651. (
  652. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  653. );
  654. exit;
  655. end;
  656. with insprop[p.opcode] do
  657. begin
  658. case getregtype(reg) of
  659. R_INTREGISTER:
  660. begin
  661. case getsupreg(reg) of
  662. RS_EAX:
  663. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  664. begin
  665. RegReadByInstruction := true;
  666. exit
  667. end;
  668. RS_ECX:
  669. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  670. begin
  671. RegReadByInstruction := true;
  672. exit
  673. end;
  674. RS_EDX:
  675. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  676. begin
  677. RegReadByInstruction := true;
  678. exit
  679. end;
  680. RS_EBX:
  681. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  682. begin
  683. RegReadByInstruction := true;
  684. exit
  685. end;
  686. RS_ESP:
  687. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  688. begin
  689. RegReadByInstruction := true;
  690. exit
  691. end;
  692. RS_EBP:
  693. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  694. begin
  695. RegReadByInstruction := true;
  696. exit
  697. end;
  698. RS_ESI:
  699. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  700. begin
  701. RegReadByInstruction := true;
  702. exit
  703. end;
  704. RS_EDI:
  705. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  706. begin
  707. RegReadByInstruction := true;
  708. exit
  709. end;
  710. end;
  711. end;
  712. R_MMREGISTER:
  713. begin
  714. case getsupreg(reg) of
  715. RS_XMM0:
  716. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  717. begin
  718. RegReadByInstruction := true;
  719. exit
  720. end;
  721. end;
  722. end;
  723. else
  724. ;
  725. end;
  726. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  727. begin
  728. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  729. begin
  730. case p.condition of
  731. C_A,C_NBE, { CF=0 and ZF=0 }
  732. C_BE,C_NA: { CF=1 or ZF=1 }
  733. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  734. C_AE,C_NB,C_NC, { CF=0 }
  735. C_B,C_NAE,C_C: { CF=1 }
  736. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  737. C_NE,C_NZ, { ZF=0 }
  738. C_E,C_Z: { ZF=1 }
  739. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  740. C_G,C_NLE, { ZF=0 and SF=OF }
  741. C_LE,C_NG: { ZF=1 or SF<>OF }
  742. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  743. C_GE,C_NL, { SF=OF }
  744. C_L,C_NGE: { SF<>OF }
  745. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  746. C_NO, { OF=0 }
  747. C_O: { OF=1 }
  748. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  749. C_NP,C_PO, { PF=0 }
  750. C_P,C_PE: { PF=1 }
  751. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  752. C_NS, { SF=0 }
  753. C_S: { SF=1 }
  754. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  755. else
  756. internalerror(2017042701);
  757. end;
  758. if RegReadByInstruction then
  759. exit;
  760. end;
  761. case getsubreg(reg) of
  762. R_SUBW,R_SUBD,R_SUBQ:
  763. RegReadByInstruction :=
  764. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  765. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  766. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  767. R_SUBFLAGCARRY:
  768. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  769. R_SUBFLAGPARITY:
  770. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  771. R_SUBFLAGAUXILIARY:
  772. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  773. R_SUBFLAGZERO:
  774. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  775. R_SUBFLAGSIGN:
  776. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  777. R_SUBFLAGOVERFLOW:
  778. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  779. R_SUBFLAGINTERRUPT:
  780. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  781. R_SUBFLAGDIRECTION:
  782. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  783. else
  784. internalerror(2017042601);
  785. end;
  786. exit;
  787. end;
  788. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  789. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  790. (p.oper[0]^.reg=p.oper[1]^.reg) then
  791. exit;
  792. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  793. begin
  794. RegReadByInstruction := true;
  795. exit
  796. end;
  797. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  798. begin
  799. RegReadByInstruction := true;
  800. exit
  801. end;
  802. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  803. begin
  804. RegReadByInstruction := true;
  805. exit
  806. end;
  807. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  808. begin
  809. RegReadByInstruction := true;
  810. exit
  811. end;
  812. end;
  813. end;
  814. end;
  815. end;
  816. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  817. begin
  818. result:=false;
  819. if p1.typ<>ait_instruction then
  820. exit;
  821. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  822. exit(true);
  823. if (getregtype(reg)=R_INTREGISTER) and
  824. { change information for xmm movsd are not correct }
  825. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  826. begin
  827. case getsupreg(reg) of
  828. { RS_EAX = RS_RAX on x86-64 }
  829. RS_EAX:
  830. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  831. RS_ECX:
  832. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  833. RS_EDX:
  834. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  835. RS_EBX:
  836. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  837. RS_ESP:
  838. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  839. RS_EBP:
  840. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  841. RS_ESI:
  842. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  843. RS_EDI:
  844. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  845. else
  846. ;
  847. end;
  848. if result then
  849. exit;
  850. end
  851. else if getregtype(reg)=R_MMREGISTER then
  852. begin
  853. case getsupreg(reg) of
  854. RS_XMM0:
  855. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  856. else
  857. ;
  858. end;
  859. if result then
  860. exit;
  861. end
  862. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  863. begin
  864. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  865. exit(true);
  866. case getsubreg(reg) of
  867. R_SUBFLAGCARRY:
  868. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  869. R_SUBFLAGPARITY:
  870. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  871. R_SUBFLAGAUXILIARY:
  872. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  873. R_SUBFLAGZERO:
  874. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  875. R_SUBFLAGSIGN:
  876. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  877. R_SUBFLAGOVERFLOW:
  878. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  879. R_SUBFLAGINTERRUPT:
  880. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  881. R_SUBFLAGDIRECTION:
  882. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  883. R_SUBW,R_SUBD,R_SUBQ:
  884. { Everything except the direction bits }
  885. Result:=
  886. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  887. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  888. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  889. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  890. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  891. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  892. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  893. else
  894. ;
  895. end;
  896. if result then
  897. exit;
  898. end
  899. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  900. exit(true);
  901. Result:=inherited RegInInstruction(Reg, p1);
  902. end;
  903. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  904. const
  905. WriteOps: array[0..3] of set of TInsChange =
  906. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  907. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  908. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  909. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  910. var
  911. OperIdx: Integer;
  912. begin
  913. Result := False;
  914. if p1.typ <> ait_instruction then
  915. exit;
  916. with insprop[taicpu(p1).opcode] do
  917. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  918. begin
  919. case getsubreg(reg) of
  920. R_SUBW,R_SUBD,R_SUBQ:
  921. Result :=
  922. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  923. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  924. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  925. R_SUBFLAGCARRY:
  926. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  927. R_SUBFLAGPARITY:
  928. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  929. R_SUBFLAGAUXILIARY:
  930. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  931. R_SUBFLAGZERO:
  932. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  933. R_SUBFLAGSIGN:
  934. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  935. R_SUBFLAGOVERFLOW:
  936. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  937. R_SUBFLAGINTERRUPT:
  938. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  939. R_SUBFLAGDIRECTION:
  940. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  941. else
  942. internalerror(2017042602);
  943. end;
  944. exit;
  945. end;
  946. case taicpu(p1).opcode of
  947. A_CALL:
  948. { We could potentially set Result to False if the register in
  949. question is non-volatile for the subroutine's calling convention,
  950. but this would require detecting the calling convention in use and
  951. also assuming that the routine doesn't contain malformed assembly
  952. language, for example... so it could only be done under -O4 as it
  953. would be considered a side-effect. [Kit] }
  954. Result := True;
  955. A_MOVSD:
  956. { special handling for SSE MOVSD }
  957. if (taicpu(p1).ops>0) then
  958. begin
  959. if taicpu(p1).ops<>2 then
  960. internalerror(2017042703);
  961. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  962. end;
  963. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  964. so fix it here (FK)
  965. }
  966. A_VMOVSS,
  967. A_VMOVSD:
  968. begin
  969. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  970. exit;
  971. end;
  972. A_IMUL:
  973. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  974. else
  975. ;
  976. end;
  977. if Result then
  978. exit;
  979. with insprop[taicpu(p1).opcode] do
  980. begin
  981. if getregtype(reg)=R_INTREGISTER then
  982. begin
  983. case getsupreg(reg) of
  984. RS_EAX:
  985. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  986. begin
  987. Result := True;
  988. exit
  989. end;
  990. RS_ECX:
  991. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  992. begin
  993. Result := True;
  994. exit
  995. end;
  996. RS_EDX:
  997. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  998. begin
  999. Result := True;
  1000. exit
  1001. end;
  1002. RS_EBX:
  1003. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1004. begin
  1005. Result := True;
  1006. exit
  1007. end;
  1008. RS_ESP:
  1009. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1010. begin
  1011. Result := True;
  1012. exit
  1013. end;
  1014. RS_EBP:
  1015. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1016. begin
  1017. Result := True;
  1018. exit
  1019. end;
  1020. RS_ESI:
  1021. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1022. begin
  1023. Result := True;
  1024. exit
  1025. end;
  1026. RS_EDI:
  1027. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1028. begin
  1029. Result := True;
  1030. exit
  1031. end;
  1032. end;
  1033. end;
  1034. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1035. if (WriteOps[OperIdx]*Ch<>[]) and
  1036. { The register doesn't get modified inside a reference }
  1037. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1038. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1039. begin
  1040. Result := true;
  1041. exit
  1042. end;
  1043. end;
  1044. end;
  1045. {$ifdef DEBUG_AOPTCPU}
  1046. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1047. begin
  1048. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1049. end;
  1050. function debug_tostr(i: tcgint): string; inline;
  1051. begin
  1052. Result := tostr(i);
  1053. end;
  1054. function debug_regname(r: TRegister): string; inline;
  1055. begin
  1056. Result := '%' + std_regname(r);
  1057. end;
  1058. { Debug output function - creates a string representation of an operator }
  1059. function debug_operstr(oper: TOper): string;
  1060. begin
  1061. case oper.typ of
  1062. top_const:
  1063. Result := '$' + debug_tostr(oper.val);
  1064. top_reg:
  1065. Result := debug_regname(oper.reg);
  1066. top_ref:
  1067. begin
  1068. if oper.ref^.offset <> 0 then
  1069. Result := debug_tostr(oper.ref^.offset) + '('
  1070. else
  1071. Result := '(';
  1072. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1073. begin
  1074. Result := Result + debug_regname(oper.ref^.base);
  1075. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1076. Result := Result + ',' + debug_regname(oper.ref^.index);
  1077. end
  1078. else
  1079. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1080. Result := Result + debug_regname(oper.ref^.index);
  1081. if (oper.ref^.scalefactor > 1) then
  1082. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1083. else
  1084. Result := Result + ')';
  1085. end;
  1086. else
  1087. Result := '[UNKNOWN]';
  1088. end;
  1089. end;
  1090. function debug_op2str(opcode: tasmop): string; inline;
  1091. begin
  1092. Result := std_op2str[opcode];
  1093. end;
  1094. function debug_opsize2str(opsize: topsize): string; inline;
  1095. begin
  1096. Result := gas_opsize2str[opsize];
  1097. end;
  1098. {$else DEBUG_AOPTCPU}
  1099. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1100. begin
  1101. end;
  1102. function debug_tostr(i: tcgint): string; inline;
  1103. begin
  1104. Result := '';
  1105. end;
  1106. function debug_regname(r: TRegister): string; inline;
  1107. begin
  1108. Result := '';
  1109. end;
  1110. function debug_operstr(oper: TOper): string; inline;
  1111. begin
  1112. Result := '';
  1113. end;
  1114. function debug_op2str(opcode: tasmop): string; inline;
  1115. begin
  1116. Result := '';
  1117. end;
  1118. function debug_opsize2str(opsize: topsize): string; inline;
  1119. begin
  1120. Result := '';
  1121. end;
  1122. {$endif DEBUG_AOPTCPU}
  1123. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1124. begin
  1125. {$ifdef x86_64}
  1126. { Always fine on x86-64 }
  1127. Result := True;
  1128. {$else x86_64}
  1129. Result :=
  1130. {$ifdef i8086}
  1131. (current_settings.cputype >= cpu_386) and
  1132. {$endif i8086}
  1133. (
  1134. { Always accept if optimising for size }
  1135. (cs_opt_size in current_settings.optimizerswitches) or
  1136. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1137. (current_settings.optimizecputype >= cpu_Pentium2)
  1138. );
  1139. {$endif x86_64}
  1140. end;
  1141. { Attempts to allocate a volatile integer register for use between p and hp,
  1142. using AUsedRegs for the current register usage information. Returns NR_NO
  1143. if no free register could be found }
  1144. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1145. var
  1146. RegSet: TCPURegisterSet;
  1147. CurrentSuperReg: Integer;
  1148. CurrentReg: TRegister;
  1149. Currentp: tai;
  1150. Breakout: Boolean;
  1151. begin
  1152. Result := NR_NO;
  1153. RegSet :=
  1154. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1155. current_procinfo.saved_regs_int;
  1156. for CurrentSuperReg in RegSet do
  1157. begin
  1158. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1159. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1160. {$if defined(i386) or defined(i8086)}
  1161. { If the target size is 8-bit, make sure we can actually encode it }
  1162. and (
  1163. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1164. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1165. )
  1166. {$endif i386 or i8086}
  1167. then
  1168. begin
  1169. Currentp := p;
  1170. Breakout := False;
  1171. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1172. begin
  1173. case Currentp.typ of
  1174. ait_instruction:
  1175. begin
  1176. if RegInInstruction(CurrentReg, Currentp) then
  1177. begin
  1178. Breakout := True;
  1179. Break;
  1180. end;
  1181. { Cannot allocate across an unconditional jump }
  1182. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1183. Exit;
  1184. end;
  1185. ait_marker:
  1186. { Don't try anything more if a marker is hit }
  1187. Exit;
  1188. ait_regalloc:
  1189. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1190. begin
  1191. Breakout := True;
  1192. Break;
  1193. end;
  1194. else
  1195. ;
  1196. end;
  1197. end;
  1198. if Breakout then
  1199. { Try the next register }
  1200. Continue;
  1201. { We have a free register available }
  1202. Result := CurrentReg;
  1203. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1204. Exit;
  1205. end;
  1206. end;
  1207. end;
  1208. { Attempts to allocate a volatile MM register for use between p and hp,
  1209. using AUsedRegs for the current register usage information. Returns NR_NO
  1210. if no free register could be found }
  1211. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1212. var
  1213. RegSet: TCPURegisterSet;
  1214. CurrentSuperReg: Integer;
  1215. CurrentReg: TRegister;
  1216. Currentp: tai;
  1217. Breakout: Boolean;
  1218. begin
  1219. Result := NR_NO;
  1220. RegSet :=
  1221. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1222. current_procinfo.saved_regs_mm;
  1223. for CurrentSuperReg in RegSet do
  1224. begin
  1225. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1226. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1227. begin
  1228. Currentp := p;
  1229. Breakout := False;
  1230. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1231. begin
  1232. case Currentp.typ of
  1233. ait_instruction:
  1234. begin
  1235. if RegInInstruction(CurrentReg, Currentp) then
  1236. begin
  1237. Breakout := True;
  1238. Break;
  1239. end;
  1240. { Cannot allocate across an unconditional jump }
  1241. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1242. Exit;
  1243. end;
  1244. ait_marker:
  1245. { Don't try anything more if a marker is hit }
  1246. Exit;
  1247. ait_regalloc:
  1248. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1249. begin
  1250. Breakout := True;
  1251. Break;
  1252. end;
  1253. else
  1254. ;
  1255. end;
  1256. end;
  1257. if Breakout then
  1258. { Try the next register }
  1259. Continue;
  1260. { We have a free register available }
  1261. Result := CurrentReg;
  1262. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1263. Exit;
  1264. end;
  1265. end;
  1266. end;
  1267. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1268. begin
  1269. if not SuperRegistersEqual(reg1,reg2) then
  1270. exit(false);
  1271. if getregtype(reg1)<>R_INTREGISTER then
  1272. exit(true); {because SuperRegisterEqual is true}
  1273. case getsubreg(reg1) of
  1274. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1275. higher, it preserves the high bits, so the new value depends on
  1276. reg2's previous value. In other words, it is equivalent to doing:
  1277. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1278. R_SUBL:
  1279. exit(getsubreg(reg2)=R_SUBL);
  1280. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1281. higher, it actually does a:
  1282. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1283. R_SUBH:
  1284. exit(getsubreg(reg2)=R_SUBH);
  1285. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1286. bits of reg2:
  1287. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1288. R_SUBW:
  1289. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1290. { a write to R_SUBD always overwrites every other subregister,
  1291. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1292. R_SUBD,
  1293. R_SUBQ:
  1294. exit(true);
  1295. else
  1296. internalerror(2017042801);
  1297. end;
  1298. end;
  1299. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1300. begin
  1301. if not SuperRegistersEqual(reg1,reg2) then
  1302. exit(false);
  1303. if getregtype(reg1)<>R_INTREGISTER then
  1304. exit(true); {because SuperRegisterEqual is true}
  1305. case getsubreg(reg1) of
  1306. R_SUBL:
  1307. exit(getsubreg(reg2)<>R_SUBH);
  1308. R_SUBH:
  1309. exit(getsubreg(reg2)<>R_SUBL);
  1310. R_SUBW,
  1311. R_SUBD,
  1312. R_SUBQ:
  1313. exit(true);
  1314. else
  1315. internalerror(2017042802);
  1316. end;
  1317. end;
  1318. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1319. var
  1320. hp1 : tai;
  1321. l : TCGInt;
  1322. begin
  1323. result:=false;
  1324. { changes the code sequence
  1325. shr/sar const1, x
  1326. shl const2, x
  1327. to
  1328. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1329. if GetNextInstruction(p, hp1) and
  1330. MatchInstruction(hp1,A_SHL,[]) and
  1331. (taicpu(p).oper[0]^.typ = top_const) and
  1332. (taicpu(hp1).oper[0]^.typ = top_const) and
  1333. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1334. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1335. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1336. begin
  1337. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1338. not(cs_opt_size in current_settings.optimizerswitches) then
  1339. begin
  1340. { shr/sar const1, %reg
  1341. shl const2, %reg
  1342. with const1 > const2 }
  1343. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1344. taicpu(hp1).opcode := A_AND;
  1345. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1346. case taicpu(p).opsize Of
  1347. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1348. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1349. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1350. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1351. else
  1352. Internalerror(2017050703)
  1353. end;
  1354. end
  1355. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1356. not(cs_opt_size in current_settings.optimizerswitches) then
  1357. begin
  1358. { shr/sar const1, %reg
  1359. shl const2, %reg
  1360. with const1 < const2 }
  1361. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1362. taicpu(p).opcode := A_AND;
  1363. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1364. case taicpu(p).opsize Of
  1365. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1366. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1367. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1368. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1369. else
  1370. Internalerror(2017050702)
  1371. end;
  1372. end
  1373. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1374. begin
  1375. { shr/sar const1, %reg
  1376. shl const2, %reg
  1377. with const1 = const2 }
  1378. taicpu(p).opcode := A_AND;
  1379. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1380. case taicpu(p).opsize Of
  1381. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1382. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1383. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1384. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1385. else
  1386. Internalerror(2017050701)
  1387. end;
  1388. RemoveInstruction(hp1);
  1389. end;
  1390. end;
  1391. end;
  1392. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1393. var
  1394. opsize : topsize;
  1395. hp1, hp2 : tai;
  1396. tmpref : treference;
  1397. ShiftValue : Cardinal;
  1398. BaseValue : TCGInt;
  1399. begin
  1400. result:=false;
  1401. opsize:=taicpu(p).opsize;
  1402. { changes certain "imul const, %reg"'s to lea sequences }
  1403. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1404. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1405. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1406. if (taicpu(p).oper[0]^.val = 1) then
  1407. if (taicpu(p).ops = 2) then
  1408. { remove "imul $1, reg" }
  1409. begin
  1410. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1411. Result := RemoveCurrentP(p);
  1412. end
  1413. else
  1414. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1415. begin
  1416. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1417. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1418. asml.InsertAfter(hp1, p);
  1419. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1420. RemoveCurrentP(p, hp1);
  1421. Result := True;
  1422. end
  1423. else if ((taicpu(p).ops <= 2) or
  1424. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1425. not(cs_opt_size in current_settings.optimizerswitches) and
  1426. (not(GetNextInstruction(p, hp1)) or
  1427. not((tai(hp1).typ = ait_instruction) and
  1428. ((taicpu(hp1).opcode=A_Jcc) and
  1429. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1430. begin
  1431. {
  1432. imul X, reg1, reg2 to
  1433. lea (reg1,reg1,Y), reg2
  1434. shl ZZ,reg2
  1435. imul XX, reg1 to
  1436. lea (reg1,reg1,YY), reg1
  1437. shl ZZ,reg2
  1438. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1439. it does not exist as a separate optimization target in FPC though.
  1440. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1441. at most two zeros
  1442. }
  1443. reference_reset(tmpref,1,[]);
  1444. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1445. begin
  1446. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1447. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1448. TmpRef.base := taicpu(p).oper[1]^.reg;
  1449. TmpRef.index := taicpu(p).oper[1]^.reg;
  1450. if not(BaseValue in [3,5,9]) then
  1451. Internalerror(2018110101);
  1452. TmpRef.ScaleFactor := BaseValue-1;
  1453. if (taicpu(p).ops = 2) then
  1454. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1455. else
  1456. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1457. AsmL.InsertAfter(hp1,p);
  1458. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1459. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1460. RemoveCurrentP(p, hp1);
  1461. if ShiftValue>0 then
  1462. begin
  1463. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1464. AsmL.InsertAfter(hp2,hp1);
  1465. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1466. end;
  1467. Result := True;
  1468. end;
  1469. end;
  1470. end;
  1471. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1472. begin
  1473. Result := False;
  1474. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1475. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1476. begin
  1477. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1478. taicpu(p).opcode := A_MOV;
  1479. Result := True;
  1480. end;
  1481. end;
  1482. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1483. var
  1484. p: taicpu absolute hp; { Implicit typecast }
  1485. i: Integer;
  1486. begin
  1487. Result := False;
  1488. if not assigned(hp) or
  1489. (hp.typ <> ait_instruction) then
  1490. Exit;
  1491. Prefetch(insprop[p.opcode]);
  1492. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1493. with insprop[p.opcode] do
  1494. begin
  1495. case getsubreg(reg) of
  1496. R_SUBW,R_SUBD,R_SUBQ:
  1497. Result:=
  1498. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1499. uncommon flags are checked first }
  1500. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1501. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1502. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1503. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1504. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1505. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1506. R_SUBFLAGCARRY:
  1507. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1508. R_SUBFLAGPARITY:
  1509. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1510. R_SUBFLAGAUXILIARY:
  1511. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1512. R_SUBFLAGZERO:
  1513. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1514. R_SUBFLAGSIGN:
  1515. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1516. R_SUBFLAGOVERFLOW:
  1517. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1518. R_SUBFLAGINTERRUPT:
  1519. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1520. R_SUBFLAGDIRECTION:
  1521. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1522. else
  1523. internalerror(2017050501);
  1524. end;
  1525. exit;
  1526. end;
  1527. { Handle special cases first }
  1528. case p.opcode of
  1529. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1530. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1531. begin
  1532. Result :=
  1533. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1534. (p.oper[1]^.typ = top_reg) and
  1535. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1536. (
  1537. (p.oper[0]^.typ = top_const) or
  1538. (
  1539. (p.oper[0]^.typ = top_reg) and
  1540. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1541. ) or (
  1542. (p.oper[0]^.typ = top_ref) and
  1543. not RegInRef(reg,p.oper[0]^.ref^)
  1544. )
  1545. );
  1546. end;
  1547. A_MUL, A_IMUL:
  1548. Result :=
  1549. (
  1550. (p.ops=3) and { IMUL only }
  1551. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1552. (
  1553. (
  1554. (p.oper[1]^.typ=top_reg) and
  1555. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1556. ) or (
  1557. (p.oper[1]^.typ=top_ref) and
  1558. not RegInRef(reg,p.oper[1]^.ref^)
  1559. )
  1560. )
  1561. ) or (
  1562. (
  1563. (p.ops=1) and
  1564. (
  1565. (
  1566. (
  1567. (p.oper[0]^.typ=top_reg) and
  1568. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1569. )
  1570. ) or (
  1571. (p.oper[0]^.typ=top_ref) and
  1572. not RegInRef(reg,p.oper[0]^.ref^)
  1573. )
  1574. ) and (
  1575. (
  1576. (p.opsize=S_B) and
  1577. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1578. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1579. ) or (
  1580. (p.opsize=S_W) and
  1581. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1582. ) or (
  1583. (p.opsize=S_L) and
  1584. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1585. {$ifdef x86_64}
  1586. ) or (
  1587. (p.opsize=S_Q) and
  1588. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1589. {$endif x86_64}
  1590. )
  1591. )
  1592. )
  1593. );
  1594. A_CBW:
  1595. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1596. {$ifndef x86_64}
  1597. A_LDS:
  1598. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1599. A_LES:
  1600. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1601. {$endif not x86_64}
  1602. A_LFS:
  1603. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1604. A_LGS:
  1605. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1606. A_LSS:
  1607. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1608. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1609. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1610. A_LODSB:
  1611. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1612. A_LODSW:
  1613. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1614. {$ifdef x86_64}
  1615. A_LODSQ:
  1616. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1617. {$endif x86_64}
  1618. A_LODSD:
  1619. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1620. A_FSTSW, A_FNSTSW:
  1621. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1622. else
  1623. begin
  1624. with insprop[p.opcode] do
  1625. begin
  1626. if (
  1627. { xor %reg,%reg etc. is classed as a new value }
  1628. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1629. MatchOpType(p, top_reg, top_reg) and
  1630. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1631. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1632. ) then
  1633. begin
  1634. Result := True;
  1635. Exit;
  1636. end;
  1637. { Make sure the entire register is overwritten }
  1638. if (getregtype(reg) = R_INTREGISTER) then
  1639. begin
  1640. if (p.ops > 0) then
  1641. begin
  1642. if RegInOp(reg, p.oper[0]^) then
  1643. begin
  1644. if (p.oper[0]^.typ = top_ref) then
  1645. begin
  1646. if RegInRef(reg, p.oper[0]^.ref^) then
  1647. begin
  1648. Result := False;
  1649. Exit;
  1650. end;
  1651. end
  1652. else if (p.oper[0]^.typ = top_reg) then
  1653. begin
  1654. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1655. begin
  1656. Result := False;
  1657. Exit;
  1658. end
  1659. else if ([Ch_WOp1]*Ch<>[]) then
  1660. begin
  1661. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1662. Result := True
  1663. else
  1664. begin
  1665. Result := False;
  1666. Exit;
  1667. end;
  1668. end;
  1669. end;
  1670. end;
  1671. if (p.ops > 1) then
  1672. begin
  1673. if RegInOp(reg, p.oper[1]^) then
  1674. begin
  1675. if (p.oper[1]^.typ = top_ref) then
  1676. begin
  1677. if RegInRef(reg, p.oper[1]^.ref^) then
  1678. begin
  1679. Result := False;
  1680. Exit;
  1681. end;
  1682. end
  1683. else if (p.oper[1]^.typ = top_reg) then
  1684. begin
  1685. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1686. begin
  1687. Result := False;
  1688. Exit;
  1689. end
  1690. else if ([Ch_WOp2]*Ch<>[]) then
  1691. begin
  1692. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1693. Result := True
  1694. else
  1695. begin
  1696. Result := False;
  1697. Exit;
  1698. end;
  1699. end;
  1700. end;
  1701. end;
  1702. if (p.ops > 2) then
  1703. begin
  1704. if RegInOp(reg, p.oper[2]^) then
  1705. begin
  1706. if (p.oper[2]^.typ = top_ref) then
  1707. begin
  1708. if RegInRef(reg, p.oper[2]^.ref^) then
  1709. begin
  1710. Result := False;
  1711. Exit;
  1712. end;
  1713. end
  1714. else if (p.oper[2]^.typ = top_reg) then
  1715. begin
  1716. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1717. begin
  1718. Result := False;
  1719. Exit;
  1720. end
  1721. else if ([Ch_WOp3]*Ch<>[]) then
  1722. begin
  1723. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1724. Result := True
  1725. else
  1726. begin
  1727. Result := False;
  1728. Exit;
  1729. end;
  1730. end;
  1731. end;
  1732. end;
  1733. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1734. begin
  1735. if (p.oper[3]^.typ = top_ref) then
  1736. begin
  1737. if RegInRef(reg, p.oper[3]^.ref^) then
  1738. begin
  1739. Result := False;
  1740. Exit;
  1741. end;
  1742. end
  1743. else if (p.oper[3]^.typ = top_reg) then
  1744. begin
  1745. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1746. begin
  1747. Result := False;
  1748. Exit;
  1749. end
  1750. else if ([Ch_WOp4]*Ch<>[]) then
  1751. begin
  1752. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1753. Result := True
  1754. else
  1755. begin
  1756. Result := False;
  1757. Exit;
  1758. end;
  1759. end;
  1760. end;
  1761. end;
  1762. end;
  1763. end;
  1764. end;
  1765. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1766. case getsupreg(reg) of
  1767. RS_EAX:
  1768. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1769. begin
  1770. Result := True;
  1771. Exit;
  1772. end;
  1773. RS_ECX:
  1774. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1775. begin
  1776. Result := True;
  1777. Exit;
  1778. end;
  1779. RS_EDX:
  1780. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1781. begin
  1782. Result := True;
  1783. Exit;
  1784. end;
  1785. RS_EBX:
  1786. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1787. begin
  1788. Result := True;
  1789. Exit;
  1790. end;
  1791. RS_ESP:
  1792. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1793. begin
  1794. Result := True;
  1795. Exit;
  1796. end;
  1797. RS_EBP:
  1798. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1799. begin
  1800. Result := True;
  1801. Exit;
  1802. end;
  1803. RS_ESI:
  1804. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1805. begin
  1806. Result := True;
  1807. Exit;
  1808. end;
  1809. RS_EDI:
  1810. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1811. begin
  1812. Result := True;
  1813. Exit;
  1814. end;
  1815. else
  1816. ;
  1817. end;
  1818. end;
  1819. end;
  1820. end;
  1821. end;
  1822. end;
  1823. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1824. var
  1825. hp2,hp3 : tai;
  1826. begin
  1827. { some x86-64 issue a NOP before the real exit code }
  1828. if MatchInstruction(p,A_NOP,[]) then
  1829. GetNextInstruction(p,p);
  1830. result:=assigned(p) and (p.typ=ait_instruction) and
  1831. ((taicpu(p).opcode = A_RET) or
  1832. ((taicpu(p).opcode=A_LEAVE) and
  1833. GetNextInstruction(p,hp2) and
  1834. MatchInstruction(hp2,A_RET,[S_NO])
  1835. ) or
  1836. (((taicpu(p).opcode=A_LEA) and
  1837. MatchOpType(taicpu(p),top_ref,top_reg) and
  1838. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1839. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1840. ) and
  1841. GetNextInstruction(p,hp2) and
  1842. MatchInstruction(hp2,A_RET,[S_NO])
  1843. ) or
  1844. ((((taicpu(p).opcode=A_MOV) and
  1845. MatchOpType(taicpu(p),top_reg,top_reg) and
  1846. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1847. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1848. ((taicpu(p).opcode=A_LEA) and
  1849. MatchOpType(taicpu(p),top_ref,top_reg) and
  1850. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1851. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1852. )
  1853. ) and
  1854. GetNextInstruction(p,hp2) and
  1855. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1856. MatchOpType(taicpu(hp2),top_reg) and
  1857. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1858. GetNextInstruction(hp2,hp3) and
  1859. MatchInstruction(hp3,A_RET,[S_NO])
  1860. )
  1861. );
  1862. end;
  1863. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1864. begin
  1865. isFoldableArithOp := False;
  1866. case hp1.opcode of
  1867. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1868. isFoldableArithOp :=
  1869. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1870. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1871. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1872. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1873. (taicpu(hp1).oper[1]^.reg = reg);
  1874. A_INC,A_DEC,A_NEG,A_NOT:
  1875. isFoldableArithOp :=
  1876. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1877. (taicpu(hp1).oper[0]^.reg = reg);
  1878. else
  1879. ;
  1880. end;
  1881. end;
  1882. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1883. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1884. var
  1885. hp2: tai;
  1886. begin
  1887. hp2 := p;
  1888. repeat
  1889. hp2 := tai(hp2.previous);
  1890. if assigned(hp2) and
  1891. (hp2.typ = ait_regalloc) and
  1892. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1893. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1894. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1895. begin
  1896. RemoveInstruction(hp2);
  1897. break;
  1898. end;
  1899. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1900. end;
  1901. begin
  1902. case current_procinfo.procdef.returndef.typ of
  1903. arraydef,recorddef,pointerdef,
  1904. stringdef,enumdef,procdef,objectdef,errordef,
  1905. filedef,setdef,procvardef,
  1906. classrefdef,forwarddef:
  1907. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1908. orddef:
  1909. if current_procinfo.procdef.returndef.size <> 0 then
  1910. begin
  1911. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1912. { for int64/qword }
  1913. if current_procinfo.procdef.returndef.size = 8 then
  1914. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1915. end;
  1916. else
  1917. ;
  1918. end;
  1919. end;
  1920. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1921. var
  1922. hp1,hp2 : tai;
  1923. begin
  1924. result:=false;
  1925. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1926. begin
  1927. { vmova* reg1,reg1
  1928. =>
  1929. <nop> }
  1930. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1931. begin
  1932. RemoveCurrentP(p);
  1933. result:=true;
  1934. exit;
  1935. end
  1936. else if GetNextInstruction(p,hp1) then
  1937. begin
  1938. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1939. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1940. begin
  1941. { vmova* reg1,reg2
  1942. vmova* reg2,reg3
  1943. dealloc reg2
  1944. =>
  1945. vmova* reg1,reg3 }
  1946. TransferUsedRegs(TmpUsedRegs);
  1947. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1948. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1949. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1950. begin
  1951. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1952. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1953. RemoveInstruction(hp1);
  1954. result:=true;
  1955. exit;
  1956. end
  1957. { special case:
  1958. vmova* reg1,<op>
  1959. vmova* <op>,reg1
  1960. =>
  1961. vmova* reg1,<op> }
  1962. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1963. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1964. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1965. ) then
  1966. begin
  1967. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1968. RemoveInstruction(hp1);
  1969. result:=true;
  1970. exit;
  1971. end
  1972. end
  1973. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1974. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1975. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1976. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1977. ) and
  1978. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1979. begin
  1980. { vmova* reg1,reg2
  1981. vmovs* reg2,<op>
  1982. dealloc reg2
  1983. =>
  1984. vmovs* reg1,reg3 }
  1985. TransferUsedRegs(TmpUsedRegs);
  1986. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1987. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1988. begin
  1989. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1990. taicpu(p).opcode:=taicpu(hp1).opcode;
  1991. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1992. RemoveInstruction(hp1);
  1993. result:=true;
  1994. exit;
  1995. end
  1996. end;
  1997. end;
  1998. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1999. begin
  2000. if MatchInstruction(hp1,[A_VFMADDPD,
  2001. A_VFMADD132PD,
  2002. A_VFMADD132PS,
  2003. A_VFMADD132SD,
  2004. A_VFMADD132SS,
  2005. A_VFMADD213PD,
  2006. A_VFMADD213PS,
  2007. A_VFMADD213SD,
  2008. A_VFMADD213SS,
  2009. A_VFMADD231PD,
  2010. A_VFMADD231PS,
  2011. A_VFMADD231SD,
  2012. A_VFMADD231SS,
  2013. A_VFMADDSUB132PD,
  2014. A_VFMADDSUB132PS,
  2015. A_VFMADDSUB213PD,
  2016. A_VFMADDSUB213PS,
  2017. A_VFMADDSUB231PD,
  2018. A_VFMADDSUB231PS,
  2019. A_VFMSUB132PD,
  2020. A_VFMSUB132PS,
  2021. A_VFMSUB132SD,
  2022. A_VFMSUB132SS,
  2023. A_VFMSUB213PD,
  2024. A_VFMSUB213PS,
  2025. A_VFMSUB213SD,
  2026. A_VFMSUB213SS,
  2027. A_VFMSUB231PD,
  2028. A_VFMSUB231PS,
  2029. A_VFMSUB231SD,
  2030. A_VFMSUB231SS,
  2031. A_VFMSUBADD132PD,
  2032. A_VFMSUBADD132PS,
  2033. A_VFMSUBADD213PD,
  2034. A_VFMSUBADD213PS,
  2035. A_VFMSUBADD231PD,
  2036. A_VFMSUBADD231PS,
  2037. A_VFNMADD132PD,
  2038. A_VFNMADD132PS,
  2039. A_VFNMADD132SD,
  2040. A_VFNMADD132SS,
  2041. A_VFNMADD213PD,
  2042. A_VFNMADD213PS,
  2043. A_VFNMADD213SD,
  2044. A_VFNMADD213SS,
  2045. A_VFNMADD231PD,
  2046. A_VFNMADD231PS,
  2047. A_VFNMADD231SD,
  2048. A_VFNMADD231SS,
  2049. A_VFNMSUB132PD,
  2050. A_VFNMSUB132PS,
  2051. A_VFNMSUB132SD,
  2052. A_VFNMSUB132SS,
  2053. A_VFNMSUB213PD,
  2054. A_VFNMSUB213PS,
  2055. A_VFNMSUB213SD,
  2056. A_VFNMSUB213SS,
  2057. A_VFNMSUB231PD,
  2058. A_VFNMSUB231PS,
  2059. A_VFNMSUB231SD,
  2060. A_VFNMSUB231SS],[S_NO]) and
  2061. { we mix single and double opperations here because we assume that the compiler
  2062. generates vmovapd only after double operations and vmovaps only after single operations }
  2063. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  2064. GetNextInstruction(hp1,hp2) and
  2065. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2066. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2067. begin
  2068. TransferUsedRegs(TmpUsedRegs);
  2069. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2070. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2071. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2072. begin
  2073. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2074. RemoveCurrentP(p);
  2075. RemoveInstruction(hp2);
  2076. end;
  2077. end
  2078. else if (hp1.typ = ait_instruction) and
  2079. GetNextInstruction(hp1, hp2) and
  2080. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2081. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2082. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2083. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  2084. (((taicpu(p).opcode=A_MOVAPS) and
  2085. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2086. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2087. ((taicpu(p).opcode=A_MOVAPD) and
  2088. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2089. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2090. ) then
  2091. { change
  2092. movapX reg,reg2
  2093. addsX/subsX/... reg3, reg2
  2094. movapX reg2,reg
  2095. to
  2096. addsX/subsX/... reg3,reg
  2097. }
  2098. begin
  2099. TransferUsedRegs(TmpUsedRegs);
  2100. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2101. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2102. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2103. begin
  2104. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2105. debug_op2str(taicpu(p).opcode)+' '+
  2106. debug_op2str(taicpu(hp1).opcode)+' '+
  2107. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2108. { we cannot eliminate the first move if
  2109. the operations uses the same register for source and dest }
  2110. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2111. { Remember that hp1 is not necessarily the immediate
  2112. next instruction }
  2113. RemoveCurrentP(p);
  2114. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2115. RemoveInstruction(hp2);
  2116. result:=true;
  2117. end;
  2118. end
  2119. else if (hp1.typ = ait_instruction) and
  2120. (((taicpu(p).opcode=A_VMOVAPD) and
  2121. (taicpu(hp1).opcode=A_VCOMISD)) or
  2122. ((taicpu(p).opcode=A_VMOVAPS) and
  2123. ((taicpu(hp1).opcode=A_VCOMISS))
  2124. )
  2125. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2126. { change
  2127. movapX reg,reg1
  2128. vcomisX reg1,reg1
  2129. to
  2130. vcomisX reg,reg
  2131. }
  2132. begin
  2133. TransferUsedRegs(TmpUsedRegs);
  2134. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2135. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2136. begin
  2137. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2138. debug_op2str(taicpu(p).opcode)+' '+
  2139. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2140. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2141. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2142. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2143. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2144. RemoveCurrentP(p);
  2145. result:=true;
  2146. exit;
  2147. end;
  2148. end
  2149. end;
  2150. end;
  2151. end;
  2152. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2153. var
  2154. hp1 : tai;
  2155. begin
  2156. result:=false;
  2157. { replace
  2158. V<Op>X %mreg1,%mreg2,%mreg3
  2159. VMovX %mreg3,%mreg4
  2160. dealloc %mreg3
  2161. by
  2162. V<Op>X %mreg1,%mreg2,%mreg4
  2163. ?
  2164. }
  2165. if GetNextInstruction(p,hp1) and
  2166. { we mix single and double operations here because we assume that the compiler
  2167. generates vmovapd only after double operations and vmovaps only after single operations }
  2168. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2169. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2170. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2171. begin
  2172. TransferUsedRegs(TmpUsedRegs);
  2173. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2174. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2175. begin
  2176. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2177. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2178. RemoveInstruction(hp1);
  2179. result:=true;
  2180. end;
  2181. end;
  2182. end;
  2183. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2184. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2185. begin
  2186. Result := False;
  2187. { For safety reasons, only check for exact register matches }
  2188. { Check base register }
  2189. if (ref.base = AOldReg) then
  2190. begin
  2191. ref.base := ANewReg;
  2192. Result := True;
  2193. end;
  2194. { Check index register }
  2195. if (ref.index = AOldReg) then
  2196. begin
  2197. ref.index := ANewReg;
  2198. Result := True;
  2199. end;
  2200. end;
  2201. { Replaces all references to AOldReg in an operand to ANewReg }
  2202. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2203. var
  2204. OldSupReg, NewSupReg: TSuperRegister;
  2205. OldSubReg, NewSubReg: TSubRegister;
  2206. OldRegType: TRegisterType;
  2207. ThisOper: POper;
  2208. begin
  2209. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2210. Result := False;
  2211. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2212. InternalError(2020011801);
  2213. OldSupReg := getsupreg(AOldReg);
  2214. OldSubReg := getsubreg(AOldReg);
  2215. OldRegType := getregtype(AOldReg);
  2216. NewSupReg := getsupreg(ANewReg);
  2217. NewSubReg := getsubreg(ANewReg);
  2218. if OldRegType <> getregtype(ANewReg) then
  2219. InternalError(2020011802);
  2220. if OldSubReg <> NewSubReg then
  2221. InternalError(2020011803);
  2222. case ThisOper^.typ of
  2223. top_reg:
  2224. if (
  2225. (ThisOper^.reg = AOldReg) or
  2226. (
  2227. (OldRegType = R_INTREGISTER) and
  2228. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2229. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2230. (
  2231. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2232. {$ifndef x86_64}
  2233. and (
  2234. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2235. don't have an 8-bit representation }
  2236. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2237. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2238. )
  2239. {$endif x86_64}
  2240. )
  2241. )
  2242. ) then
  2243. begin
  2244. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2245. Result := True;
  2246. end;
  2247. top_ref:
  2248. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2249. Result := True;
  2250. else
  2251. ;
  2252. end;
  2253. end;
  2254. { Replaces all references to AOldReg in an instruction to ANewReg }
  2255. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2256. const
  2257. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2258. var
  2259. OperIdx: Integer;
  2260. begin
  2261. Result := False;
  2262. for OperIdx := 0 to p.ops - 1 do
  2263. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2264. begin
  2265. { The shift and rotate instructions can only use CL }
  2266. if not (
  2267. (OperIdx = 0) and
  2268. { This second condition just helps to avoid unnecessarily
  2269. calling MatchInstruction for 10 different opcodes }
  2270. (p.oper[0]^.reg = NR_CL) and
  2271. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2272. ) then
  2273. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2274. end
  2275. else if p.oper[OperIdx]^.typ = top_ref then
  2276. { It's okay to replace registers in references that get written to }
  2277. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2278. end;
  2279. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2280. begin
  2281. with ref^ do
  2282. Result :=
  2283. (index = NR_NO) and
  2284. (
  2285. {$ifdef x86_64}
  2286. (
  2287. (base = NR_RIP) and
  2288. (refaddr in [addr_pic, addr_pic_no_got])
  2289. ) or
  2290. {$endif x86_64}
  2291. (base = NR_STACK_POINTER_REG) or
  2292. (base = current_procinfo.framepointer)
  2293. );
  2294. end;
  2295. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2296. var
  2297. l: asizeint;
  2298. begin
  2299. Result := False;
  2300. { Should have been checked previously }
  2301. if p.opcode <> A_LEA then
  2302. InternalError(2020072501);
  2303. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2304. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2305. not(cs_opt_size in current_settings.optimizerswitches) then
  2306. exit;
  2307. with p.oper[0]^.ref^ do
  2308. begin
  2309. if (base <> p.oper[1]^.reg) or
  2310. (index <> NR_NO) or
  2311. assigned(symbol) then
  2312. exit;
  2313. l:=offset;
  2314. if (l=1) and UseIncDec then
  2315. begin
  2316. p.opcode:=A_INC;
  2317. p.loadreg(0,p.oper[1]^.reg);
  2318. p.ops:=1;
  2319. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2320. end
  2321. else if (l=-1) and UseIncDec then
  2322. begin
  2323. p.opcode:=A_DEC;
  2324. p.loadreg(0,p.oper[1]^.reg);
  2325. p.ops:=1;
  2326. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2327. end
  2328. else
  2329. begin
  2330. if (l<0) and (l<>-2147483648) then
  2331. begin
  2332. p.opcode:=A_SUB;
  2333. p.loadConst(0,-l);
  2334. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2335. end
  2336. else
  2337. begin
  2338. p.opcode:=A_ADD;
  2339. p.loadConst(0,l);
  2340. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2341. end;
  2342. end;
  2343. end;
  2344. Result := True;
  2345. end;
  2346. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2347. var
  2348. CurrentReg, ReplaceReg: TRegister;
  2349. begin
  2350. Result := False;
  2351. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2352. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2353. case hp.opcode of
  2354. A_FSTSW, A_FNSTSW,
  2355. A_IN, A_INS, A_OUT, A_OUTS,
  2356. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2357. { These routines have explicit operands, but they are restricted in
  2358. what they can be (e.g. IN and OUT can only read from AL, AX or
  2359. EAX. }
  2360. Exit;
  2361. A_IMUL:
  2362. begin
  2363. { The 1-operand version writes to implicit registers
  2364. The 2-operand version reads from the first operator, and reads
  2365. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2366. the 3-operand version reads from a register that it doesn't write to
  2367. }
  2368. case hp.ops of
  2369. 1:
  2370. if (
  2371. (
  2372. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2373. ) or
  2374. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2375. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2376. begin
  2377. Result := True;
  2378. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2379. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2380. end;
  2381. 2:
  2382. { Only modify the first parameter }
  2383. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2384. begin
  2385. Result := True;
  2386. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2387. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2388. end;
  2389. 3:
  2390. { Only modify the second parameter }
  2391. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2392. begin
  2393. Result := True;
  2394. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2395. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2396. end;
  2397. else
  2398. InternalError(2020012901);
  2399. end;
  2400. end;
  2401. else
  2402. if (hp.ops > 0) and
  2403. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2404. begin
  2405. Result := True;
  2406. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2407. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2408. end;
  2409. end;
  2410. end;
  2411. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2412. var
  2413. hp1, hp2, hp3: tai;
  2414. DoOptimisation, TempBool: Boolean;
  2415. {$ifdef x86_64}
  2416. NewConst: TCGInt;
  2417. {$endif x86_64}
  2418. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2419. begin
  2420. if taicpu(hp1).opcode = signed_movop then
  2421. begin
  2422. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2423. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2424. end
  2425. else
  2426. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2427. end;
  2428. function TryConstMerge(var p1, p2: tai): Boolean;
  2429. var
  2430. ThisRef: TReference;
  2431. begin
  2432. Result := False;
  2433. ThisRef := taicpu(p2).oper[1]^.ref^;
  2434. { Only permit writes to the stack, since we can guarantee alignment with that }
  2435. if (ThisRef.index = NR_NO) and
  2436. (
  2437. (ThisRef.base = NR_STACK_POINTER_REG) or
  2438. (ThisRef.base = current_procinfo.framepointer)
  2439. ) then
  2440. begin
  2441. case taicpu(p).opsize of
  2442. S_B:
  2443. begin
  2444. { Word writes must be on a 2-byte boundary }
  2445. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2446. begin
  2447. { Reduce offset of second reference to see if it is sequential with the first }
  2448. Dec(ThisRef.offset, 1);
  2449. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2450. begin
  2451. { Make sure the constants aren't represented as a
  2452. negative number, as these won't merge properly }
  2453. taicpu(p1).opsize := S_W;
  2454. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2455. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2456. RemoveInstruction(p2);
  2457. Result := True;
  2458. end;
  2459. end;
  2460. end;
  2461. S_W:
  2462. begin
  2463. { Longword writes must be on a 4-byte boundary }
  2464. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2465. begin
  2466. { Reduce offset of second reference to see if it is sequential with the first }
  2467. Dec(ThisRef.offset, 2);
  2468. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2469. begin
  2470. { Make sure the constants aren't represented as a
  2471. negative number, as these won't merge properly }
  2472. taicpu(p1).opsize := S_L;
  2473. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2474. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2475. RemoveInstruction(p2);
  2476. Result := True;
  2477. end;
  2478. end;
  2479. end;
  2480. {$ifdef x86_64}
  2481. S_L:
  2482. begin
  2483. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2484. see if the constants can be encoded this way. }
  2485. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2486. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2487. { Quadword writes must be on an 8-byte boundary }
  2488. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2489. begin
  2490. { Reduce offset of second reference to see if it is sequential with the first }
  2491. Dec(ThisRef.offset, 4);
  2492. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2493. begin
  2494. { Make sure the constants aren't represented as a
  2495. negative number, as these won't merge properly }
  2496. taicpu(p1).opsize := S_Q;
  2497. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2498. taicpu(p1).oper[0]^.val := NewConst;
  2499. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2500. RemoveInstruction(p2);
  2501. Result := True;
  2502. end;
  2503. end;
  2504. end;
  2505. {$endif x86_64}
  2506. else
  2507. ;
  2508. end;
  2509. end;
  2510. end;
  2511. var
  2512. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2513. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2514. NewSize: topsize;
  2515. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2516. SourceRef, TargetRef: TReference;
  2517. MovAligned, MovUnaligned: TAsmOp;
  2518. ThisRef: TReference;
  2519. JumpTracking: TLinkedList;
  2520. begin
  2521. Result:=false;
  2522. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2523. { remove mov reg1,reg1? }
  2524. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2525. then
  2526. begin
  2527. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2528. { take care of the register (de)allocs following p }
  2529. RemoveCurrentP(p, hp1);
  2530. Result:=true;
  2531. exit;
  2532. end;
  2533. { All the next optimisations require a next instruction }
  2534. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2535. Exit;
  2536. { Prevent compiler warnings }
  2537. p_TargetReg := NR_NO;
  2538. if taicpu(p).oper[1]^.typ = top_reg then
  2539. begin
  2540. { Saves on a large number of dereferences }
  2541. p_TargetReg := taicpu(p).oper[1]^.reg;
  2542. { Look for:
  2543. mov %reg1,%reg2
  2544. ??? %reg2,r/m
  2545. Change to:
  2546. mov %reg1,%reg2
  2547. ??? %reg1,r/m
  2548. }
  2549. if taicpu(p).oper[0]^.typ = top_reg then
  2550. begin
  2551. if RegReadByInstruction(p_TargetReg, hp1) and
  2552. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2553. begin
  2554. { A change has occurred, just not in p }
  2555. Result := True;
  2556. TransferUsedRegs(TmpUsedRegs);
  2557. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2558. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2559. { Just in case something didn't get modified (e.g. an
  2560. implicit register) }
  2561. not RegReadByInstruction(p_TargetReg, hp1) then
  2562. begin
  2563. { We can remove the original MOV }
  2564. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2565. RemoveCurrentp(p, hp1);
  2566. { UsedRegs got updated by RemoveCurrentp }
  2567. Result := True;
  2568. Exit;
  2569. end;
  2570. { If we know a MOV instruction has become a null operation, we might as well
  2571. get rid of it now to save time. }
  2572. if (taicpu(hp1).opcode = A_MOV) and
  2573. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2574. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2575. { Just being a register is enough to confirm it's a null operation }
  2576. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2577. begin
  2578. Result := True;
  2579. { Speed-up to reduce a pipeline stall... if we had something like...
  2580. movl %eax,%edx
  2581. movw %dx,%ax
  2582. ... the second instruction would change to movw %ax,%ax, but
  2583. given that it is now %ax that's active rather than %eax,
  2584. penalties might occur due to a partial register write, so instead,
  2585. change it to a MOVZX instruction when optimising for speed.
  2586. }
  2587. if not (cs_opt_size in current_settings.optimizerswitches) and
  2588. IsMOVZXAcceptable and
  2589. (taicpu(hp1).opsize < taicpu(p).opsize)
  2590. {$ifdef x86_64}
  2591. { operations already implicitly set the upper 64 bits to zero }
  2592. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2593. {$endif x86_64}
  2594. then
  2595. begin
  2596. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2597. case taicpu(p).opsize of
  2598. S_W:
  2599. if taicpu(hp1).opsize = S_B then
  2600. taicpu(hp1).opsize := S_BL
  2601. else
  2602. InternalError(2020012911);
  2603. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2604. case taicpu(hp1).opsize of
  2605. S_B:
  2606. taicpu(hp1).opsize := S_BL;
  2607. S_W:
  2608. taicpu(hp1).opsize := S_WL;
  2609. else
  2610. InternalError(2020012912);
  2611. end;
  2612. else
  2613. InternalError(2020012910);
  2614. end;
  2615. taicpu(hp1).opcode := A_MOVZX;
  2616. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2617. end
  2618. else
  2619. begin
  2620. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2621. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2622. RemoveInstruction(hp1);
  2623. { The instruction after what was hp1 is now the immediate next instruction,
  2624. so we can continue to make optimisations if it's present }
  2625. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2626. Exit;
  2627. hp1 := hp2;
  2628. end;
  2629. end;
  2630. end;
  2631. end;
  2632. end;
  2633. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2634. overwrites the original destination register. e.g.
  2635. movl ###,%reg2d
  2636. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2637. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2638. }
  2639. if (taicpu(p).oper[1]^.typ = top_reg) and
  2640. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2641. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2642. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2643. begin
  2644. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2645. begin
  2646. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2647. case taicpu(p).oper[0]^.typ of
  2648. top_const:
  2649. { We have something like:
  2650. movb $x, %regb
  2651. movzbl %regb,%regd
  2652. Change to:
  2653. movl $x, %regd
  2654. }
  2655. begin
  2656. case taicpu(hp1).opsize of
  2657. S_BW:
  2658. begin
  2659. convert_mov_value(A_MOVSX, $FF);
  2660. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2661. taicpu(p).opsize := S_W;
  2662. end;
  2663. S_BL:
  2664. begin
  2665. convert_mov_value(A_MOVSX, $FF);
  2666. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2667. taicpu(p).opsize := S_L;
  2668. end;
  2669. S_WL:
  2670. begin
  2671. convert_mov_value(A_MOVSX, $FFFF);
  2672. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2673. taicpu(p).opsize := S_L;
  2674. end;
  2675. {$ifdef x86_64}
  2676. S_BQ:
  2677. begin
  2678. convert_mov_value(A_MOVSX, $FF);
  2679. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2680. taicpu(p).opsize := S_Q;
  2681. end;
  2682. S_WQ:
  2683. begin
  2684. convert_mov_value(A_MOVSX, $FFFF);
  2685. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2686. taicpu(p).opsize := S_Q;
  2687. end;
  2688. S_LQ:
  2689. begin
  2690. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2691. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2692. taicpu(p).opsize := S_Q;
  2693. end;
  2694. {$endif x86_64}
  2695. else
  2696. { If hp1 was a MOV instruction, it should have been
  2697. optimised already }
  2698. InternalError(2020021001);
  2699. end;
  2700. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2701. RemoveInstruction(hp1);
  2702. Result := True;
  2703. Exit;
  2704. end;
  2705. top_ref:
  2706. begin
  2707. { We have something like:
  2708. movb mem, %regb
  2709. movzbl %regb,%regd
  2710. Change to:
  2711. movzbl mem, %regd
  2712. }
  2713. ThisRef := taicpu(p).oper[0]^.ref^;
  2714. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2715. begin
  2716. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2717. taicpu(hp1).loadref(0, ThisRef);
  2718. { Make sure any registers in the references are properly tracked }
  2719. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2720. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2721. if (ThisRef.index <> NR_NO) then
  2722. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2723. RemoveCurrentP(p, hp1);
  2724. Result := True;
  2725. Exit;
  2726. end;
  2727. end;
  2728. else
  2729. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2730. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2731. Exit;
  2732. end;
  2733. end
  2734. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2735. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2736. optimised }
  2737. else
  2738. begin
  2739. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2740. RemoveCurrentP(p, hp1);
  2741. Result := True;
  2742. Exit;
  2743. end;
  2744. end;
  2745. if (taicpu(hp1).opcode = A_AND) and
  2746. (taicpu(p).oper[1]^.typ = top_reg) and
  2747. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2748. begin
  2749. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2750. begin
  2751. case taicpu(p).opsize of
  2752. S_L:
  2753. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2754. begin
  2755. { Optimize out:
  2756. mov x, %reg
  2757. and ffffffffh, %reg
  2758. }
  2759. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2760. RemoveInstruction(hp1);
  2761. Result:=true;
  2762. exit;
  2763. end;
  2764. S_Q: { TODO: Confirm if this is even possible }
  2765. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2766. begin
  2767. { Optimize out:
  2768. mov x, %reg
  2769. and ffffffffffffffffh, %reg
  2770. }
  2771. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2772. RemoveInstruction(hp1);
  2773. Result:=true;
  2774. exit;
  2775. end;
  2776. else
  2777. ;
  2778. end;
  2779. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2780. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2781. GetNextInstruction(hp1,hp2) and
  2782. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2783. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2784. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2785. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2786. GetNextInstruction(hp2,hp3) and
  2787. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2788. (taicpu(hp3).condition in [C_E,C_NE]) then
  2789. begin
  2790. TransferUsedRegs(TmpUsedRegs);
  2791. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2792. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2793. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2794. begin
  2795. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2796. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2797. taicpu(hp1).opcode:=A_TEST;
  2798. RemoveInstruction(hp2);
  2799. RemoveCurrentP(p, hp1);
  2800. Result:=true;
  2801. exit;
  2802. end;
  2803. end;
  2804. end
  2805. else if IsMOVZXAcceptable and
  2806. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2807. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2808. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2809. then
  2810. begin
  2811. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2812. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2813. case taicpu(p).opsize of
  2814. S_B:
  2815. if (taicpu(hp1).oper[0]^.val = $ff) then
  2816. begin
  2817. { Convert:
  2818. movb x, %regl movb x, %regl
  2819. andw ffh, %regw andl ffh, %regd
  2820. To:
  2821. movzbw x, %regd movzbl x, %regd
  2822. (Identical registers, just different sizes)
  2823. }
  2824. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2825. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2826. case taicpu(hp1).opsize of
  2827. S_W: NewSize := S_BW;
  2828. S_L: NewSize := S_BL;
  2829. {$ifdef x86_64}
  2830. S_Q: NewSize := S_BQ;
  2831. {$endif x86_64}
  2832. else
  2833. InternalError(2018011510);
  2834. end;
  2835. end
  2836. else
  2837. NewSize := S_NO;
  2838. S_W:
  2839. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2840. begin
  2841. { Convert:
  2842. movw x, %regw
  2843. andl ffffh, %regd
  2844. To:
  2845. movzwl x, %regd
  2846. (Identical registers, just different sizes)
  2847. }
  2848. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2849. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2850. case taicpu(hp1).opsize of
  2851. S_L: NewSize := S_WL;
  2852. {$ifdef x86_64}
  2853. S_Q: NewSize := S_WQ;
  2854. {$endif x86_64}
  2855. else
  2856. InternalError(2018011511);
  2857. end;
  2858. end
  2859. else
  2860. NewSize := S_NO;
  2861. else
  2862. NewSize := S_NO;
  2863. end;
  2864. if NewSize <> S_NO then
  2865. begin
  2866. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2867. { The actual optimization }
  2868. taicpu(p).opcode := A_MOVZX;
  2869. taicpu(p).changeopsize(NewSize);
  2870. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2871. { Safeguard if "and" is followed by a conditional command }
  2872. TransferUsedRegs(TmpUsedRegs);
  2873. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2874. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2875. begin
  2876. { At this point, the "and" command is effectively equivalent to
  2877. "test %reg,%reg". This will be handled separately by the
  2878. Peephole Optimizer. [Kit] }
  2879. DebugMsg(SPeepholeOptimization + PreMessage +
  2880. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2881. end
  2882. else
  2883. begin
  2884. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2885. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2886. RemoveInstruction(hp1);
  2887. end;
  2888. Result := True;
  2889. Exit;
  2890. end;
  2891. end;
  2892. end;
  2893. if (taicpu(hp1).opcode = A_OR) and
  2894. (taicpu(p).oper[1]^.typ = top_reg) and
  2895. MatchOperand(taicpu(p).oper[0]^, 0) and
  2896. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2897. begin
  2898. { mov 0, %reg
  2899. or ###,%reg
  2900. Change to (only if the flags are not used):
  2901. mov ###,%reg
  2902. }
  2903. TransferUsedRegs(TmpUsedRegs);
  2904. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2905. DoOptimisation := True;
  2906. { Even if the flags are used, we might be able to do the optimisation
  2907. if the conditions are predictable }
  2908. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2909. begin
  2910. { Only perform if ### = %reg (the same register) or equal to 0,
  2911. so %reg is guaranteed to still have a value of zero }
  2912. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2913. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2914. begin
  2915. hp2 := hp1;
  2916. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2917. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2918. GetNextInstruction(hp2, hp3) do
  2919. begin
  2920. { Don't continue modifying if the flags state is getting changed }
  2921. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2922. Break;
  2923. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2924. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2925. begin
  2926. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2927. begin
  2928. { Condition is always true }
  2929. case taicpu(hp3).opcode of
  2930. A_Jcc:
  2931. begin
  2932. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2933. { Check for jump shortcuts before we destroy the condition }
  2934. DoJumpOptimizations(hp3, TempBool);
  2935. MakeUnconditional(taicpu(hp3));
  2936. Result := True;
  2937. end;
  2938. A_CMOVcc:
  2939. begin
  2940. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2941. taicpu(hp3).opcode := A_MOV;
  2942. taicpu(hp3).condition := C_None;
  2943. Result := True;
  2944. end;
  2945. A_SETcc:
  2946. begin
  2947. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2948. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2949. taicpu(hp3).opcode := A_MOV;
  2950. taicpu(hp3).ops := 2;
  2951. taicpu(hp3).condition := C_None;
  2952. taicpu(hp3).opsize := S_B;
  2953. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2954. taicpu(hp3).loadconst(0, 1);
  2955. Result := True;
  2956. end;
  2957. else
  2958. InternalError(2021090701);
  2959. end;
  2960. end
  2961. 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
  2962. begin
  2963. { Condition is always false }
  2964. case taicpu(hp3).opcode of
  2965. A_Jcc:
  2966. begin
  2967. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2968. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2969. RemoveInstruction(hp3);
  2970. Result := True;
  2971. { Since hp3 was deleted, hp2 must not be updated }
  2972. Continue;
  2973. end;
  2974. A_CMOVcc:
  2975. begin
  2976. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2977. RemoveInstruction(hp3);
  2978. Result := True;
  2979. { Since hp3 was deleted, hp2 must not be updated }
  2980. Continue;
  2981. end;
  2982. A_SETcc:
  2983. begin
  2984. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2985. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2986. taicpu(hp3).opcode := A_MOV;
  2987. taicpu(hp3).ops := 2;
  2988. taicpu(hp3).condition := C_None;
  2989. taicpu(hp3).opsize := S_B;
  2990. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2991. taicpu(hp3).loadconst(0, 0);
  2992. Result := True;
  2993. end;
  2994. else
  2995. InternalError(2021090702);
  2996. end;
  2997. end
  2998. else
  2999. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3000. DoOptimisation := False;
  3001. end;
  3002. hp2 := hp3;
  3003. end;
  3004. { Flags are still in use - don't optimise }
  3005. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3006. DoOptimisation := False;
  3007. end
  3008. else
  3009. DoOptimisation := False;
  3010. end;
  3011. if DoOptimisation then
  3012. begin
  3013. {$ifdef x86_64}
  3014. { OR only supports 32-bit sign-extended constants for 64-bit
  3015. instructions, so compensate for this if the constant is
  3016. encoded as a value greater than or equal to 2^31 }
  3017. if (taicpu(hp1).opsize = S_Q) and
  3018. (taicpu(hp1).oper[0]^.typ = top_const) and
  3019. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3020. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3021. {$endif x86_64}
  3022. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3023. taicpu(hp1).opcode := A_MOV;
  3024. RemoveCurrentP(p, hp1);
  3025. Result := True;
  3026. Exit;
  3027. end;
  3028. end;
  3029. { Next instruction is also a MOV ? }
  3030. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3031. begin
  3032. if MatchOpType(taicpu(p), top_const, top_ref) and
  3033. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3034. TryConstMerge(p, hp1) then
  3035. begin
  3036. Result := True;
  3037. { In case we have four byte writes in a row, check for 2 more
  3038. right now so we don't have to wait for another iteration of
  3039. pass 1
  3040. }
  3041. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3042. case taicpu(p).opsize of
  3043. S_W:
  3044. begin
  3045. if GetNextInstruction(p, hp1) and
  3046. MatchInstruction(hp1, A_MOV, [S_B]) and
  3047. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3048. GetNextInstruction(hp1, hp2) and
  3049. MatchInstruction(hp2, A_MOV, [S_B]) and
  3050. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3051. { Try to merge the two bytes }
  3052. TryConstMerge(hp1, hp2) then
  3053. { Now try to merge the two words (hp2 will get deleted) }
  3054. TryConstMerge(p, hp1);
  3055. end;
  3056. S_L:
  3057. begin
  3058. { Though this only really benefits x86_64 and not i386, it
  3059. gets a potential optimisation done faster and hence
  3060. reduces the number of times OptPass1MOV is entered }
  3061. if GetNextInstruction(p, hp1) and
  3062. MatchInstruction(hp1, A_MOV, [S_W]) and
  3063. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3064. GetNextInstruction(hp1, hp2) and
  3065. MatchInstruction(hp2, A_MOV, [S_W]) and
  3066. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3067. { Try to merge the two words }
  3068. TryConstMerge(hp1, hp2) then
  3069. { This will always fail on i386, so don't bother
  3070. calling it unless we're doing x86_64 }
  3071. {$ifdef x86_64}
  3072. { Now try to merge the two longwords (hp2 will get deleted) }
  3073. TryConstMerge(p, hp1)
  3074. {$endif x86_64}
  3075. ;
  3076. end;
  3077. else
  3078. ;
  3079. end;
  3080. Exit;
  3081. end;
  3082. if (taicpu(p).oper[1]^.typ = top_reg) and
  3083. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3084. begin
  3085. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3086. TransferUsedRegs(TmpUsedRegs);
  3087. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3088. { we have
  3089. mov x, %treg
  3090. mov %treg, y
  3091. }
  3092. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3093. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3094. { we've got
  3095. mov x, %treg
  3096. mov %treg, y
  3097. with %treg is not used after }
  3098. case taicpu(p).oper[0]^.typ Of
  3099. { top_reg is covered by DeepMOVOpt }
  3100. top_const:
  3101. begin
  3102. { change
  3103. mov const, %treg
  3104. mov %treg, y
  3105. to
  3106. mov const, y
  3107. }
  3108. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3109. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3110. begin
  3111. if taicpu(hp1).oper[1]^.typ=top_reg then
  3112. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3113. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3114. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3115. RemoveInstruction(hp1);
  3116. Result:=true;
  3117. Exit;
  3118. end;
  3119. end;
  3120. top_ref:
  3121. case taicpu(hp1).oper[1]^.typ of
  3122. top_reg:
  3123. begin
  3124. { change
  3125. mov mem, %treg
  3126. mov %treg, %reg
  3127. to
  3128. mov mem, %reg"
  3129. }
  3130. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3131. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3132. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3133. RemoveInstruction(hp1);
  3134. Result:=true;
  3135. Exit;
  3136. end;
  3137. top_ref:
  3138. begin
  3139. {$ifdef x86_64}
  3140. { Look for the following to simplify:
  3141. mov x(mem1), %reg
  3142. mov %reg, y(mem2)
  3143. mov x+8(mem1), %reg
  3144. mov %reg, y+8(mem2)
  3145. Change to:
  3146. movdqu x(mem1), %xmmreg
  3147. movdqu %xmmreg, y(mem2)
  3148. ...but only as long as the memory blocks don't overlap
  3149. }
  3150. SourceRef := taicpu(p).oper[0]^.ref^;
  3151. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3152. if (taicpu(p).opsize = S_Q) and
  3153. GetNextInstruction(hp1, hp2) and
  3154. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3155. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3156. begin
  3157. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3158. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3159. Inc(SourceRef.offset, 8);
  3160. if UseAVX then
  3161. begin
  3162. MovAligned := A_VMOVDQA;
  3163. MovUnaligned := A_VMOVDQU;
  3164. end
  3165. else
  3166. begin
  3167. MovAligned := A_MOVDQA;
  3168. MovUnaligned := A_MOVDQU;
  3169. end;
  3170. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3171. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3172. begin
  3173. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3174. Inc(TargetRef.offset, 8);
  3175. if GetNextInstruction(hp2, hp3) and
  3176. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3177. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3178. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3179. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3180. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3181. begin
  3182. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3183. if NewMMReg <> NR_NO then
  3184. begin
  3185. { Remember that the offsets are 8 ahead }
  3186. if ((SourceRef.offset mod 16) = 8) and
  3187. (
  3188. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3189. (SourceRef.base = current_procinfo.framepointer) or
  3190. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3191. ) then
  3192. taicpu(p).opcode := MovAligned
  3193. else
  3194. taicpu(p).opcode := MovUnaligned;
  3195. taicpu(p).opsize := S_XMM;
  3196. taicpu(p).oper[1]^.reg := NewMMReg;
  3197. if ((TargetRef.offset mod 16) = 8) and
  3198. (
  3199. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3200. (TargetRef.base = current_procinfo.framepointer) or
  3201. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3202. ) then
  3203. taicpu(hp1).opcode := MovAligned
  3204. else
  3205. taicpu(hp1).opcode := MovUnaligned;
  3206. taicpu(hp1).opsize := S_XMM;
  3207. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3208. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3209. RemoveInstruction(hp2);
  3210. RemoveInstruction(hp3);
  3211. Result := True;
  3212. Exit;
  3213. end;
  3214. end;
  3215. end
  3216. else
  3217. begin
  3218. { See if the next references are 8 less rather than 8 greater }
  3219. Dec(SourceRef.offset, 16); { -8 the other way }
  3220. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3221. begin
  3222. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3223. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3224. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3225. GetNextInstruction(hp2, hp3) and
  3226. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3227. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3228. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3229. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3230. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3231. begin
  3232. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3233. if NewMMReg <> NR_NO then
  3234. begin
  3235. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3236. if ((SourceRef.offset mod 16) = 0) and
  3237. (
  3238. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3239. (SourceRef.base = current_procinfo.framepointer) or
  3240. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3241. ) then
  3242. taicpu(hp2).opcode := MovAligned
  3243. else
  3244. taicpu(hp2).opcode := MovUnaligned;
  3245. taicpu(hp2).opsize := S_XMM;
  3246. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3247. if ((TargetRef.offset mod 16) = 0) and
  3248. (
  3249. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3250. (TargetRef.base = current_procinfo.framepointer) or
  3251. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3252. ) then
  3253. taicpu(hp3).opcode := MovAligned
  3254. else
  3255. taicpu(hp3).opcode := MovUnaligned;
  3256. taicpu(hp3).opsize := S_XMM;
  3257. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3258. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3259. RemoveInstruction(hp1);
  3260. RemoveCurrentP(p, hp2);
  3261. Result := True;
  3262. Exit;
  3263. end;
  3264. end;
  3265. end;
  3266. end;
  3267. end;
  3268. {$endif x86_64}
  3269. end;
  3270. else
  3271. { The write target should be a reg or a ref }
  3272. InternalError(2021091601);
  3273. end;
  3274. else
  3275. ;
  3276. end
  3277. else
  3278. { %treg is used afterwards, but all eventualities
  3279. other than the first MOV instruction being a constant
  3280. are covered by DeepMOVOpt, so only check for that }
  3281. if (taicpu(p).oper[0]^.typ = top_const) and
  3282. (
  3283. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3284. not (cs_opt_size in current_settings.optimizerswitches) or
  3285. (taicpu(hp1).opsize = S_B)
  3286. ) and
  3287. (
  3288. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3289. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3290. ) then
  3291. begin
  3292. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3293. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3294. end;
  3295. end;
  3296. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3297. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3298. { mov reg1, mem1 or mov mem1, reg1
  3299. mov mem2, reg2 mov reg2, mem2}
  3300. begin
  3301. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3302. { mov reg1, mem1 or mov mem1, reg1
  3303. mov mem2, reg1 mov reg2, mem1}
  3304. begin
  3305. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3306. { Removes the second statement from
  3307. mov reg1, mem1/reg2
  3308. mov mem1/reg2, reg1 }
  3309. begin
  3310. if taicpu(p).oper[0]^.typ=top_reg then
  3311. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3312. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3313. RemoveInstruction(hp1);
  3314. Result:=true;
  3315. exit;
  3316. end
  3317. else
  3318. begin
  3319. TransferUsedRegs(TmpUsedRegs);
  3320. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3321. if (taicpu(p).oper[1]^.typ = top_ref) and
  3322. { mov reg1, mem1
  3323. mov mem2, reg1 }
  3324. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3325. GetNextInstruction(hp1, hp2) and
  3326. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3327. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3328. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3329. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3330. { change to
  3331. mov reg1, mem1 mov reg1, mem1
  3332. mov mem2, reg1 cmp reg1, mem2
  3333. cmp mem1, reg1
  3334. }
  3335. begin
  3336. RemoveInstruction(hp2);
  3337. taicpu(hp1).opcode := A_CMP;
  3338. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3339. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3340. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3341. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3342. end;
  3343. end;
  3344. end
  3345. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3346. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3347. begin
  3348. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3349. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3350. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3351. end
  3352. else
  3353. begin
  3354. TransferUsedRegs(TmpUsedRegs);
  3355. if GetNextInstruction(hp1, hp2) and
  3356. MatchOpType(taicpu(p),top_ref,top_reg) and
  3357. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3358. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3359. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3360. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3361. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3362. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3363. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3364. { mov mem1, %reg1
  3365. mov %reg1, mem2
  3366. mov mem2, reg2
  3367. to:
  3368. mov mem1, reg2
  3369. mov reg2, mem2}
  3370. begin
  3371. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3372. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3373. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3374. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3375. RemoveInstruction(hp2);
  3376. Result := True;
  3377. end
  3378. {$ifdef i386}
  3379. { this is enabled for i386 only, as the rules to create the reg sets below
  3380. are too complicated for x86-64, so this makes this code too error prone
  3381. on x86-64
  3382. }
  3383. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3384. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3385. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3386. { mov mem1, reg1 mov mem1, reg1
  3387. mov reg1, mem2 mov reg1, mem2
  3388. mov mem2, reg2 mov mem2, reg1
  3389. to: to:
  3390. mov mem1, reg1 mov mem1, reg1
  3391. mov mem1, reg2 mov reg1, mem2
  3392. mov reg1, mem2
  3393. or (if mem1 depends on reg1
  3394. and/or if mem2 depends on reg2)
  3395. to:
  3396. mov mem1, reg1
  3397. mov reg1, mem2
  3398. mov reg1, reg2
  3399. }
  3400. begin
  3401. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3402. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3403. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3404. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3405. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3406. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3407. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3408. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3409. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3410. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3411. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3412. end
  3413. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3414. begin
  3415. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3416. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3417. end
  3418. else
  3419. begin
  3420. RemoveInstruction(hp2);
  3421. end
  3422. {$endif i386}
  3423. ;
  3424. end;
  3425. end
  3426. { movl [mem1],reg1
  3427. movl [mem1],reg2
  3428. to
  3429. movl [mem1],reg1
  3430. movl reg1,reg2
  3431. }
  3432. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3433. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3434. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3435. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3436. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3437. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3438. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3439. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3440. begin
  3441. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3442. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3443. end;
  3444. { movl const1,[mem1]
  3445. movl [mem1],reg1
  3446. to
  3447. movl const1,reg1
  3448. movl reg1,[mem1]
  3449. }
  3450. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3451. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3452. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3453. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3454. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3455. begin
  3456. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3457. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3458. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3459. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3460. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3461. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3462. Result:=true;
  3463. exit;
  3464. end;
  3465. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3466. { Change:
  3467. movl %reg1,%reg2
  3468. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3469. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3470. To:
  3471. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3472. movl x(%reg1),%reg1
  3473. movl %reg1,%regX
  3474. }
  3475. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3476. begin
  3477. p_SourceReg := taicpu(p).oper[0]^.reg;
  3478. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3479. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3480. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3481. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3482. GetNextInstruction(hp1, hp2) and
  3483. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3484. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3485. begin
  3486. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3487. if RegInRef(p_TargetReg, SourceRef) and
  3488. { If %reg1 also appears in the second reference, then it will
  3489. not refer to the same memory block as the first reference }
  3490. not RegInRef(p_SourceReg, SourceRef) then
  3491. begin
  3492. { Check to see if the references match if %reg2 is changed to %reg1 }
  3493. if SourceRef.base = p_TargetReg then
  3494. SourceRef.base := p_SourceReg;
  3495. if SourceRef.index = p_TargetReg then
  3496. SourceRef.index := p_SourceReg;
  3497. { RefsEqual also checks to ensure both references are non-volatile }
  3498. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3499. begin
  3500. taicpu(hp2).loadreg(0, p_SourceReg);
  3501. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3502. Result := True;
  3503. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3504. begin
  3505. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3506. RemoveCurrentP(p, hp1);
  3507. Exit;
  3508. end
  3509. else
  3510. begin
  3511. { Check to see if %reg2 is no longer in use }
  3512. TransferUsedRegs(TmpUsedRegs);
  3513. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3514. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3515. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3516. begin
  3517. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3518. RemoveCurrentP(p, hp1);
  3519. Exit;
  3520. end;
  3521. end;
  3522. { If we reach this point, p and hp1 weren't actually modified,
  3523. so we can do a bit more work on this pass }
  3524. end;
  3525. end;
  3526. end;
  3527. end;
  3528. end;
  3529. { search further than the next instruction for a mov (as long as it's not a jump) }
  3530. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3531. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3532. (taicpu(p).oper[1]^.typ = top_reg) and
  3533. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3534. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3535. begin
  3536. { we work with hp2 here, so hp1 can be still used later on when
  3537. checking for GetNextInstruction_p }
  3538. hp3 := hp1;
  3539. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3540. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3541. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3542. TransferUsedRegs(TmpUsedRegs);
  3543. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3544. if NotFirstIteration then
  3545. JumpTracking := TLinkedList.Create
  3546. else
  3547. JumpTracking := nil;
  3548. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3549. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3550. (hp2.typ=ait_instruction) do
  3551. begin
  3552. case taicpu(hp2).opcode of
  3553. A_POP:
  3554. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3555. begin
  3556. if not CrossJump and
  3557. not RegUsedBetween(p_TargetReg, p, hp2) then
  3558. begin
  3559. { We can remove the original MOV since the register
  3560. wasn't used between it and its popping from the stack }
  3561. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3562. RemoveCurrentp(p, hp1);
  3563. Result := True;
  3564. JumpTracking.Free;
  3565. Exit;
  3566. end;
  3567. { Can't go any further }
  3568. Break;
  3569. end;
  3570. A_MOV:
  3571. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3572. ((taicpu(p).oper[0]^.typ=top_const) or
  3573. ((taicpu(p).oper[0]^.typ=top_reg) and
  3574. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3575. )
  3576. ) then
  3577. begin
  3578. { we have
  3579. mov x, %treg
  3580. mov %treg, y
  3581. }
  3582. { We don't need to call UpdateUsedRegs for every instruction between
  3583. p and hp2 because the register we're concerned about will not
  3584. become deallocated (otherwise GetNextInstructionUsingReg would
  3585. have stopped at an earlier instruction). [Kit] }
  3586. TempRegUsed :=
  3587. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3588. RegReadByInstruction(p_TargetReg, hp3) or
  3589. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3590. case taicpu(p).oper[0]^.typ Of
  3591. top_reg:
  3592. begin
  3593. { change
  3594. mov %reg, %treg
  3595. mov %treg, y
  3596. to
  3597. mov %reg, y
  3598. }
  3599. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3600. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3601. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3602. begin
  3603. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3604. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3605. if TempRegUsed then
  3606. begin
  3607. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3608. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3609. { Set the start of the next GetNextInstructionUsingRegCond search
  3610. to start at the entry right before hp2 (which is about to be removed) }
  3611. hp3 := tai(hp2.Previous);
  3612. RemoveInstruction(hp2);
  3613. { See if there's more we can optimise }
  3614. Continue;
  3615. end
  3616. else
  3617. begin
  3618. RemoveInstruction(hp2);
  3619. { We can remove the original MOV too }
  3620. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3621. RemoveCurrentP(p, hp1);
  3622. Result:=true;
  3623. JumpTracking.Free;
  3624. Exit;
  3625. end;
  3626. end
  3627. else
  3628. begin
  3629. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3630. taicpu(hp2).loadReg(0, p_SourceReg);
  3631. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3632. { Check to see if the register also appears in the reference }
  3633. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3634. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3635. { Don't remove the first instruction if the temporary register is in use }
  3636. if not TempRegUsed and
  3637. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3638. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3639. begin
  3640. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3641. RemoveCurrentP(p, hp1);
  3642. Result:=true;
  3643. JumpTracking.Free;
  3644. Exit;
  3645. end;
  3646. { No need to set Result to True here. If there's another instruction later
  3647. on that can be optimised, it will be detected when the main Pass 1 loop
  3648. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3649. end;
  3650. end;
  3651. top_const:
  3652. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3653. begin
  3654. { change
  3655. mov const, %treg
  3656. mov %treg, y
  3657. to
  3658. mov const, y
  3659. }
  3660. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3661. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3662. begin
  3663. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3664. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3665. if TempRegUsed then
  3666. begin
  3667. { Don't remove the first instruction if the temporary register is in use }
  3668. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3669. { No need to set Result to True. If there's another instruction later on
  3670. that can be optimised, it will be detected when the main Pass 1 loop
  3671. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3672. end
  3673. else
  3674. begin
  3675. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3676. RemoveCurrentP(p, hp1);
  3677. Result:=true;
  3678. Exit;
  3679. end;
  3680. end;
  3681. end;
  3682. else
  3683. Internalerror(2019103001);
  3684. end;
  3685. end
  3686. else
  3687. if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3688. begin
  3689. if not CrossJump and
  3690. not RegUsedBetween(p_TargetReg, p, hp2) and
  3691. not RegReadByInstruction(p_TargetReg, hp2) then
  3692. begin
  3693. { Register is not used before it is overwritten }
  3694. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3695. RemoveCurrentp(p, hp1);
  3696. Result := True;
  3697. Exit;
  3698. end;
  3699. if (taicpu(p).oper[0]^.typ = top_const) and
  3700. (taicpu(hp2).oper[0]^.typ = top_const) then
  3701. begin
  3702. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3703. begin
  3704. { Same value - register hasn't changed }
  3705. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3706. RemoveInstruction(hp2);
  3707. Result := True;
  3708. { See if there's more we can optimise }
  3709. Continue;
  3710. end;
  3711. end;
  3712. end;
  3713. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3714. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3715. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  3716. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  3717. begin
  3718. {
  3719. Change from:
  3720. mov ###, %reg
  3721. ...
  3722. movs/z %reg,%reg (Same register, just different sizes)
  3723. To:
  3724. movs/z ###, %reg (Longer version)
  3725. ...
  3726. (remove)
  3727. }
  3728. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3729. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3730. { Keep the first instruction as mov if ### is a constant }
  3731. if taicpu(p).oper[0]^.typ = top_const then
  3732. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3733. else
  3734. begin
  3735. taicpu(p).opcode := taicpu(hp2).opcode;
  3736. taicpu(p).opsize := taicpu(hp2).opsize;
  3737. end;
  3738. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3739. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3740. RemoveInstruction(hp2);
  3741. Result := True;
  3742. JumpTracking.Free;
  3743. Exit;
  3744. end;
  3745. else
  3746. { Move down to the MatchOpType if-block below };
  3747. end;
  3748. { Also catches MOV/S/Z instructions that aren't modified }
  3749. if taicpu(p).oper[0]^.typ = top_reg then
  3750. begin
  3751. p_SourceReg := taicpu(p).oper[0]^.reg;
  3752. if
  3753. not RegModifiedByInstruction(p_SourceReg, hp3) and
  3754. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  3755. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3756. begin
  3757. Result := True;
  3758. { Just in case something didn't get modified (e.g. an
  3759. implicit register). Also, if it does read from this
  3760. register, then there's no longer an advantage to
  3761. changing the register on subsequent instructions.}
  3762. if not RegReadByInstruction(p_TargetReg, hp2) then
  3763. begin
  3764. { If a conditional jump was crossed, do not delete
  3765. the original MOV no matter what }
  3766. if not CrossJump and
  3767. { RegEndOfLife returns True if the register is
  3768. deallocated before the next instruction or has
  3769. been loaded with a new value }
  3770. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  3771. begin
  3772. { We can remove the original MOV }
  3773. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3774. RemoveCurrentp(p, hp1);
  3775. JumpTracking.Free;
  3776. Result := True;
  3777. Exit;
  3778. end;
  3779. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  3780. begin
  3781. { See if there's more we can optimise }
  3782. hp3 := hp2;
  3783. Continue;
  3784. end;
  3785. end;
  3786. end;
  3787. end;
  3788. { Break out of the while loop under normal circumstances }
  3789. Break;
  3790. end;
  3791. JumpTracking.Free;
  3792. end;
  3793. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3794. (taicpu(p).oper[1]^.typ = top_reg) and
  3795. (taicpu(p).opsize = S_L) and
  3796. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3797. (hp2.typ = ait_instruction) and
  3798. (taicpu(hp2).opcode = A_AND) and
  3799. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3800. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3801. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3802. ) then
  3803. begin
  3804. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3805. begin
  3806. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3807. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3808. begin
  3809. { Optimize out:
  3810. mov x, %reg
  3811. and ffffffffh, %reg
  3812. }
  3813. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3814. RemoveInstruction(hp2);
  3815. Result:=true;
  3816. exit;
  3817. end;
  3818. end;
  3819. end;
  3820. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3821. x >= RetOffset) as it doesn't do anything (it writes either to a
  3822. parameter or to the temporary storage room for the function
  3823. result)
  3824. }
  3825. if IsExitCode(hp1) and
  3826. (taicpu(p).oper[1]^.typ = top_ref) and
  3827. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3828. (
  3829. (
  3830. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3831. not (
  3832. assigned(current_procinfo.procdef.funcretsym) and
  3833. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3834. )
  3835. ) or
  3836. { Also discard writes to the stack that are below the base pointer,
  3837. as this is temporary storage rather than a function result on the
  3838. stack, say. }
  3839. (
  3840. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3841. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3842. )
  3843. ) then
  3844. begin
  3845. RemoveCurrentp(p, hp1);
  3846. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3847. RemoveLastDeallocForFuncRes(p);
  3848. Result:=true;
  3849. exit;
  3850. end;
  3851. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3852. begin
  3853. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3854. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3855. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3856. begin
  3857. { change
  3858. mov reg1, mem1
  3859. test/cmp x, mem1
  3860. to
  3861. mov reg1, mem1
  3862. test/cmp x, reg1
  3863. }
  3864. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3865. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3866. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3867. Result := True;
  3868. Exit;
  3869. end;
  3870. if DoMovCmpMemOpt(p, hp1, True) then
  3871. begin
  3872. Result := True;
  3873. Exit;
  3874. end;
  3875. end;
  3876. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3877. { If the flags register is in use, don't change the instruction to an
  3878. ADD otherwise this will scramble the flags. [Kit] }
  3879. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3880. begin
  3881. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3882. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3883. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3884. ) or
  3885. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3886. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3887. )
  3888. ) then
  3889. { mov reg1,ref
  3890. lea reg2,[reg1,reg2]
  3891. to
  3892. add reg2,ref}
  3893. begin
  3894. TransferUsedRegs(TmpUsedRegs);
  3895. { reg1 may not be used afterwards }
  3896. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3897. begin
  3898. Taicpu(hp1).opcode:=A_ADD;
  3899. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3900. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3901. RemoveCurrentp(p, hp1);
  3902. result:=true;
  3903. exit;
  3904. end;
  3905. end;
  3906. { If the LEA instruction can be converted into an arithmetic instruction,
  3907. it may be possible to then fold it in the next optimisation, otherwise
  3908. there's nothing more that can be optimised here. }
  3909. if not ConvertLEA(taicpu(hp1)) then
  3910. Exit;
  3911. end;
  3912. if (taicpu(p).oper[1]^.typ = top_reg) and
  3913. (hp1.typ = ait_instruction) and
  3914. GetNextInstruction(hp1, hp2) and
  3915. MatchInstruction(hp2,A_MOV,[]) and
  3916. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3917. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3918. (
  3919. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3920. {$ifdef x86_64}
  3921. or
  3922. (
  3923. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3924. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3925. )
  3926. {$endif x86_64}
  3927. ) then
  3928. begin
  3929. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3930. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3931. { change movsX/movzX reg/ref, reg2
  3932. add/sub/or/... reg3/$const, reg2
  3933. mov reg2 reg/ref
  3934. dealloc reg2
  3935. to
  3936. add/sub/or/... reg3/$const, reg/ref }
  3937. begin
  3938. TransferUsedRegs(TmpUsedRegs);
  3939. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3940. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3941. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3942. begin
  3943. { by example:
  3944. movswl %si,%eax movswl %si,%eax p
  3945. decl %eax addl %edx,%eax hp1
  3946. movw %ax,%si movw %ax,%si hp2
  3947. ->
  3948. movswl %si,%eax movswl %si,%eax p
  3949. decw %eax addw %edx,%eax hp1
  3950. movw %ax,%si movw %ax,%si hp2
  3951. }
  3952. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3953. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3954. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3955. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3956. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3957. {
  3958. ->
  3959. movswl %si,%eax movswl %si,%eax p
  3960. decw %si addw %dx,%si hp1
  3961. movw %ax,%si movw %ax,%si hp2
  3962. }
  3963. case taicpu(hp1).ops of
  3964. 1:
  3965. begin
  3966. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3967. if taicpu(hp1).oper[0]^.typ=top_reg then
  3968. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3969. end;
  3970. 2:
  3971. begin
  3972. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3973. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3974. (taicpu(hp1).opcode<>A_SHL) and
  3975. (taicpu(hp1).opcode<>A_SHR) and
  3976. (taicpu(hp1).opcode<>A_SAR) then
  3977. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3978. end;
  3979. else
  3980. internalerror(2008042701);
  3981. end;
  3982. {
  3983. ->
  3984. decw %si addw %dx,%si p
  3985. }
  3986. RemoveInstruction(hp2);
  3987. RemoveCurrentP(p, hp1);
  3988. Result:=True;
  3989. Exit;
  3990. end;
  3991. end;
  3992. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3993. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3994. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3995. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3996. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3997. )
  3998. {$ifdef i386}
  3999. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4000. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4001. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4002. {$endif i386}
  4003. then
  4004. { change movsX/movzX reg/ref, reg2
  4005. add/sub/or/... regX/$const, reg2
  4006. mov reg2, reg3
  4007. dealloc reg2
  4008. to
  4009. movsX/movzX reg/ref, reg3
  4010. add/sub/or/... reg3/$const, reg3
  4011. }
  4012. begin
  4013. TransferUsedRegs(TmpUsedRegs);
  4014. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4015. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4016. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4017. begin
  4018. { by example:
  4019. movswl %si,%eax movswl %si,%eax p
  4020. decl %eax addl %edx,%eax hp1
  4021. movw %ax,%si movw %ax,%si hp2
  4022. ->
  4023. movswl %si,%eax movswl %si,%eax p
  4024. decw %eax addw %edx,%eax hp1
  4025. movw %ax,%si movw %ax,%si hp2
  4026. }
  4027. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4028. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4029. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4030. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4031. { limit size of constants as well to avoid assembler errors, but
  4032. check opsize to avoid overflow when left shifting the 1 }
  4033. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4034. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4035. {$ifdef x86_64}
  4036. { Be careful of, for example:
  4037. movl %reg1,%reg2
  4038. addl %reg3,%reg2
  4039. movq %reg2,%reg4
  4040. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4041. }
  4042. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4043. begin
  4044. taicpu(hp2).changeopsize(S_L);
  4045. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4046. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4047. end;
  4048. {$endif x86_64}
  4049. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4050. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4051. if taicpu(p).oper[0]^.typ=top_reg then
  4052. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4053. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4054. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4055. {
  4056. ->
  4057. movswl %si,%eax movswl %si,%eax p
  4058. decw %si addw %dx,%si hp1
  4059. movw %ax,%si movw %ax,%si hp2
  4060. }
  4061. case taicpu(hp1).ops of
  4062. 1:
  4063. begin
  4064. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4065. if taicpu(hp1).oper[0]^.typ=top_reg then
  4066. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4067. end;
  4068. 2:
  4069. begin
  4070. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4071. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4072. (taicpu(hp1).opcode<>A_SHL) and
  4073. (taicpu(hp1).opcode<>A_SHR) and
  4074. (taicpu(hp1).opcode<>A_SAR) then
  4075. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4076. end;
  4077. else
  4078. internalerror(2018111801);
  4079. end;
  4080. {
  4081. ->
  4082. decw %si addw %dx,%si p
  4083. }
  4084. RemoveInstruction(hp2);
  4085. end;
  4086. end;
  4087. end;
  4088. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4089. GetNextInstruction(hp1, hp2) and
  4090. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4091. MatchOperand(Taicpu(p).oper[0]^,0) and
  4092. (Taicpu(p).oper[1]^.typ = top_reg) and
  4093. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4094. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4095. { mov reg1,0
  4096. bts reg1,operand1 --> mov reg1,operand2
  4097. or reg1,operand2 bts reg1,operand1}
  4098. begin
  4099. Taicpu(hp2).opcode:=A_MOV;
  4100. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4101. asml.remove(hp1);
  4102. insertllitem(hp2,hp2.next,hp1);
  4103. RemoveCurrentp(p, hp1);
  4104. Result:=true;
  4105. exit;
  4106. end;
  4107. {
  4108. mov ref,reg0
  4109. <op> reg0,reg1
  4110. dealloc reg0
  4111. to
  4112. <op> ref,reg1
  4113. }
  4114. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4115. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4116. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4117. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4118. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4119. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4120. begin
  4121. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4122. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4123. RemoveCurrentp(p, hp1);
  4124. Result:=true;
  4125. exit;
  4126. end;
  4127. {$ifdef x86_64}
  4128. { Convert:
  4129. movq x(ref),%reg64
  4130. shrq y,%reg64
  4131. To:
  4132. movl x+4(ref),%reg32
  4133. shrl y-32,%reg32 (Remove if y = 32)
  4134. }
  4135. if (taicpu(p).opsize = S_Q) and
  4136. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4137. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  4138. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  4139. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4140. (taicpu(hp1).oper[0]^.val >= 32) and
  4141. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4142. begin
  4143. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4144. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4145. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4146. { Convert to 32-bit }
  4147. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4148. taicpu(p).opsize := S_L;
  4149. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4150. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4151. if (taicpu(hp1).oper[0]^.val = 32) then
  4152. begin
  4153. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4154. RemoveInstruction(hp1);
  4155. end
  4156. else
  4157. begin
  4158. { This will potentially open up more arithmetic operations since
  4159. the peephole optimizer now has a big hint that only the lower
  4160. 32 bits are currently in use (and opcodes are smaller in size) }
  4161. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4162. taicpu(hp1).opsize := S_L;
  4163. Dec(taicpu(hp1).oper[0]^.val, 32);
  4164. DebugMsg(SPeepholeOptimization + PreMessage +
  4165. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4166. end;
  4167. Result := True;
  4168. Exit;
  4169. end;
  4170. {$endif x86_64}
  4171. { Backward optimisation. If we have:
  4172. func. %reg1,%reg2
  4173. mov %reg2,%reg3
  4174. (dealloc %reg2)
  4175. Change to:
  4176. func. %reg1,%reg3 (see comment below for what a valid func. is)
  4177. }
  4178. if MatchOpType(taicpu(p), top_reg, top_reg) then
  4179. begin
  4180. p_SourceReg := taicpu(p).oper[0]^.reg;
  4181. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4182. TransferUsedRegs(TmpUsedRegs);
  4183. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  4184. GetLastInstruction(p, hp2) and
  4185. (hp2.typ = ait_instruction) and
  4186. { Have to make sure it's an instruction that only reads from
  4187. operand 1 and only writes (not reads or modifies) from operand 2;
  4188. in essence, a one-operand pure function such as BSR or POPCNT }
  4189. (taicpu(hp2).ops = 2) and
  4190. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  4191. (taicpu(hp2).oper[1]^.typ = top_reg) and
  4192. (taicpu(hp2).oper[1]^.reg = p_SourceReg) then
  4193. begin
  4194. case taicpu(hp2).opcode of
  4195. A_FSTSW, A_FNSTSW,
  4196. A_IN, A_INS, A_OUT, A_OUTS,
  4197. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  4198. { These routines have explicit operands, but they are restricted in
  4199. what they can be (e.g. IN and OUT can only read from AL, AX or
  4200. EAX. }
  4201. ;
  4202. else
  4203. begin
  4204. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  4205. taicpu(hp2).oper[1]^.reg := p_TargetReg;
  4206. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  4207. RemoveCurrentp(p, hp1);
  4208. Result := True;
  4209. Exit;
  4210. end;
  4211. end;
  4212. end;
  4213. end;
  4214. end;
  4215. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4216. var
  4217. hp1 : tai;
  4218. begin
  4219. Result:=false;
  4220. if taicpu(p).ops <> 2 then
  4221. exit;
  4222. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4223. GetNextInstruction(p,hp1) then
  4224. begin
  4225. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4226. (taicpu(hp1).ops = 2) then
  4227. begin
  4228. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4229. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4230. { movXX reg1, mem1 or movXX mem1, reg1
  4231. movXX mem2, reg2 movXX reg2, mem2}
  4232. begin
  4233. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4234. { movXX reg1, mem1 or movXX mem1, reg1
  4235. movXX mem2, reg1 movXX reg2, mem1}
  4236. begin
  4237. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4238. begin
  4239. { Removes the second statement from
  4240. movXX reg1, mem1/reg2
  4241. movXX mem1/reg2, reg1
  4242. }
  4243. if taicpu(p).oper[0]^.typ=top_reg then
  4244. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4245. { Removes the second statement from
  4246. movXX mem1/reg1, reg2
  4247. movXX reg2, mem1/reg1
  4248. }
  4249. if (taicpu(p).oper[1]^.typ=top_reg) and
  4250. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4251. begin
  4252. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4253. RemoveInstruction(hp1);
  4254. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4255. Result:=true;
  4256. exit;
  4257. end
  4258. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4259. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4260. begin
  4261. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4262. RemoveInstruction(hp1);
  4263. Result:=true;
  4264. exit;
  4265. end;
  4266. end
  4267. end;
  4268. end;
  4269. end;
  4270. end;
  4271. end;
  4272. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4273. var
  4274. hp1 : tai;
  4275. begin
  4276. result:=false;
  4277. { replace
  4278. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4279. MovX %mreg2,%mreg1
  4280. dealloc %mreg2
  4281. by
  4282. <Op>X %mreg2,%mreg1
  4283. ?
  4284. }
  4285. if GetNextInstruction(p,hp1) and
  4286. { we mix single and double opperations here because we assume that the compiler
  4287. generates vmovapd only after double operations and vmovaps only after single operations }
  4288. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4289. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4290. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4291. (taicpu(p).oper[0]^.typ=top_reg) then
  4292. begin
  4293. TransferUsedRegs(TmpUsedRegs);
  4294. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4295. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4296. begin
  4297. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4298. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4299. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4300. RemoveInstruction(hp1);
  4301. result:=true;
  4302. end;
  4303. end;
  4304. end;
  4305. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4306. var
  4307. hp1, p_label, p_dist, hp1_dist: tai;
  4308. JumpLabel, JumpLabel_dist: TAsmLabel;
  4309. FirstValue, SecondValue: TCGInt;
  4310. begin
  4311. Result := False;
  4312. if (taicpu(p).oper[0]^.typ = top_const) and
  4313. (taicpu(p).oper[0]^.val <> -1) then
  4314. begin
  4315. { Convert unsigned maximum constants to -1 to aid optimisation }
  4316. case taicpu(p).opsize of
  4317. S_B:
  4318. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4319. begin
  4320. taicpu(p).oper[0]^.val := -1;
  4321. Result := True;
  4322. Exit;
  4323. end;
  4324. S_W:
  4325. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4326. begin
  4327. taicpu(p).oper[0]^.val := -1;
  4328. Result := True;
  4329. Exit;
  4330. end;
  4331. S_L:
  4332. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4333. begin
  4334. taicpu(p).oper[0]^.val := -1;
  4335. Result := True;
  4336. Exit;
  4337. end;
  4338. {$ifdef x86_64}
  4339. S_Q:
  4340. { Storing anything greater than $7FFFFFFF is not possible so do
  4341. nothing };
  4342. {$endif x86_64}
  4343. else
  4344. InternalError(2021121001);
  4345. end;
  4346. end;
  4347. if GetNextInstruction(p, hp1) and
  4348. TrySwapMovCmp(p, hp1) then
  4349. begin
  4350. Result := True;
  4351. Exit;
  4352. end;
  4353. { Search for:
  4354. test $x,(reg/ref)
  4355. jne @lbl1
  4356. test $y,(reg/ref) (same register or reference)
  4357. jne @lbl1
  4358. Change to:
  4359. test $(x or y),(reg/ref)
  4360. jne @lbl1
  4361. (Note, this doesn't work with je instead of jne)
  4362. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4363. Also search for:
  4364. test $x,(reg/ref)
  4365. je @lbl1
  4366. test $y,(reg/ref)
  4367. je/jne @lbl2
  4368. If (x or y) = x, then the second jump is deterministic
  4369. }
  4370. if (
  4371. (
  4372. (taicpu(p).oper[0]^.typ = top_const) or
  4373. (
  4374. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4375. (taicpu(p).oper[0]^.typ = top_reg) and
  4376. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4377. )
  4378. ) and
  4379. MatchInstruction(hp1, A_JCC, [])
  4380. ) then
  4381. begin
  4382. if (taicpu(p).oper[0]^.typ = top_reg) and
  4383. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4384. FirstValue := -1
  4385. else
  4386. FirstValue := taicpu(p).oper[0]^.val;
  4387. { If we have several test/jne's in a row, it might be the case that
  4388. the second label doesn't go to the same location, but the one
  4389. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4390. so accommodate for this with a while loop.
  4391. }
  4392. hp1_dist := hp1;
  4393. if GetNextInstruction(hp1, p_dist) and
  4394. (p_dist.typ = ait_instruction) and
  4395. (
  4396. (
  4397. (taicpu(p_dist).opcode = A_TEST) and
  4398. (
  4399. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4400. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4401. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4402. )
  4403. ) or
  4404. (
  4405. { cmp 0,%reg = test %reg,%reg }
  4406. (taicpu(p_dist).opcode = A_CMP) and
  4407. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4408. )
  4409. ) and
  4410. { Make sure the destination operands are actually the same }
  4411. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4412. GetNextInstruction(p_dist, hp1_dist) and
  4413. MatchInstruction(hp1_dist, A_JCC, []) then
  4414. begin
  4415. if
  4416. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4417. (
  4418. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4419. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4420. ) then
  4421. SecondValue := -1
  4422. else
  4423. SecondValue := taicpu(p_dist).oper[0]^.val;
  4424. { If both of the TEST constants are identical, delete the second
  4425. TEST that is unnecessary. }
  4426. if (FirstValue = SecondValue) then
  4427. begin
  4428. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4429. RemoveInstruction(p_dist);
  4430. { Don't let the flags register become deallocated and reallocated between the jumps }
  4431. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4432. Result := True;
  4433. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4434. begin
  4435. { Since the second jump's condition is a subset of the first, we
  4436. know it will never branch because the first jump dominates it.
  4437. Get it out of the way now rather than wait for the jump
  4438. optimisations for a speed boost. }
  4439. if IsJumpToLabel(taicpu(hp1_dist)) then
  4440. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4441. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4442. RemoveInstruction(hp1_dist);
  4443. end
  4444. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4445. begin
  4446. { If the inverse of the first condition is a subset of the second,
  4447. the second one will definitely branch if the first one doesn't }
  4448. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4449. MakeUnconditional(taicpu(hp1_dist));
  4450. RemoveDeadCodeAfterJump(hp1_dist);
  4451. end;
  4452. Exit;
  4453. end;
  4454. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4455. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4456. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4457. then the second jump will never branch, so it can also be
  4458. removed regardless of where it goes }
  4459. (
  4460. (FirstValue = -1) or
  4461. (SecondValue = -1) or
  4462. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4463. ) then
  4464. begin
  4465. { Same jump location... can be a register since nothing's changed }
  4466. { If any of the entries are equivalent to test %reg,%reg, then the
  4467. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4468. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4469. if IsJumpToLabel(taicpu(hp1_dist)) then
  4470. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4471. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4472. RemoveInstruction(hp1_dist);
  4473. { Only remove the second test if no jumps or other conditional instructions follow }
  4474. TransferUsedRegs(TmpUsedRegs);
  4475. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4476. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4477. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4478. RemoveInstruction(p_dist);
  4479. Result := True;
  4480. Exit;
  4481. end;
  4482. end;
  4483. end;
  4484. { Search for:
  4485. test %reg,%reg
  4486. j(c1) @lbl1
  4487. ...
  4488. @lbl:
  4489. test %reg,%reg (same register)
  4490. j(c2) @lbl2
  4491. If c2 is a subset of c1, change to:
  4492. test %reg,%reg
  4493. j(c1) @lbl2
  4494. (@lbl1 may become a dead label as a result)
  4495. }
  4496. if (taicpu(p).oper[1]^.typ = top_reg) and
  4497. (taicpu(p).oper[0]^.typ = top_reg) and
  4498. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4499. MatchInstruction(hp1, A_JCC, []) and
  4500. IsJumpToLabel(taicpu(hp1)) then
  4501. begin
  4502. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4503. p_label := nil;
  4504. if Assigned(JumpLabel) then
  4505. p_label := getlabelwithsym(JumpLabel);
  4506. if Assigned(p_label) and
  4507. GetNextInstruction(p_label, p_dist) and
  4508. MatchInstruction(p_dist, A_TEST, []) and
  4509. { It's fine if the second test uses smaller sub-registers }
  4510. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4511. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4512. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4513. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4514. GetNextInstruction(p_dist, hp1_dist) and
  4515. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4516. begin
  4517. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4518. if JumpLabel = JumpLabel_dist then
  4519. { This is an infinite loop }
  4520. Exit;
  4521. { Best optimisation when the first condition is a subset (or equal) of the second }
  4522. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4523. begin
  4524. { Any registers used here will already be allocated }
  4525. if Assigned(JumpLabel) then
  4526. JumpLabel.DecRefs;
  4527. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4528. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  4529. Result := True;
  4530. Exit;
  4531. end;
  4532. end;
  4533. end;
  4534. end;
  4535. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4536. var
  4537. hp1, hp2: tai;
  4538. ActiveReg: TRegister;
  4539. OldOffset: asizeint;
  4540. ThisConst: TCGInt;
  4541. function RegDeallocated: Boolean;
  4542. begin
  4543. TransferUsedRegs(TmpUsedRegs);
  4544. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4545. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4546. end;
  4547. begin
  4548. result:=false;
  4549. hp1 := nil;
  4550. { replace
  4551. addX const,%reg1
  4552. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4553. dealloc %reg1
  4554. by
  4555. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4556. }
  4557. if MatchOpType(taicpu(p),top_const,top_reg) then
  4558. begin
  4559. ActiveReg := taicpu(p).oper[1]^.reg;
  4560. { Ensures the entire register was updated }
  4561. if (taicpu(p).opsize >= S_L) and
  4562. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4563. MatchInstruction(hp1,A_LEA,[]) and
  4564. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4565. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4566. (
  4567. { Cover the case where the register in the reference is also the destination register }
  4568. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4569. (
  4570. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4571. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4572. RegDeallocated
  4573. )
  4574. ) then
  4575. begin
  4576. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4577. {$push}
  4578. {$R-}{$Q-}
  4579. { Explicitly disable overflow checking for these offset calculation
  4580. as those do not matter for the final result }
  4581. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4582. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4583. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4584. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4585. {$pop}
  4586. {$ifdef x86_64}
  4587. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4588. begin
  4589. { Overflow; abort }
  4590. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4591. end
  4592. else
  4593. {$endif x86_64}
  4594. begin
  4595. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4596. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4597. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4598. RemoveCurrentP(p, hp1)
  4599. else
  4600. RemoveCurrentP(p);
  4601. result:=true;
  4602. Exit;
  4603. end;
  4604. end;
  4605. if (
  4606. { Save calling GetNextInstructionUsingReg again }
  4607. Assigned(hp1) or
  4608. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4609. ) and
  4610. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4611. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4612. begin
  4613. if taicpu(hp1).oper[0]^.typ = top_const then
  4614. begin
  4615. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4616. if taicpu(hp1).opcode = A_ADD then
  4617. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4618. else
  4619. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4620. Result := True;
  4621. { Handle any overflows }
  4622. case taicpu(p).opsize of
  4623. S_B:
  4624. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4625. S_W:
  4626. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4627. S_L:
  4628. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4629. {$ifdef x86_64}
  4630. S_Q:
  4631. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4632. { Overflow; abort }
  4633. Result := False
  4634. else
  4635. taicpu(p).oper[0]^.val := ThisConst;
  4636. {$endif x86_64}
  4637. else
  4638. InternalError(2021102610);
  4639. end;
  4640. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4641. if Result then
  4642. begin
  4643. if (taicpu(p).oper[0]^.val < 0) and
  4644. (
  4645. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4646. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4647. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4648. ) then
  4649. begin
  4650. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4651. taicpu(p).opcode := A_SUB;
  4652. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4653. end
  4654. else
  4655. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4656. RemoveInstruction(hp1);
  4657. end;
  4658. end
  4659. else
  4660. begin
  4661. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4662. TransferUsedRegs(TmpUsedRegs);
  4663. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4664. hp2 := p;
  4665. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4666. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4667. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4668. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4669. begin
  4670. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4671. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4672. Asml.Remove(p);
  4673. Asml.InsertAfter(p, hp1);
  4674. p := hp1;
  4675. Result := True;
  4676. end;
  4677. end;
  4678. end;
  4679. end;
  4680. end;
  4681. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4682. var
  4683. hp1: tai;
  4684. ref: Integer;
  4685. saveref: treference;
  4686. Multiple: TCGInt;
  4687. Adjacent: Boolean;
  4688. begin
  4689. Result:=false;
  4690. { play save and throw an error if LEA uses a seg register prefix,
  4691. this is most likely an error somewhere else }
  4692. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  4693. internalerror(2022022001);
  4694. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4695. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4696. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4697. (
  4698. { do not mess with leas accessing the stack pointer
  4699. unless it's a null operation }
  4700. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4701. (
  4702. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4703. (taicpu(p).oper[0]^.ref^.offset = 0)
  4704. )
  4705. ) and
  4706. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4707. begin
  4708. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4709. begin
  4710. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4711. begin
  4712. taicpu(p).opcode := A_MOV;
  4713. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  4714. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  4715. end
  4716. else
  4717. begin
  4718. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4719. RemoveCurrentP(p);
  4720. end;
  4721. Result:=true;
  4722. exit;
  4723. end
  4724. else if (
  4725. { continue to use lea to adjust the stack pointer,
  4726. it is the recommended way, but only if not optimizing for size }
  4727. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4728. (cs_opt_size in current_settings.optimizerswitches)
  4729. ) and
  4730. { If the flags register is in use, don't change the instruction
  4731. to an ADD otherwise this will scramble the flags. [Kit] }
  4732. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4733. ConvertLEA(taicpu(p)) then
  4734. begin
  4735. Result:=true;
  4736. exit;
  4737. end;
  4738. end;
  4739. { Don't optimise if the stack or frame pointer is the destination register }
  4740. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  4741. Exit;
  4742. if GetNextInstruction(p,hp1) and
  4743. (hp1.typ=ait_instruction) then
  4744. begin
  4745. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4746. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4747. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  4748. begin
  4749. TransferUsedRegs(TmpUsedRegs);
  4750. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4751. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4752. begin
  4753. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4754. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4755. RemoveInstruction(hp1);
  4756. result:=true;
  4757. exit;
  4758. end;
  4759. end;
  4760. { changes
  4761. lea <ref1>, reg1
  4762. <op> ...,<ref. with reg1>,...
  4763. to
  4764. <op> ...,<ref1>,... }
  4765. { find a reference which uses reg1 }
  4766. 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
  4767. ref:=0
  4768. 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
  4769. ref:=1
  4770. else
  4771. ref:=-1;
  4772. if (ref<>-1) and
  4773. { reg1 must be either the base or the index }
  4774. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4775. begin
  4776. { reg1 can be removed from the reference }
  4777. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4778. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4779. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4780. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4781. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4782. else
  4783. Internalerror(2019111201);
  4784. { check if the can insert all data of the lea into the second instruction }
  4785. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4786. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4787. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4788. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4789. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4790. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4791. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4792. {$ifdef x86_64}
  4793. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4794. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4795. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4796. )
  4797. {$endif x86_64}
  4798. then
  4799. begin
  4800. { reg1 might not used by the second instruction after it is remove from the reference }
  4801. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4802. begin
  4803. TransferUsedRegs(TmpUsedRegs);
  4804. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4805. { reg1 is not updated so it might not be used afterwards }
  4806. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4807. begin
  4808. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4809. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4810. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4811. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4812. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4813. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4814. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4815. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4816. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4817. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4818. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4819. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4820. RemoveCurrentP(p, hp1);
  4821. result:=true;
  4822. exit;
  4823. end
  4824. end;
  4825. end;
  4826. { recover }
  4827. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4828. end;
  4829. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  4830. if Adjacent or
  4831. { Check further ahead (up to 2 instructions ahead for -O2) }
  4832. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  4833. begin
  4834. { Check common LEA/LEA conditions }
  4835. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4836. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4837. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4838. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4839. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4840. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4841. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4842. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4843. (
  4844. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  4845. calling it (since it calls GetNextInstruction) }
  4846. Adjacent or
  4847. (
  4848. (
  4849. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4850. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4851. ) and (
  4852. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4853. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4854. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4855. )
  4856. )
  4857. ) then
  4858. begin
  4859. { changes
  4860. lea (regX,scale), reg1
  4861. lea offset(reg1,reg1), reg1
  4862. to
  4863. lea offset(regX,scale*2), reg1
  4864. and
  4865. lea (regX,scale1), reg1
  4866. lea offset(reg1,scale2), reg1
  4867. to
  4868. lea offset(regX,scale1*scale2), reg1
  4869. ... so long as the final scale does not exceed 8
  4870. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4871. }
  4872. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  4873. (taicpu(p).oper[0]^.ref^.offset = 0) and
  4874. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4875. (
  4876. (
  4877. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4878. ) or (
  4879. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4880. (
  4881. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4882. (
  4883. { RegUsedBetween always returns False if p and hp1 are adjacent }
  4884. Adjacent or
  4885. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4886. )
  4887. )
  4888. )
  4889. ) and (
  4890. (
  4891. { lea (reg1,scale2), reg1 variant }
  4892. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4893. (
  4894. (
  4895. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4896. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4897. ) or (
  4898. { lea (regX,regX), reg1 variant }
  4899. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4900. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4901. )
  4902. )
  4903. ) or (
  4904. { lea (reg1,reg1), reg1 variant }
  4905. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4906. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4907. )
  4908. ) then
  4909. begin
  4910. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4911. { Make everything homogeneous to make calculations easier }
  4912. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4913. begin
  4914. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4915. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4916. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4917. else
  4918. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4919. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4920. end;
  4921. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4922. begin
  4923. { Just to prevent miscalculations }
  4924. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4925. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4926. else
  4927. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4928. end
  4929. else
  4930. begin
  4931. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4932. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4933. end;
  4934. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4935. RemoveCurrentP(p);
  4936. result:=true;
  4937. exit;
  4938. end
  4939. { changes
  4940. lea offset1(regX), reg1
  4941. lea offset2(reg1), reg1
  4942. to
  4943. lea offset1+offset2(regX), reg1 }
  4944. else if
  4945. (
  4946. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4947. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4948. ) or (
  4949. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4950. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4951. (
  4952. (
  4953. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4954. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4955. ) or (
  4956. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4957. (
  4958. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4959. (
  4960. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4961. (
  4962. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4963. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4964. )
  4965. )
  4966. )
  4967. )
  4968. )
  4969. ) then
  4970. begin
  4971. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4972. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4973. begin
  4974. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4975. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4976. { if the register is used as index and base, we have to increase for base as well
  4977. and adapt base }
  4978. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4979. begin
  4980. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4981. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4982. end;
  4983. end
  4984. else
  4985. begin
  4986. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4987. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4988. end;
  4989. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4990. begin
  4991. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4992. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4993. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4994. end;
  4995. RemoveCurrentP(p);
  4996. result:=true;
  4997. exit;
  4998. end;
  4999. end;
  5000. { Change:
  5001. leal/q $x(%reg1),%reg2
  5002. ...
  5003. shll/q $y,%reg2
  5004. To:
  5005. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5006. }
  5007. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5008. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5009. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5010. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5011. (taicpu(hp1).oper[0]^.val <= 3) then
  5012. begin
  5013. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5014. TransferUsedRegs(TmpUsedRegs);
  5015. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5016. if
  5017. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5018. (this works even if scalefactor is zero) }
  5019. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5020. { Ensure offset doesn't go out of bounds }
  5021. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5022. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5023. (
  5024. (
  5025. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5026. (
  5027. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5028. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5029. (
  5030. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5031. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5032. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5033. )
  5034. )
  5035. ) or (
  5036. (
  5037. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5038. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5039. ) and
  5040. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5041. )
  5042. ) then
  5043. begin
  5044. repeat
  5045. with taicpu(p).oper[0]^.ref^ do
  5046. begin
  5047. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5048. if index = base then
  5049. begin
  5050. if Multiple > 4 then
  5051. { Optimisation will no longer work because resultant
  5052. scale factor will exceed 8 }
  5053. Break;
  5054. base := NR_NO;
  5055. scalefactor := 2;
  5056. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5057. end
  5058. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5059. begin
  5060. { Scale factor only works on the index register }
  5061. index := base;
  5062. base := NR_NO;
  5063. end;
  5064. { For safety }
  5065. if scalefactor <= 1 then
  5066. begin
  5067. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5068. scalefactor := Multiple;
  5069. end
  5070. else
  5071. begin
  5072. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5073. scalefactor := scalefactor * Multiple;
  5074. end;
  5075. offset := offset * Multiple;
  5076. end;
  5077. RemoveInstruction(hp1);
  5078. Result := True;
  5079. Exit;
  5080. { This repeat..until loop exists for the benefit of Break }
  5081. until True;
  5082. end;
  5083. end;
  5084. end;
  5085. end;
  5086. end;
  5087. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  5088. var
  5089. hp1 : tai;
  5090. begin
  5091. DoSubAddOpt := False;
  5092. if taicpu(p).oper[0]^.typ <> top_const then
  5093. { Should have been confirmed before calling }
  5094. InternalError(2021102601);
  5095. if GetLastInstruction(p, hp1) and
  5096. (hp1.typ = ait_instruction) and
  5097. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5098. case taicpu(hp1).opcode Of
  5099. A_DEC:
  5100. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5101. begin
  5102. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  5103. RemoveInstruction(hp1);
  5104. end;
  5105. A_SUB:
  5106. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5107. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5108. begin
  5109. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  5110. RemoveInstruction(hp1);
  5111. end;
  5112. A_ADD:
  5113. begin
  5114. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5115. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5116. begin
  5117. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  5118. RemoveInstruction(hp1);
  5119. if (taicpu(p).oper[0]^.val = 0) then
  5120. begin
  5121. hp1 := tai(p.next);
  5122. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5123. if not GetLastInstruction(hp1, p) then
  5124. p := hp1;
  5125. DoSubAddOpt := True;
  5126. end
  5127. end;
  5128. end;
  5129. else
  5130. ;
  5131. end;
  5132. end;
  5133. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  5134. begin
  5135. Result := False;
  5136. if UpdateTmpUsedRegs then
  5137. TransferUsedRegs(TmpUsedRegs);
  5138. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5139. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5140. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5141. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5142. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5143. (
  5144. (
  5145. (taicpu(hp1).opcode = A_TEST)
  5146. ) or (
  5147. (taicpu(hp1).opcode = A_CMP) and
  5148. { A sanity check more than anything }
  5149. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5150. )
  5151. ) then
  5152. begin
  5153. { change
  5154. mov mem, %reg
  5155. cmp/test x, %reg / test %reg,%reg
  5156. (reg deallocated)
  5157. to
  5158. cmp/test x, mem / cmp 0, mem
  5159. }
  5160. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5161. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5162. begin
  5163. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5164. if (taicpu(hp1).opcode = A_TEST) and
  5165. (
  5166. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5167. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5168. ) then
  5169. begin
  5170. taicpu(hp1).opcode := A_CMP;
  5171. taicpu(hp1).loadconst(0, 0);
  5172. end;
  5173. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5174. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5175. RemoveCurrentP(p, hp1);
  5176. Result := True;
  5177. Exit;
  5178. end;
  5179. end;
  5180. end;
  5181. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5182. var
  5183. hp2, hp3, hp4, hp5, hp6: tai;
  5184. ThisReg: TRegister;
  5185. JumpLoc: TAsmLabel;
  5186. begin
  5187. Result := False;
  5188. {
  5189. Convert:
  5190. j<c> .L1
  5191. .L2:
  5192. mov 1,reg
  5193. jmp .L3 (or ret, although it might not be a RET yet)
  5194. .L1:
  5195. mov 0,reg
  5196. jmp .L3 (or ret)
  5197. ( As long as .L3 <> .L1 or .L2)
  5198. To:
  5199. mov 0,reg
  5200. set<not(c)> reg
  5201. jmp .L3 (or ret)
  5202. .L2:
  5203. mov 1,reg
  5204. jmp .L3 (or ret)
  5205. .L1:
  5206. mov 0,reg
  5207. jmp .L3 (or ret)
  5208. }
  5209. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5210. Exit;
  5211. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5212. if GetNextInstruction(hp_label, hp2) and
  5213. MatchInstruction(hp2,A_MOV,[]) and
  5214. (taicpu(hp2).oper[0]^.typ = top_const) and
  5215. (
  5216. (
  5217. (taicpu(hp2).oper[1]^.typ = top_reg)
  5218. {$ifdef i386}
  5219. { Under i386, ESI, EDI, EBP and ESP
  5220. don't have an 8-bit representation }
  5221. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5222. {$endif i386}
  5223. ) or (
  5224. {$ifdef i386}
  5225. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5226. {$endif i386}
  5227. (taicpu(hp2).opsize = S_B)
  5228. )
  5229. ) and
  5230. GetNextInstruction(hp2, hp3) and
  5231. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5232. (
  5233. (taicpu(hp3).opcode=A_RET) or
  5234. (
  5235. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5236. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5237. )
  5238. ) and
  5239. GetNextInstruction(hp3, hp4) and
  5240. SkipAligns(hp4, hp4) and
  5241. (hp4.typ=ait_label) and
  5242. (tai_label(hp4).labsym=JumpLoc) and
  5243. (
  5244. not (cs_opt_size in current_settings.optimizerswitches) or
  5245. { If the initial jump is the label's only reference, then it will
  5246. become a dead label if the other conditions are met and hence
  5247. remove at least 2 instructions, including a jump }
  5248. (JumpLoc.getrefs = 1)
  5249. ) and
  5250. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5251. that will be optimised out }
  5252. GetNextInstruction(hp4, hp5) and
  5253. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5254. (taicpu(hp5).oper[0]^.typ = top_const) and
  5255. (
  5256. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5257. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5258. ) and
  5259. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5260. GetNextInstruction(hp5,hp6) and
  5261. (
  5262. (hp6.typ<>ait_label) or
  5263. SkipLabels(hp6, hp6)
  5264. ) and
  5265. (hp6.typ=ait_instruction) then
  5266. begin
  5267. { First, let's look at the two jumps that are hp3 and hp6 }
  5268. if not
  5269. (
  5270. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5271. (
  5272. (taicpu(hp6).opcode=A_RET) or
  5273. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5274. )
  5275. ) then
  5276. { If condition is False, then the JMP/RET instructions matched conventionally }
  5277. begin
  5278. { See if one of the jumps can be instantly converted into a RET }
  5279. if (taicpu(hp3).opcode=A_JMP) then
  5280. begin
  5281. { Reuse hp5 }
  5282. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5283. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5284. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5285. Exit;
  5286. if MatchInstruction(hp5, A_RET, []) then
  5287. begin
  5288. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5289. ConvertJumpToRET(hp3, hp5);
  5290. Result := True;
  5291. end
  5292. else
  5293. Exit;
  5294. end;
  5295. if (taicpu(hp6).opcode=A_JMP) then
  5296. begin
  5297. { Reuse hp5 }
  5298. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5299. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5300. Exit;
  5301. if MatchInstruction(hp5, A_RET, []) then
  5302. begin
  5303. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5304. ConvertJumpToRET(hp6, hp5);
  5305. Result := True;
  5306. end
  5307. else
  5308. Exit;
  5309. end;
  5310. if not
  5311. (
  5312. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5313. (
  5314. (taicpu(hp6).opcode=A_RET) or
  5315. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5316. )
  5317. ) then
  5318. { Still doesn't match }
  5319. Exit;
  5320. end;
  5321. if (taicpu(hp2).oper[0]^.val = 1) then
  5322. begin
  5323. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5324. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5325. end
  5326. else
  5327. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5328. if taicpu(hp2).opsize=S_B then
  5329. begin
  5330. if taicpu(hp2).oper[1]^.typ = top_reg then
  5331. hp4:=taicpu.op_reg(A_SETcc, S_B, taicpu(hp2).oper[1]^.reg)
  5332. else
  5333. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5334. hp2 := p;
  5335. end
  5336. else
  5337. begin
  5338. { Will be a register because the size can't be S_B otherwise }
  5339. ThisReg:=newreg(R_INTREGISTER,getsupreg(taicpu(hp2).oper[1]^.reg), R_SUBL);
  5340. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5341. hp2:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, taicpu(hp2).oper[1]^.reg);
  5342. taicpu(hp2).fileinfo:=taicpu(p).fileinfo;
  5343. { Inserting it right before p will guarantee that the flags are also tracked }
  5344. Asml.InsertBefore(hp2, p);
  5345. end;
  5346. taicpu(hp4).fileinfo := taicpu(hp2).fileinfo;
  5347. taicpu(hp4).condition := taicpu(p).condition;
  5348. asml.InsertBefore(hp4, hp2);
  5349. JumpLoc.decrefs;
  5350. if taicpu(hp3).opcode = A_JMP then
  5351. begin
  5352. MakeUnconditional(taicpu(p));
  5353. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5354. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5355. end
  5356. else
  5357. begin
  5358. taicpu(p).condition := C_None;
  5359. taicpu(p).opcode := A_RET;
  5360. taicpu(p).clearop(0);
  5361. taicpu(p).ops := 0;
  5362. end;
  5363. if (JumpLoc.getrefs = 0) then
  5364. RemoveDeadCodeAfterJump(hp3);
  5365. Result:=true;
  5366. exit;
  5367. end;
  5368. end;
  5369. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5370. var
  5371. hp1, hp2: tai;
  5372. ActiveReg: TRegister;
  5373. OldOffset: asizeint;
  5374. ThisConst: TCGInt;
  5375. function RegDeallocated: Boolean;
  5376. begin
  5377. TransferUsedRegs(TmpUsedRegs);
  5378. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5379. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5380. end;
  5381. begin
  5382. Result:=false;
  5383. hp1 := nil;
  5384. { replace
  5385. subX const,%reg1
  5386. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5387. dealloc %reg1
  5388. by
  5389. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5390. }
  5391. if MatchOpType(taicpu(p),top_const,top_reg) then
  5392. begin
  5393. ActiveReg := taicpu(p).oper[1]^.reg;
  5394. { Ensures the entire register was updated }
  5395. if (taicpu(p).opsize >= S_L) and
  5396. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5397. MatchInstruction(hp1,A_LEA,[]) and
  5398. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5399. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5400. (
  5401. { Cover the case where the register in the reference is also the destination register }
  5402. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5403. (
  5404. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5405. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5406. RegDeallocated
  5407. )
  5408. ) then
  5409. begin
  5410. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5411. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5412. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5413. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5414. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5415. {$ifdef x86_64}
  5416. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5417. begin
  5418. { Overflow; abort }
  5419. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5420. end
  5421. else
  5422. {$endif x86_64}
  5423. begin
  5424. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5425. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5426. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5427. RemoveCurrentP(p, hp1)
  5428. else
  5429. RemoveCurrentP(p);
  5430. result:=true;
  5431. Exit;
  5432. end;
  5433. end;
  5434. if (
  5435. { Save calling GetNextInstructionUsingReg again }
  5436. Assigned(hp1) or
  5437. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5438. ) and
  5439. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5440. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5441. begin
  5442. if taicpu(hp1).oper[0]^.typ = top_const then
  5443. begin
  5444. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5445. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5446. Result := True;
  5447. { Handle any overflows }
  5448. case taicpu(p).opsize of
  5449. S_B:
  5450. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5451. S_W:
  5452. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5453. S_L:
  5454. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5455. {$ifdef x86_64}
  5456. S_Q:
  5457. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5458. { Overflow; abort }
  5459. Result := False
  5460. else
  5461. taicpu(p).oper[0]^.val := ThisConst;
  5462. {$endif x86_64}
  5463. else
  5464. InternalError(2021102610);
  5465. end;
  5466. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5467. if Result then
  5468. begin
  5469. if (taicpu(p).oper[0]^.val < 0) and
  5470. (
  5471. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5472. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5473. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5474. ) then
  5475. begin
  5476. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5477. taicpu(p).opcode := A_SUB;
  5478. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5479. end
  5480. else
  5481. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5482. RemoveInstruction(hp1);
  5483. end;
  5484. end
  5485. else
  5486. begin
  5487. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5488. TransferUsedRegs(TmpUsedRegs);
  5489. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5490. hp2 := p;
  5491. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5492. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5493. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5494. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5495. begin
  5496. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5497. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5498. Asml.Remove(p);
  5499. Asml.InsertAfter(p, hp1);
  5500. p := hp1;
  5501. Result := True;
  5502. Exit;
  5503. end;
  5504. end;
  5505. end;
  5506. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5507. { * change "sub/add const1, reg" or "dec reg" followed by
  5508. "sub const2, reg" to one "sub ..., reg" }
  5509. {$ifdef i386}
  5510. if (taicpu(p).oper[0]^.val = 2) and
  5511. (ActiveReg = NR_ESP) and
  5512. { Don't do the sub/push optimization if the sub }
  5513. { comes from setting up the stack frame (JM) }
  5514. (not(GetLastInstruction(p,hp1)) or
  5515. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5516. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5517. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5518. begin
  5519. hp1 := tai(p.next);
  5520. while Assigned(hp1) and
  5521. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5522. not RegReadByInstruction(NR_ESP,hp1) and
  5523. not RegModifiedByInstruction(NR_ESP,hp1) do
  5524. hp1 := tai(hp1.next);
  5525. if Assigned(hp1) and
  5526. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5527. begin
  5528. taicpu(hp1).changeopsize(S_L);
  5529. if taicpu(hp1).oper[0]^.typ=top_reg then
  5530. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5531. hp1 := tai(p.next);
  5532. RemoveCurrentp(p, hp1);
  5533. Result:=true;
  5534. exit;
  5535. end;
  5536. end;
  5537. {$endif i386}
  5538. if DoSubAddOpt(p) then
  5539. Result:=true;
  5540. end;
  5541. end;
  5542. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5543. var
  5544. TmpBool1,TmpBool2 : Boolean;
  5545. tmpref : treference;
  5546. hp1,hp2: tai;
  5547. mask: tcgint;
  5548. begin
  5549. Result:=false;
  5550. { All these optimisations work on "shl/sal const,%reg" }
  5551. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5552. Exit;
  5553. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5554. (taicpu(p).oper[0]^.val <= 3) then
  5555. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5556. begin
  5557. { should we check the next instruction? }
  5558. TmpBool1 := True;
  5559. { have we found an add/sub which could be
  5560. integrated in the lea? }
  5561. TmpBool2 := False;
  5562. reference_reset(tmpref,2,[]);
  5563. TmpRef.index := taicpu(p).oper[1]^.reg;
  5564. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5565. while TmpBool1 and
  5566. GetNextInstruction(p, hp1) and
  5567. (tai(hp1).typ = ait_instruction) and
  5568. ((((taicpu(hp1).opcode = A_ADD) or
  5569. (taicpu(hp1).opcode = A_SUB)) and
  5570. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5571. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5572. (((taicpu(hp1).opcode = A_INC) or
  5573. (taicpu(hp1).opcode = A_DEC)) and
  5574. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5575. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5576. ((taicpu(hp1).opcode = A_LEA) and
  5577. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5578. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5579. (not GetNextInstruction(hp1,hp2) or
  5580. not instrReadsFlags(hp2)) Do
  5581. begin
  5582. TmpBool1 := False;
  5583. if taicpu(hp1).opcode=A_LEA then
  5584. begin
  5585. if (TmpRef.base = NR_NO) and
  5586. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5587. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5588. { Segment register isn't a concern here }
  5589. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5590. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5591. begin
  5592. TmpBool1 := True;
  5593. TmpBool2 := True;
  5594. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5595. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5596. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5597. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5598. RemoveInstruction(hp1);
  5599. end
  5600. end
  5601. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5602. begin
  5603. TmpBool1 := True;
  5604. TmpBool2 := True;
  5605. case taicpu(hp1).opcode of
  5606. A_ADD:
  5607. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5608. A_SUB:
  5609. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5610. else
  5611. internalerror(2019050536);
  5612. end;
  5613. RemoveInstruction(hp1);
  5614. end
  5615. else
  5616. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5617. (((taicpu(hp1).opcode = A_ADD) and
  5618. (TmpRef.base = NR_NO)) or
  5619. (taicpu(hp1).opcode = A_INC) or
  5620. (taicpu(hp1).opcode = A_DEC)) then
  5621. begin
  5622. TmpBool1 := True;
  5623. TmpBool2 := True;
  5624. case taicpu(hp1).opcode of
  5625. A_ADD:
  5626. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5627. A_INC:
  5628. inc(TmpRef.offset);
  5629. A_DEC:
  5630. dec(TmpRef.offset);
  5631. else
  5632. internalerror(2019050535);
  5633. end;
  5634. RemoveInstruction(hp1);
  5635. end;
  5636. end;
  5637. if TmpBool2
  5638. {$ifndef x86_64}
  5639. or
  5640. ((current_settings.optimizecputype < cpu_Pentium2) and
  5641. (taicpu(p).oper[0]^.val <= 3) and
  5642. not(cs_opt_size in current_settings.optimizerswitches))
  5643. {$endif x86_64}
  5644. then
  5645. begin
  5646. if not(TmpBool2) and
  5647. (taicpu(p).oper[0]^.val=1) then
  5648. begin
  5649. taicpu(p).opcode := A_ADD;
  5650. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  5651. end
  5652. else
  5653. begin
  5654. taicpu(p).opcode := A_LEA;
  5655. taicpu(p).loadref(0, TmpRef);
  5656. end;
  5657. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5658. Result := True;
  5659. end;
  5660. end
  5661. {$ifndef x86_64}
  5662. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5663. begin
  5664. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5665. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5666. (unlike shl, which is only Tairable in the U pipe) }
  5667. if taicpu(p).oper[0]^.val=1 then
  5668. begin
  5669. taicpu(p).opcode := A_ADD;
  5670. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  5671. Result := True;
  5672. end
  5673. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5674. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5675. else if (taicpu(p).opsize = S_L) and
  5676. (taicpu(p).oper[0]^.val<= 3) then
  5677. begin
  5678. reference_reset(tmpref,2,[]);
  5679. TmpRef.index := taicpu(p).oper[1]^.reg;
  5680. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5681. taicpu(p).opcode := A_LEA;
  5682. taicpu(p).loadref(0, TmpRef);
  5683. Result := True;
  5684. end;
  5685. end
  5686. {$endif x86_64}
  5687. else if
  5688. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5689. (
  5690. (
  5691. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5692. SetAndTest(hp1, hp2)
  5693. {$ifdef x86_64}
  5694. ) or
  5695. (
  5696. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5697. GetNextInstruction(hp1, hp2) and
  5698. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5699. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5700. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5701. {$endif x86_64}
  5702. )
  5703. ) and
  5704. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5705. begin
  5706. { Change:
  5707. shl x, %reg1
  5708. mov -(1<<x), %reg2
  5709. and %reg2, %reg1
  5710. Or:
  5711. shl x, %reg1
  5712. and -(1<<x), %reg1
  5713. To just:
  5714. shl x, %reg1
  5715. Since the and operation only zeroes bits that are already zero from the shl operation
  5716. }
  5717. case taicpu(p).oper[0]^.val of
  5718. 8:
  5719. mask:=$FFFFFFFFFFFFFF00;
  5720. 16:
  5721. mask:=$FFFFFFFFFFFF0000;
  5722. 32:
  5723. mask:=$FFFFFFFF00000000;
  5724. 63:
  5725. { Constant pre-calculated to prevent overflow errors with Int64 }
  5726. mask:=$8000000000000000;
  5727. else
  5728. begin
  5729. if taicpu(p).oper[0]^.val >= 64 then
  5730. { Shouldn't happen realistically, since the register
  5731. is guaranteed to be set to zero at this point }
  5732. mask := 0
  5733. else
  5734. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5735. end;
  5736. end;
  5737. if taicpu(hp1).oper[0]^.val = mask then
  5738. begin
  5739. { Everything checks out, perform the optimisation, as long as
  5740. the FLAGS register isn't being used}
  5741. TransferUsedRegs(TmpUsedRegs);
  5742. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5743. {$ifdef x86_64}
  5744. if (hp1 <> hp2) then
  5745. begin
  5746. { "shl/mov/and" version }
  5747. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5748. { Don't do the optimisation if the FLAGS register is in use }
  5749. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5750. begin
  5751. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5752. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5753. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5754. begin
  5755. RemoveInstruction(hp1);
  5756. Result := True;
  5757. end;
  5758. { Only set Result to True if the 'mov' instruction was removed }
  5759. RemoveInstruction(hp2);
  5760. end;
  5761. end
  5762. else
  5763. {$endif x86_64}
  5764. begin
  5765. { "shl/and" version }
  5766. { Don't do the optimisation if the FLAGS register is in use }
  5767. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5768. begin
  5769. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5770. RemoveInstruction(hp1);
  5771. Result := True;
  5772. end;
  5773. end;
  5774. Exit;
  5775. end
  5776. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5777. begin
  5778. { Even if the mask doesn't allow for its removal, we might be
  5779. able to optimise the mask for the "shl/and" version, which
  5780. may permit other peephole optimisations }
  5781. {$ifdef DEBUG_AOPTCPU}
  5782. mask := taicpu(hp1).oper[0]^.val and mask;
  5783. if taicpu(hp1).oper[0]^.val <> mask then
  5784. begin
  5785. DebugMsg(
  5786. SPeepholeOptimization +
  5787. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5788. ' to $' + debug_tostr(mask) +
  5789. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5790. taicpu(hp1).oper[0]^.val := mask;
  5791. end;
  5792. {$else DEBUG_AOPTCPU}
  5793. { If debugging is off, just set the operand even if it's the same }
  5794. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5795. {$endif DEBUG_AOPTCPU}
  5796. end;
  5797. end;
  5798. {
  5799. change
  5800. shl/sal const,reg
  5801. <op> ...(...,reg,1),...
  5802. into
  5803. <op> ...(...,reg,1 shl const),...
  5804. if const in 1..3
  5805. }
  5806. if MatchOpType(taicpu(p), top_const, top_reg) and
  5807. (taicpu(p).oper[0]^.val in [1..3]) and
  5808. GetNextInstruction(p, hp1) and
  5809. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5810. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5811. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5812. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5813. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5814. begin
  5815. TransferUsedRegs(TmpUsedRegs);
  5816. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5817. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5818. begin
  5819. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5820. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5821. RemoveCurrentP(p);
  5822. Result:=true;
  5823. end;
  5824. end;
  5825. end;
  5826. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5827. var
  5828. CurrentRef: TReference;
  5829. FullReg: TRegister;
  5830. hp1, hp2: tai;
  5831. begin
  5832. Result := False;
  5833. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5834. Exit;
  5835. { We assume you've checked if the operand is actually a reference by
  5836. this point. If it isn't, you'll most likely get an access violation }
  5837. CurrentRef := first_mov.oper[1]^.ref^;
  5838. { Memory must be aligned }
  5839. if (CurrentRef.offset mod 4) <> 0 then
  5840. Exit;
  5841. Inc(CurrentRef.offset);
  5842. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5843. if MatchOperand(second_mov.oper[0]^, 0) and
  5844. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5845. GetNextInstruction(second_mov, hp1) and
  5846. (hp1.typ = ait_instruction) and
  5847. (taicpu(hp1).opcode = A_MOV) and
  5848. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5849. (taicpu(hp1).oper[0]^.val = 0) then
  5850. begin
  5851. Inc(CurrentRef.offset);
  5852. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5853. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5854. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5855. begin
  5856. case taicpu(hp1).opsize of
  5857. S_B:
  5858. if GetNextInstruction(hp1, hp2) and
  5859. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5860. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5861. (taicpu(hp2).oper[0]^.val = 0) then
  5862. begin
  5863. Inc(CurrentRef.offset);
  5864. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5865. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5866. (taicpu(hp2).opsize = S_B) then
  5867. begin
  5868. RemoveInstruction(hp1);
  5869. RemoveInstruction(hp2);
  5870. first_mov.opsize := S_L;
  5871. if first_mov.oper[0]^.typ = top_reg then
  5872. begin
  5873. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5874. { Reuse second_mov as a MOVZX instruction }
  5875. second_mov.opcode := A_MOVZX;
  5876. second_mov.opsize := S_BL;
  5877. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5878. second_mov.loadreg(1, FullReg);
  5879. first_mov.oper[0]^.reg := FullReg;
  5880. asml.Remove(second_mov);
  5881. asml.InsertBefore(second_mov, first_mov);
  5882. end
  5883. else
  5884. { It's a value }
  5885. begin
  5886. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5887. RemoveInstruction(second_mov);
  5888. end;
  5889. Result := True;
  5890. Exit;
  5891. end;
  5892. end;
  5893. S_W:
  5894. begin
  5895. RemoveInstruction(hp1);
  5896. first_mov.opsize := S_L;
  5897. if first_mov.oper[0]^.typ = top_reg then
  5898. begin
  5899. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5900. { Reuse second_mov as a MOVZX instruction }
  5901. second_mov.opcode := A_MOVZX;
  5902. second_mov.opsize := S_BL;
  5903. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5904. second_mov.loadreg(1, FullReg);
  5905. first_mov.oper[0]^.reg := FullReg;
  5906. asml.Remove(second_mov);
  5907. asml.InsertBefore(second_mov, first_mov);
  5908. end
  5909. else
  5910. { It's a value }
  5911. begin
  5912. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5913. RemoveInstruction(second_mov);
  5914. end;
  5915. Result := True;
  5916. Exit;
  5917. end;
  5918. else
  5919. ;
  5920. end;
  5921. end;
  5922. end;
  5923. end;
  5924. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5925. { returns true if a "continue" should be done after this optimization }
  5926. var
  5927. hp1, hp2: tai;
  5928. begin
  5929. Result := false;
  5930. if MatchOpType(taicpu(p),top_ref) and
  5931. GetNextInstruction(p, hp1) and
  5932. (hp1.typ = ait_instruction) and
  5933. (((taicpu(hp1).opcode = A_FLD) and
  5934. (taicpu(p).opcode = A_FSTP)) or
  5935. ((taicpu(p).opcode = A_FISTP) and
  5936. (taicpu(hp1).opcode = A_FILD))) and
  5937. MatchOpType(taicpu(hp1),top_ref) and
  5938. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5939. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5940. begin
  5941. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5942. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5943. GetNextInstruction(hp1, hp2) and
  5944. (hp2.typ = ait_instruction) and
  5945. IsExitCode(hp2) and
  5946. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5947. not(assigned(current_procinfo.procdef.funcretsym) and
  5948. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5949. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5950. begin
  5951. RemoveInstruction(hp1);
  5952. RemoveCurrentP(p, hp2);
  5953. RemoveLastDeallocForFuncRes(p);
  5954. Result := true;
  5955. end
  5956. else
  5957. { we can do this only in fast math mode as fstp is rounding ...
  5958. ... still disabled as it breaks the compiler and/or rtl }
  5959. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5960. { ... or if another fstp equal to the first one follows }
  5961. (GetNextInstruction(hp1,hp2) and
  5962. (hp2.typ = ait_instruction) and
  5963. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5964. (taicpu(p).opsize=taicpu(hp2).opsize))
  5965. ) and
  5966. { fst can't store an extended/comp value }
  5967. (taicpu(p).opsize <> S_FX) and
  5968. (taicpu(p).opsize <> S_IQ) then
  5969. begin
  5970. if (taicpu(p).opcode = A_FSTP) then
  5971. taicpu(p).opcode := A_FST
  5972. else
  5973. taicpu(p).opcode := A_FIST;
  5974. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5975. RemoveInstruction(hp1);
  5976. end;
  5977. end;
  5978. end;
  5979. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5980. var
  5981. hp1, hp2: tai;
  5982. begin
  5983. result:=false;
  5984. if MatchOpType(taicpu(p),top_reg) and
  5985. GetNextInstruction(p, hp1) and
  5986. (hp1.typ = Ait_Instruction) and
  5987. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5988. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5989. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5990. { change to
  5991. fld reg fxxx reg,st
  5992. fxxxp st, st1 (hp1)
  5993. Remark: non commutative operations must be reversed!
  5994. }
  5995. begin
  5996. case taicpu(hp1).opcode Of
  5997. A_FMULP,A_FADDP,
  5998. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5999. begin
  6000. case taicpu(hp1).opcode Of
  6001. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6002. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6003. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6004. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6005. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6006. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6007. else
  6008. internalerror(2019050534);
  6009. end;
  6010. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6011. taicpu(hp1).oper[1]^.reg := NR_ST;
  6012. RemoveCurrentP(p, hp1);
  6013. Result:=true;
  6014. exit;
  6015. end;
  6016. else
  6017. ;
  6018. end;
  6019. end
  6020. else
  6021. if MatchOpType(taicpu(p),top_ref) and
  6022. GetNextInstruction(p, hp2) and
  6023. (hp2.typ = Ait_Instruction) and
  6024. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6025. (taicpu(p).opsize in [S_FS, S_FL]) and
  6026. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6027. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6028. if GetLastInstruction(p, hp1) and
  6029. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6030. MatchOpType(taicpu(hp1),top_ref) and
  6031. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6032. if ((taicpu(hp2).opcode = A_FMULP) or
  6033. (taicpu(hp2).opcode = A_FADDP)) then
  6034. { change to
  6035. fld/fst mem1 (hp1) fld/fst mem1
  6036. fld mem1 (p) fadd/
  6037. faddp/ fmul st, st
  6038. fmulp st, st1 (hp2) }
  6039. begin
  6040. RemoveCurrentP(p, hp1);
  6041. if (taicpu(hp2).opcode = A_FADDP) then
  6042. taicpu(hp2).opcode := A_FADD
  6043. else
  6044. taicpu(hp2).opcode := A_FMUL;
  6045. taicpu(hp2).oper[1]^.reg := NR_ST;
  6046. end
  6047. else
  6048. { change to
  6049. fld/fst mem1 (hp1) fld/fst mem1
  6050. fld mem1 (p) fld st}
  6051. begin
  6052. taicpu(p).changeopsize(S_FL);
  6053. taicpu(p).loadreg(0,NR_ST);
  6054. end
  6055. else
  6056. begin
  6057. case taicpu(hp2).opcode Of
  6058. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6059. { change to
  6060. fld/fst mem1 (hp1) fld/fst mem1
  6061. fld mem2 (p) fxxx mem2
  6062. fxxxp st, st1 (hp2) }
  6063. begin
  6064. case taicpu(hp2).opcode Of
  6065. A_FADDP: taicpu(p).opcode := A_FADD;
  6066. A_FMULP: taicpu(p).opcode := A_FMUL;
  6067. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6068. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6069. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6070. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6071. else
  6072. internalerror(2019050533);
  6073. end;
  6074. RemoveInstruction(hp2);
  6075. end
  6076. else
  6077. ;
  6078. end
  6079. end
  6080. end;
  6081. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6082. begin
  6083. Result := condition_in(cond1, cond2) or
  6084. { Not strictly subsets due to the actual flags checked, but because we're
  6085. comparing integers, E is a subset of AE and GE and their aliases }
  6086. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6087. end;
  6088. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6089. var
  6090. v: TCGInt;
  6091. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6092. FirstMatch: Boolean;
  6093. NewReg: TRegister;
  6094. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6095. begin
  6096. Result:=false;
  6097. { All these optimisations need a next instruction }
  6098. if not GetNextInstruction(p, hp1) then
  6099. Exit;
  6100. { Search for:
  6101. cmp ###,###
  6102. j(c1) @lbl1
  6103. ...
  6104. @lbl:
  6105. cmp ###,### (same comparison as above)
  6106. j(c2) @lbl2
  6107. If c1 is a subset of c2, change to:
  6108. cmp ###,###
  6109. j(c1) @lbl2
  6110. (@lbl1 may become a dead label as a result)
  6111. }
  6112. { Also handle cases where there are multiple jumps in a row }
  6113. p_jump := hp1;
  6114. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6115. begin
  6116. if IsJumpToLabel(taicpu(p_jump)) then
  6117. begin
  6118. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6119. p_label := nil;
  6120. if Assigned(JumpLabel) then
  6121. p_label := getlabelwithsym(JumpLabel);
  6122. if Assigned(p_label) and
  6123. GetNextInstruction(p_label, p_dist) and
  6124. MatchInstruction(p_dist, A_CMP, []) and
  6125. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6126. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6127. GetNextInstruction(p_dist, hp1_dist) and
  6128. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6129. begin
  6130. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6131. if JumpLabel = JumpLabel_dist then
  6132. { This is an infinite loop }
  6133. Exit;
  6134. { Best optimisation when the first condition is a subset (or equal) of the second }
  6135. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6136. begin
  6137. { Any registers used here will already be allocated }
  6138. if Assigned(JumpLabel) then
  6139. JumpLabel.DecRefs;
  6140. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6141. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  6142. Result := True;
  6143. { Don't exit yet. Since p and p_jump haven't actually been
  6144. removed, we can check for more on this iteration }
  6145. end
  6146. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6147. GetNextInstruction(hp1_dist, hp1_label) and
  6148. SkipAligns(hp1_label, hp1_label) and
  6149. (hp1_label.typ = ait_label) then
  6150. begin
  6151. JumpLabel_far := tai_label(hp1_label).labsym;
  6152. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6153. { This is an infinite loop }
  6154. Exit;
  6155. if Assigned(JumpLabel_far) then
  6156. begin
  6157. { In this situation, if the first jump branches, the second one will never,
  6158. branch so change the destination label to after the second jump }
  6159. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  6160. if Assigned(JumpLabel) then
  6161. JumpLabel.DecRefs;
  6162. JumpLabel_far.IncRefs;
  6163. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  6164. Result := True;
  6165. { Don't exit yet. Since p and p_jump haven't actually been
  6166. removed, we can check for more on this iteration }
  6167. Continue;
  6168. end;
  6169. end;
  6170. end;
  6171. end;
  6172. { Search for:
  6173. cmp ###,###
  6174. j(c1) @lbl1
  6175. cmp ###,### (same as first)
  6176. Remove second cmp
  6177. }
  6178. if GetNextInstruction(p_jump, hp2) and
  6179. (
  6180. (
  6181. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  6182. (
  6183. (
  6184. MatchOpType(taicpu(p), top_const, top_reg) and
  6185. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6186. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  6187. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6188. ) or (
  6189. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  6190. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  6191. )
  6192. )
  6193. ) or (
  6194. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6195. MatchOperand(taicpu(p).oper[0]^, 0) and
  6196. (taicpu(p).oper[1]^.typ = top_reg) and
  6197. MatchInstruction(hp2, A_TEST, []) and
  6198. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6199. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6200. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6201. )
  6202. ) then
  6203. begin
  6204. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6205. RemoveInstruction(hp2);
  6206. Result := True;
  6207. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6208. end;
  6209. GetNextInstruction(p_jump, p_jump);
  6210. end;
  6211. {
  6212. Try to optimise the following:
  6213. cmp $x,### ($x and $y can be registers or constants)
  6214. je @lbl1 (only reference)
  6215. cmp $y,### (### are identical)
  6216. @Lbl:
  6217. sete %reg1
  6218. Change to:
  6219. cmp $x,###
  6220. sete %reg2 (allocate new %reg2)
  6221. cmp $y,###
  6222. sete %reg1
  6223. orb %reg2,%reg1
  6224. (dealloc %reg2)
  6225. This adds an instruction (so don't perform under -Os), but it removes
  6226. a conditional branch.
  6227. }
  6228. if not (cs_opt_size in current_settings.optimizerswitches) and
  6229. (
  6230. (hp1 = p_jump) or
  6231. GetNextInstruction(p, hp1)
  6232. ) and
  6233. MatchInstruction(hp1, A_Jcc, []) and
  6234. IsJumpToLabel(taicpu(hp1)) and
  6235. (taicpu(hp1).condition in [C_E, C_Z]) and
  6236. GetNextInstruction(hp1, hp2) and
  6237. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6238. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6239. { The first operand of CMP instructions can only be a register or
  6240. immediate anyway, so no need to check }
  6241. GetNextInstruction(hp2, p_label) and
  6242. (
  6243. (p_label.typ = ait_label) or
  6244. (
  6245. { Sometimes there's a zero-distance jump before the label, so deal with it here
  6246. to potentially cut down on the iterations of Pass 1 }
  6247. MatchInstruction(p_label, A_Jcc, []) and
  6248. IsJumpToLabel(taicpu(p_label)) and
  6249. { Use p_dist to hold the jump briefly }
  6250. SetAndTest(p_label, p_dist) and
  6251. GetNextInstruction(p_dist, p_label) and
  6252. (p_label.typ = ait_label) and
  6253. (tai_label(p_label).labsym.getrefs >= 2) and
  6254. (JumpTargetOp(taicpu(p_dist))^.ref^.symbol = tai_label(p_label).labsym) and
  6255. { We might as well collapse the jump now }
  6256. CollapseZeroDistJump(p_dist, tai_label(p_label).labsym)
  6257. )
  6258. ) and
  6259. (tai_label(p_label).labsym.getrefs = 1) and
  6260. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6261. GetNextInstruction(p_label, p_dist) and
  6262. MatchInstruction(p_dist, A_SETcc, []) and
  6263. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6264. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  6265. { Get the instruction after the SETcc instruction so we can
  6266. allocate a new register over the entire range }
  6267. GetNextInstruction(p_dist, hp1_dist) then
  6268. begin
  6269. TransferUsedRegs(TmpUsedRegs);
  6270. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6271. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6272. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6273. // UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6274. { RegUsedAfterInstruction modifies TmpUsedRegs }
  6275. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  6276. begin
  6277. { Register can appear in p if it's not used afterwards, so only
  6278. allocate between hp1 and hp1_dist }
  6279. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, p_dist);
  6280. if NewReg <> NR_NO then
  6281. begin
  6282. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6283. { Change the jump instruction into a SETcc instruction }
  6284. taicpu(hp1).opcode := A_SETcc;
  6285. taicpu(hp1).opsize := S_B;
  6286. taicpu(hp1).loadreg(0, NewReg);
  6287. { This is now a dead label }
  6288. tai_label(p_label).labsym.decrefs;
  6289. { Prefer adding before the next instruction so the FLAGS
  6290. register is deallocated first }
  6291. hp2 := taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg);
  6292. taicpu(hp2).fileinfo := taicpu(p_dist).fileinfo;
  6293. AsmL.InsertBefore(
  6294. hp2,
  6295. hp1_dist
  6296. );
  6297. { Make sure the new register is in use over the new instruction
  6298. (long-winded, but things work best when the FLAGS register
  6299. is not allocated here) }
  6300. AllocRegBetween(NewReg, p_dist, hp2, TmpUsedRegs);
  6301. Result := True;
  6302. { Don't exit yet, as p wasn't changed and hp1, while
  6303. modified, is still intact and might be optimised by the
  6304. SETcc optimisation below }
  6305. end;
  6306. end;
  6307. end;
  6308. if taicpu(p).oper[0]^.typ = top_const then
  6309. begin
  6310. if (taicpu(p).oper[0]^.val = 0) and
  6311. (taicpu(p).oper[1]^.typ = top_reg) and
  6312. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6313. begin
  6314. hp2 := p;
  6315. FirstMatch := True;
  6316. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6317. anything meaningful once it's converted to "test %reg,%reg";
  6318. additionally, some jumps will always (or never) branch, so
  6319. evaluate every jump immediately following the
  6320. comparison, optimising the conditions if possible.
  6321. Similarly with SETcc... those that are always set to 0 or 1
  6322. are changed to MOV instructions }
  6323. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6324. (
  6325. GetNextInstruction(hp2, hp1) and
  6326. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6327. ) do
  6328. begin
  6329. FirstMatch := False;
  6330. case taicpu(hp1).condition of
  6331. C_B, C_C, C_NAE, C_O:
  6332. { For B/NAE:
  6333. Will never branch since an unsigned integer can never be below zero
  6334. For C/O:
  6335. Result cannot overflow because 0 is being subtracted
  6336. }
  6337. begin
  6338. if taicpu(hp1).opcode = A_Jcc then
  6339. begin
  6340. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6341. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6342. RemoveInstruction(hp1);
  6343. { Since hp1 was deleted, hp2 must not be updated }
  6344. Continue;
  6345. end
  6346. else
  6347. begin
  6348. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6349. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6350. taicpu(hp1).opcode := A_MOV;
  6351. taicpu(hp1).ops := 2;
  6352. taicpu(hp1).condition := C_None;
  6353. taicpu(hp1).opsize := S_B;
  6354. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6355. taicpu(hp1).loadconst(0, 0);
  6356. end;
  6357. end;
  6358. C_BE, C_NA:
  6359. begin
  6360. { Will only branch if equal to zero }
  6361. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6362. taicpu(hp1).condition := C_E;
  6363. end;
  6364. C_A, C_NBE:
  6365. begin
  6366. { Will only branch if not equal to zero }
  6367. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6368. taicpu(hp1).condition := C_NE;
  6369. end;
  6370. C_AE, C_NB, C_NC, C_NO:
  6371. begin
  6372. { Will always branch }
  6373. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6374. if taicpu(hp1).opcode = A_Jcc then
  6375. begin
  6376. MakeUnconditional(taicpu(hp1));
  6377. { Any jumps/set that follow will now be dead code }
  6378. RemoveDeadCodeAfterJump(taicpu(hp1));
  6379. Break;
  6380. end
  6381. else
  6382. begin
  6383. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6384. taicpu(hp1).opcode := A_MOV;
  6385. taicpu(hp1).ops := 2;
  6386. taicpu(hp1).condition := C_None;
  6387. taicpu(hp1).opsize := S_B;
  6388. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6389. taicpu(hp1).loadconst(0, 1);
  6390. end;
  6391. end;
  6392. C_None:
  6393. InternalError(2020012201);
  6394. C_P, C_PE, C_NP, C_PO:
  6395. { We can't handle parity checks and they should never be generated
  6396. after a general-purpose CMP (it's used in some floating-point
  6397. comparisons that don't use CMP) }
  6398. InternalError(2020012202);
  6399. else
  6400. { Zero/Equality, Sign, their complements and all of the
  6401. signed comparisons do not need to be converted };
  6402. end;
  6403. hp2 := hp1;
  6404. end;
  6405. { Convert the instruction to a TEST }
  6406. taicpu(p).opcode := A_TEST;
  6407. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6408. Result := True;
  6409. Exit;
  6410. end
  6411. else if (taicpu(p).oper[0]^.val = 1) and
  6412. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6413. (taicpu(hp1).condition in [C_L, C_NGE]) then
  6414. begin
  6415. { Convert; To:
  6416. cmp $1,r/m cmp $0,r/m
  6417. jl @lbl jle @lbl
  6418. }
  6419. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  6420. taicpu(p).oper[0]^.val := 0;
  6421. taicpu(hp1).condition := C_LE;
  6422. { If the instruction is now "cmp $0,%reg", convert it to a
  6423. TEST (and effectively do the work of the "cmp $0,%reg" in
  6424. the block above)
  6425. If it's a reference, we can get away with not setting
  6426. Result to True because he haven't evaluated the jump
  6427. in this pass yet.
  6428. }
  6429. if (taicpu(p).oper[1]^.typ = top_reg) then
  6430. begin
  6431. taicpu(p).opcode := A_TEST;
  6432. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6433. Result := True;
  6434. end;
  6435. Exit;
  6436. end
  6437. else if (taicpu(p).oper[1]^.typ = top_reg)
  6438. {$ifdef x86_64}
  6439. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6440. {$endif x86_64}
  6441. then
  6442. begin
  6443. { cmp register,$8000 neg register
  6444. je target --> jo target
  6445. .... only if register is deallocated before jump.}
  6446. case Taicpu(p).opsize of
  6447. S_B: v:=$80;
  6448. S_W: v:=$8000;
  6449. S_L: v:=qword($80000000);
  6450. else
  6451. internalerror(2013112905);
  6452. end;
  6453. if (taicpu(p).oper[0]^.val=v) and
  6454. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6455. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6456. begin
  6457. TransferUsedRegs(TmpUsedRegs);
  6458. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6459. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6460. begin
  6461. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6462. Taicpu(p).opcode:=A_NEG;
  6463. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6464. Taicpu(p).clearop(1);
  6465. Taicpu(p).ops:=1;
  6466. if Taicpu(hp1).condition=C_E then
  6467. Taicpu(hp1).condition:=C_O
  6468. else
  6469. Taicpu(hp1).condition:=C_NO;
  6470. Result:=true;
  6471. exit;
  6472. end;
  6473. end;
  6474. end;
  6475. end;
  6476. if TrySwapMovCmp(p, hp1) then
  6477. begin
  6478. Result := True;
  6479. Exit;
  6480. end;
  6481. end;
  6482. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6483. var
  6484. hp1: tai;
  6485. begin
  6486. {
  6487. remove the second (v)pxor from
  6488. pxor reg,reg
  6489. ...
  6490. pxor reg,reg
  6491. }
  6492. Result:=false;
  6493. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6494. MatchOpType(taicpu(p),top_reg,top_reg) and
  6495. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6496. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6497. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6498. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  6499. begin
  6500. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  6501. RemoveInstruction(hp1);
  6502. Result:=true;
  6503. Exit;
  6504. end
  6505. {
  6506. replace
  6507. pxor reg1,reg1
  6508. movapd/s reg1,reg2
  6509. dealloc reg1
  6510. by
  6511. pxor reg2,reg2
  6512. }
  6513. else if GetNextInstruction(p,hp1) and
  6514. { we mix single and double opperations here because we assume that the compiler
  6515. generates vmovapd only after double operations and vmovaps only after single operations }
  6516. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  6517. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6518. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6519. (taicpu(p).oper[0]^.typ=top_reg) then
  6520. begin
  6521. TransferUsedRegs(TmpUsedRegs);
  6522. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6523. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6524. begin
  6525. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  6526. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6527. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6528. RemoveInstruction(hp1);
  6529. result:=true;
  6530. end;
  6531. end;
  6532. end;
  6533. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6534. var
  6535. hp1: tai;
  6536. begin
  6537. {
  6538. remove the second (v)pxor from
  6539. (v)pxor reg,reg
  6540. ...
  6541. (v)pxor reg,reg
  6542. }
  6543. Result:=false;
  6544. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6545. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  6546. begin
  6547. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6548. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6549. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6550. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6551. begin
  6552. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  6553. RemoveInstruction(hp1);
  6554. Result:=true;
  6555. Exit;
  6556. end;
  6557. {$ifdef x86_64}
  6558. {
  6559. replace
  6560. vpxor reg1,reg1,reg1
  6561. vmov reg,mem
  6562. by
  6563. movq $0,mem
  6564. }
  6565. if GetNextInstruction(p,hp1) and
  6566. MatchInstruction(hp1,A_VMOVSD,[]) and
  6567. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6568. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  6569. begin
  6570. TransferUsedRegs(TmpUsedRegs);
  6571. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6572. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6573. begin
  6574. taicpu(hp1).loadconst(0,0);
  6575. taicpu(hp1).opcode:=A_MOV;
  6576. taicpu(hp1).opsize:=S_Q;
  6577. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  6578. RemoveCurrentP(p);
  6579. result:=true;
  6580. Exit;
  6581. end;
  6582. end;
  6583. {$endif x86_64}
  6584. end
  6585. {
  6586. replace
  6587. vpxor reg1,reg1,reg2
  6588. by
  6589. vpxor reg2,reg2,reg2
  6590. to avoid unncessary data dependencies
  6591. }
  6592. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6593. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  6594. begin
  6595. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  6596. { avoid unncessary data dependency }
  6597. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  6598. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  6599. result:=true;
  6600. exit;
  6601. end;
  6602. Result:=OptPass1VOP(p);
  6603. end;
  6604. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6605. var
  6606. hp1 : tai;
  6607. begin
  6608. result:=false;
  6609. { replace
  6610. IMul const,%mreg1,%mreg2
  6611. Mov %reg2,%mreg3
  6612. dealloc %mreg3
  6613. by
  6614. Imul const,%mreg1,%mreg23
  6615. }
  6616. if (taicpu(p).ops=3) and
  6617. GetNextInstruction(p,hp1) and
  6618. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6619. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6620. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6621. begin
  6622. TransferUsedRegs(TmpUsedRegs);
  6623. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6624. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6625. begin
  6626. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6627. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6628. RemoveInstruction(hp1);
  6629. result:=true;
  6630. end;
  6631. end;
  6632. end;
  6633. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6634. var
  6635. hp1 : tai;
  6636. begin
  6637. result:=false;
  6638. { replace
  6639. IMul %reg0,%reg1,%reg2
  6640. Mov %reg2,%reg3
  6641. dealloc %reg2
  6642. by
  6643. Imul %reg0,%reg1,%reg3
  6644. }
  6645. if GetNextInstruction(p,hp1) and
  6646. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6647. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6648. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6649. begin
  6650. TransferUsedRegs(TmpUsedRegs);
  6651. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6652. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6653. begin
  6654. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6655. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6656. RemoveInstruction(hp1);
  6657. result:=true;
  6658. end;
  6659. end;
  6660. end;
  6661. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6662. var
  6663. hp1: tai;
  6664. begin
  6665. Result:=false;
  6666. { get rid of
  6667. (v)cvtss2sd reg0,<reg1,>reg2
  6668. (v)cvtss2sd reg2,<reg2,>reg0
  6669. }
  6670. if GetNextInstruction(p,hp1) and
  6671. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6672. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6673. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6674. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6675. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6676. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6677. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6678. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6679. )
  6680. ) then
  6681. begin
  6682. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6683. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6684. begin
  6685. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6686. RemoveCurrentP(p);
  6687. RemoveInstruction(hp1);
  6688. end
  6689. else
  6690. begin
  6691. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6692. if taicpu(hp1).opcode=A_CVTSD2SS then
  6693. begin
  6694. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6695. taicpu(p).opcode:=A_MOVAPS;
  6696. end
  6697. else
  6698. begin
  6699. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6700. taicpu(p).opcode:=A_VMOVAPS;
  6701. end;
  6702. taicpu(p).ops:=2;
  6703. RemoveInstruction(hp1);
  6704. end;
  6705. Result:=true;
  6706. Exit;
  6707. end;
  6708. end;
  6709. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6710. var
  6711. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  6712. ThisReg: TRegister;
  6713. begin
  6714. Result := False;
  6715. if not GetNextInstruction(p,hp1) then
  6716. Exit;
  6717. {
  6718. convert
  6719. j<c> .L1
  6720. mov 1,reg
  6721. jmp .L2
  6722. .L1
  6723. mov 0,reg
  6724. .L2
  6725. into
  6726. mov 0,reg
  6727. set<not(c)> reg
  6728. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6729. would destroy the flag contents
  6730. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6731. executed at the same time as a previous comparison.
  6732. set<not(c)> reg
  6733. movzx reg, reg
  6734. }
  6735. if MatchInstruction(hp1,A_MOV,[]) and
  6736. (taicpu(hp1).oper[0]^.typ = top_const) and
  6737. (
  6738. (
  6739. (taicpu(hp1).oper[1]^.typ = top_reg)
  6740. {$ifdef i386}
  6741. { Under i386, ESI, EDI, EBP and ESP
  6742. don't have an 8-bit representation }
  6743. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6744. {$endif i386}
  6745. ) or (
  6746. {$ifdef i386}
  6747. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6748. {$endif i386}
  6749. (taicpu(hp1).opsize = S_B)
  6750. )
  6751. ) and
  6752. GetNextInstruction(hp1,hp2) and
  6753. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6754. GetNextInstruction(hp2,hp3) and
  6755. SkipAligns(hp3, hp3) and
  6756. (hp3.typ=ait_label) and
  6757. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6758. GetNextInstruction(hp3,hp4) and
  6759. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6760. (taicpu(hp4).oper[0]^.typ = top_const) and
  6761. (
  6762. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6763. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6764. ) and
  6765. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6766. GetNextInstruction(hp4,hp5) and
  6767. SkipAligns(hp5, hp5) and
  6768. (hp5.typ=ait_label) and
  6769. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6770. begin
  6771. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6772. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6773. tai_label(hp3).labsym.DecRefs;
  6774. { If this isn't the only reference to the middle label, we can
  6775. still make a saving - only that the first jump and everything
  6776. that follows will remain. }
  6777. if (tai_label(hp3).labsym.getrefs = 0) then
  6778. begin
  6779. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6780. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6781. else
  6782. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6783. { remove jump, first label and second MOV (also catching any aligns) }
  6784. repeat
  6785. if not GetNextInstruction(hp2, hp3) then
  6786. InternalError(2021040810);
  6787. RemoveInstruction(hp2);
  6788. hp2 := hp3;
  6789. until hp2 = hp5;
  6790. { Don't decrement reference count before the removal loop
  6791. above, otherwise GetNextInstruction won't stop on the
  6792. the label }
  6793. tai_label(hp5).labsym.DecRefs;
  6794. end
  6795. else
  6796. begin
  6797. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6798. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6799. else
  6800. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6801. end;
  6802. taicpu(p).opcode:=A_SETcc;
  6803. taicpu(p).opsize:=S_B;
  6804. taicpu(p).is_jmp:=False;
  6805. if taicpu(hp1).opsize=S_B then
  6806. begin
  6807. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6808. if taicpu(hp1).oper[1]^.typ = top_reg then
  6809. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6810. RemoveInstruction(hp1);
  6811. end
  6812. else
  6813. begin
  6814. { Will be a register because the size can't be S_B otherwise }
  6815. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6816. taicpu(p).loadreg(0, ThisReg);
  6817. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6818. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6819. begin
  6820. case taicpu(hp1).opsize of
  6821. S_W:
  6822. taicpu(hp1).opsize := S_BW;
  6823. S_L:
  6824. taicpu(hp1).opsize := S_BL;
  6825. {$ifdef x86_64}
  6826. S_Q:
  6827. begin
  6828. taicpu(hp1).opsize := S_BL;
  6829. { Change the destination register to 32-bit }
  6830. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6831. end;
  6832. {$endif x86_64}
  6833. else
  6834. InternalError(2021040820);
  6835. end;
  6836. taicpu(hp1).opcode := A_MOVZX;
  6837. taicpu(hp1).loadreg(0, ThisReg);
  6838. end
  6839. else
  6840. begin
  6841. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6842. { hp1 is already a MOV instruction with the correct register }
  6843. taicpu(hp1).loadconst(0, 0);
  6844. { Inserting it right before p will guarantee that the flags are also tracked }
  6845. asml.Remove(hp1);
  6846. asml.InsertBefore(hp1, p);
  6847. end;
  6848. end;
  6849. Result:=true;
  6850. exit;
  6851. end
  6852. else if (hp1.typ = ait_label) then
  6853. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  6854. end;
  6855. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6856. var
  6857. hp1, hp2, hp3: tai;
  6858. SourceRef, TargetRef: TReference;
  6859. CurrentReg: TRegister;
  6860. begin
  6861. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6862. if not UseAVX then
  6863. InternalError(2021100501);
  6864. Result := False;
  6865. { Look for the following to simplify:
  6866. vmovdqa/u x(mem1), %xmmreg
  6867. vmovdqa/u %xmmreg, y(mem2)
  6868. vmovdqa/u x+16(mem1), %xmmreg
  6869. vmovdqa/u %xmmreg, y+16(mem2)
  6870. Change to:
  6871. vmovdqa/u x(mem1), %ymmreg
  6872. vmovdqa/u %ymmreg, y(mem2)
  6873. vpxor %ymmreg, %ymmreg, %ymmreg
  6874. ( The VPXOR instruction is to zero the upper half, thus removing the
  6875. need to call the potentially expensive VZEROUPPER instruction. Other
  6876. peephole optimisations can remove VPXOR if it's unnecessary )
  6877. }
  6878. TransferUsedRegs(TmpUsedRegs);
  6879. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6880. { NOTE: In the optimisations below, if the references dictate that an
  6881. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6882. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6883. if (taicpu(p).opsize = S_XMM) and
  6884. MatchOpType(taicpu(p), top_ref, top_reg) and
  6885. GetNextInstruction(p, hp1) and
  6886. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6887. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6888. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6889. begin
  6890. SourceRef := taicpu(p).oper[0]^.ref^;
  6891. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6892. if GetNextInstruction(hp1, hp2) and
  6893. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6894. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6895. begin
  6896. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6897. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6898. Inc(SourceRef.offset, 16);
  6899. { Reuse the register in the first block move }
  6900. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6901. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  6902. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  6903. begin
  6904. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6905. Inc(TargetRef.offset, 16);
  6906. if GetNextInstruction(hp2, hp3) and
  6907. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6908. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6909. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6910. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6911. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6912. begin
  6913. { Update the register tracking to the new size }
  6914. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6915. { Remember that the offsets are 16 ahead }
  6916. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6917. if not (
  6918. ((SourceRef.offset mod 32) = 16) and
  6919. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6920. ) then
  6921. taicpu(p).opcode := A_VMOVDQU;
  6922. taicpu(p).opsize := S_YMM;
  6923. taicpu(p).oper[1]^.reg := CurrentReg;
  6924. if not (
  6925. ((TargetRef.offset mod 32) = 16) and
  6926. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6927. ) then
  6928. taicpu(hp1).opcode := A_VMOVDQU;
  6929. taicpu(hp1).opsize := S_YMM;
  6930. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6931. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6932. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6933. if (pi_uses_ymm in current_procinfo.flags) then
  6934. RemoveInstruction(hp2)
  6935. else
  6936. begin
  6937. taicpu(hp2).opcode := A_VPXOR;
  6938. taicpu(hp2).opsize := S_YMM;
  6939. taicpu(hp2).loadreg(0, CurrentReg);
  6940. taicpu(hp2).loadreg(1, CurrentReg);
  6941. taicpu(hp2).loadreg(2, CurrentReg);
  6942. taicpu(hp2).ops := 3;
  6943. end;
  6944. RemoveInstruction(hp3);
  6945. Result := True;
  6946. Exit;
  6947. end;
  6948. end
  6949. else
  6950. begin
  6951. { See if the next references are 16 less rather than 16 greater }
  6952. Dec(SourceRef.offset, 32); { -16 the other way }
  6953. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6954. begin
  6955. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6956. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6957. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  6958. GetNextInstruction(hp2, hp3) and
  6959. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6960. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6961. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6962. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6963. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6964. begin
  6965. { Update the register tracking to the new size }
  6966. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6967. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6968. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6969. if not(
  6970. ((SourceRef.offset mod 32) = 0) and
  6971. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6972. ) then
  6973. taicpu(hp2).opcode := A_VMOVDQU;
  6974. taicpu(hp2).opsize := S_YMM;
  6975. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6976. if not (
  6977. ((TargetRef.offset mod 32) = 0) and
  6978. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6979. ) then
  6980. taicpu(hp3).opcode := A_VMOVDQU;
  6981. taicpu(hp3).opsize := S_YMM;
  6982. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6983. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6984. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6985. if (pi_uses_ymm in current_procinfo.flags) then
  6986. RemoveInstruction(hp1)
  6987. else
  6988. begin
  6989. taicpu(hp1).opcode := A_VPXOR;
  6990. taicpu(hp1).opsize := S_YMM;
  6991. taicpu(hp1).loadreg(0, CurrentReg);
  6992. taicpu(hp1).loadreg(1, CurrentReg);
  6993. taicpu(hp1).loadreg(2, CurrentReg);
  6994. taicpu(hp1).ops := 3;
  6995. Asml.Remove(hp1);
  6996. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  6997. end;
  6998. RemoveCurrentP(p, hp2);
  6999. Result := True;
  7000. Exit;
  7001. end;
  7002. end;
  7003. end;
  7004. end;
  7005. end;
  7006. end;
  7007. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7008. var
  7009. hp2, hp3, first_assignment: tai;
  7010. IncCount, OperIdx: Integer;
  7011. OrigLabel: TAsmLabel;
  7012. begin
  7013. Count := 0;
  7014. Result := False;
  7015. first_assignment := nil;
  7016. if (LoopCount >= 20) then
  7017. begin
  7018. { Guard against infinite loops }
  7019. Exit;
  7020. end;
  7021. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7022. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7023. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7024. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7025. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7026. Exit;
  7027. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7028. {
  7029. change
  7030. jmp .L1
  7031. ...
  7032. .L1:
  7033. mov ##, ## ( multiple movs possible )
  7034. jmp/ret
  7035. into
  7036. mov ##, ##
  7037. jmp/ret
  7038. }
  7039. if not Assigned(hp1) then
  7040. begin
  7041. hp1 := GetLabelWithSym(OrigLabel);
  7042. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7043. Exit;
  7044. end;
  7045. hp2 := hp1;
  7046. while Assigned(hp2) do
  7047. begin
  7048. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7049. SkipLabels(hp2,hp2);
  7050. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7051. Break;
  7052. case taicpu(hp2).opcode of
  7053. A_MOVSS:
  7054. begin
  7055. if taicpu(hp2).ops = 0 then
  7056. { Wrong MOVSS }
  7057. Break;
  7058. Inc(Count);
  7059. if Count >= 5 then
  7060. { Too many to be worthwhile }
  7061. Break;
  7062. GetNextInstruction(hp2, hp2);
  7063. Continue;
  7064. end;
  7065. A_MOV,
  7066. A_MOVD,
  7067. A_MOVQ,
  7068. A_MOVSX,
  7069. {$ifdef x86_64}
  7070. A_MOVSXD,
  7071. {$endif x86_64}
  7072. A_MOVZX,
  7073. A_MOVAPS,
  7074. A_MOVUPS,
  7075. A_MOVSD,
  7076. A_MOVAPD,
  7077. A_MOVUPD,
  7078. A_MOVDQA,
  7079. A_MOVDQU,
  7080. A_VMOVSS,
  7081. A_VMOVAPS,
  7082. A_VMOVUPS,
  7083. A_VMOVSD,
  7084. A_VMOVAPD,
  7085. A_VMOVUPD,
  7086. A_VMOVDQA,
  7087. A_VMOVDQU:
  7088. begin
  7089. Inc(Count);
  7090. if Count >= 5 then
  7091. { Too many to be worthwhile }
  7092. Break;
  7093. GetNextInstruction(hp2, hp2);
  7094. Continue;
  7095. end;
  7096. A_JMP:
  7097. begin
  7098. { Guard against infinite loops }
  7099. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7100. Exit;
  7101. { Analyse this jump first in case it also duplicates assignments }
  7102. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7103. begin
  7104. { Something did change! }
  7105. Result := True;
  7106. Inc(Count, IncCount);
  7107. if Count >= 5 then
  7108. begin
  7109. { Too many to be worthwhile }
  7110. Exit;
  7111. end;
  7112. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7113. Break;
  7114. end;
  7115. Result := True;
  7116. Break;
  7117. end;
  7118. A_RET:
  7119. begin
  7120. Result := True;
  7121. Break;
  7122. end;
  7123. else
  7124. Break;
  7125. end;
  7126. end;
  7127. if Result then
  7128. begin
  7129. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  7130. if Count = 0 then
  7131. begin
  7132. Result := False;
  7133. Exit;
  7134. end;
  7135. hp3 := p;
  7136. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  7137. while True do
  7138. begin
  7139. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  7140. SkipLabels(hp1,hp1);
  7141. if (hp1.typ <> ait_instruction) then
  7142. InternalError(2021040720);
  7143. case taicpu(hp1).opcode of
  7144. A_JMP:
  7145. begin
  7146. { Change the original jump to the new destination }
  7147. OrigLabel.decrefs;
  7148. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  7149. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  7150. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7151. if not Assigned(first_assignment) then
  7152. InternalError(2021040810)
  7153. else
  7154. p := first_assignment;
  7155. Exit;
  7156. end;
  7157. A_RET:
  7158. begin
  7159. { Now change the jump into a RET instruction }
  7160. ConvertJumpToRET(p, hp1);
  7161. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7162. if not Assigned(first_assignment) then
  7163. InternalError(2021040811)
  7164. else
  7165. p := first_assignment;
  7166. Exit;
  7167. end;
  7168. else
  7169. begin
  7170. { Duplicate the MOV instruction }
  7171. hp3:=tai(hp1.getcopy);
  7172. if first_assignment = nil then
  7173. first_assignment := hp3;
  7174. asml.InsertBefore(hp3, p);
  7175. { Make sure the compiler knows about any final registers written here }
  7176. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  7177. with taicpu(hp3).oper[OperIdx]^ do
  7178. begin
  7179. case typ of
  7180. top_ref:
  7181. begin
  7182. if (ref^.base <> NR_NO) and
  7183. (getsupreg(ref^.base) <> RS_ESP) and
  7184. (getsupreg(ref^.base) <> RS_EBP)
  7185. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  7186. then
  7187. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  7188. if (ref^.index <> NR_NO) and
  7189. (getsupreg(ref^.index) <> RS_ESP) and
  7190. (getsupreg(ref^.index) <> RS_EBP)
  7191. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  7192. (ref^.index <> ref^.base) then
  7193. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  7194. end;
  7195. top_reg:
  7196. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  7197. else
  7198. ;
  7199. end;
  7200. end;
  7201. end;
  7202. end;
  7203. if not GetNextInstruction(hp1, hp1) then
  7204. { Should have dropped out earlier }
  7205. InternalError(2021040710);
  7206. end;
  7207. end;
  7208. end;
  7209. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  7210. var
  7211. hp2: tai;
  7212. X: Integer;
  7213. const
  7214. WriteOp: array[0..3] of set of TInsChange = (
  7215. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  7216. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  7217. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  7218. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  7219. RegWriteFlags: array[0..7] of set of TInsChange = (
  7220. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  7221. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  7222. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  7223. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  7224. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  7225. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  7226. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  7227. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  7228. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  7229. begin
  7230. { If we have something like:
  7231. cmp ###,%reg1
  7232. mov 0,%reg2
  7233. And no modified registers are shared, move the instruction to before
  7234. the comparison as this means it can be optimised without worrying
  7235. about the FLAGS register. (CMP/MOV is generated by
  7236. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  7237. As long as the second instruction doesn't use the flags or one of the
  7238. registers used by CMP or TEST (also check any references that use the
  7239. registers), then it can be moved prior to the comparison.
  7240. }
  7241. Result := False;
  7242. if (hp1.typ <> ait_instruction) or
  7243. taicpu(hp1).is_jmp or
  7244. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  7245. Exit;
  7246. { NOP is a pipeline fence, likely marking the beginning of the function
  7247. epilogue, so drop out. Similarly, drop out if POP or RET are
  7248. encountered }
  7249. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  7250. Exit;
  7251. if (taicpu(hp1).opcode = A_MOVSS) and
  7252. (taicpu(hp1).ops = 0) then
  7253. { Wrong MOVSS }
  7254. Exit;
  7255. { Check for writes to specific registers first }
  7256. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  7257. for X := 0 to 7 do
  7258. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  7259. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  7260. Exit;
  7261. for X := 0 to taicpu(hp1).ops - 1 do
  7262. begin
  7263. { Check to see if this operand writes to something }
  7264. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  7265. { And matches something in the CMP/TEST instruction }
  7266. (
  7267. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  7268. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  7269. (
  7270. { If it's a register, make sure the register written to doesn't
  7271. appear in the cmp instruction as part of a reference }
  7272. (taicpu(hp1).oper[X]^.typ = top_reg) and
  7273. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  7274. )
  7275. ) then
  7276. Exit;
  7277. end;
  7278. { The instruction can be safely moved }
  7279. asml.Remove(hp1);
  7280. { Try to insert before the FLAGS register is allocated, so "mov $0,%reg"
  7281. can be optimised into "xor %reg,%reg" later }
  7282. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  7283. asml.InsertBefore(hp1, hp2)
  7284. else
  7285. { Note, if p.Previous is nil (even if it should logically never be the
  7286. case), FindRegAllocBackward immediately exits with False and so we
  7287. safely land here (we can't just pass p because FindRegAllocBackward
  7288. immediately exits on an instruction). [Kit] }
  7289. asml.InsertBefore(hp1, p);
  7290. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7291. for X := 0 to taicpu(hp1).ops - 1 do
  7292. case taicpu(hp1).oper[X]^.typ of
  7293. top_reg:
  7294. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7295. top_ref:
  7296. begin
  7297. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7298. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7299. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7300. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7301. end;
  7302. else
  7303. ;
  7304. end;
  7305. if taicpu(hp1).opcode = A_LEA then
  7306. { The flags will be overwritten by the CMP/TEST instruction }
  7307. ConvertLEA(taicpu(hp1));
  7308. Result := True;
  7309. end;
  7310. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7311. function IsXCHGAcceptable: Boolean; inline;
  7312. begin
  7313. { Always accept if optimising for size }
  7314. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7315. (
  7316. {$ifdef x86_64}
  7317. { XCHG takes 3 cycles on AMD Athlon64 }
  7318. (current_settings.optimizecputype >= cpu_core_i)
  7319. {$else x86_64}
  7320. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7321. than 3, so it becomes a saving compared to three MOVs with two of
  7322. them able to execute simultaneously. [Kit] }
  7323. (current_settings.optimizecputype >= cpu_PentiumM)
  7324. {$endif x86_64}
  7325. );
  7326. end;
  7327. var
  7328. NewRef: TReference;
  7329. hp1, hp2, hp3, hp4: Tai;
  7330. {$ifndef x86_64}
  7331. OperIdx: Integer;
  7332. {$endif x86_64}
  7333. NewInstr : Taicpu;
  7334. NewAligh : Tai_align;
  7335. DestLabel: TAsmLabel;
  7336. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7337. var
  7338. NextInstr: tai;
  7339. begin
  7340. Result := False;
  7341. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7342. if not GetNextInstruction(InputInstr, NextInstr) or
  7343. (
  7344. { The FLAGS register isn't always tracked properly, so do not
  7345. perform this optimisation if a conditional statement follows }
  7346. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7347. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7348. ) then
  7349. begin
  7350. reference_reset(NewRef, 1, []);
  7351. NewRef.base := taicpu(p).oper[0]^.reg;
  7352. NewRef.scalefactor := 1;
  7353. if taicpu(InputInstr).opcode = A_ADD then
  7354. begin
  7355. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7356. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7357. end
  7358. else
  7359. begin
  7360. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7361. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7362. end;
  7363. taicpu(p).opcode := A_LEA;
  7364. taicpu(p).loadref(0, NewRef);
  7365. RemoveInstruction(InputInstr);
  7366. Result := True;
  7367. end;
  7368. end;
  7369. begin
  7370. Result:=false;
  7371. { This optimisation adds an instruction, so only do it for speed }
  7372. if not (cs_opt_size in current_settings.optimizerswitches) and
  7373. MatchOpType(taicpu(p), top_const, top_reg) and
  7374. (taicpu(p).oper[0]^.val = 0) then
  7375. begin
  7376. { To avoid compiler warning }
  7377. DestLabel := nil;
  7378. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7379. InternalError(2021040750);
  7380. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7381. Exit;
  7382. case hp1.typ of
  7383. ait_label:
  7384. begin
  7385. { Change:
  7386. mov $0,%reg mov $0,%reg
  7387. @Lbl1: @Lbl1:
  7388. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7389. je @Lbl2 jne @Lbl2
  7390. To: To:
  7391. mov $0,%reg mov $0,%reg
  7392. jmp @Lbl2 jmp @Lbl3
  7393. (align) (align)
  7394. @Lbl1: @Lbl1:
  7395. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  7396. je @Lbl2 je @Lbl2
  7397. @Lbl3: <-- Only if label exists
  7398. (Not if it's optimised for size)
  7399. }
  7400. if not GetNextInstruction(hp1, hp2) then
  7401. Exit;
  7402. if not (cs_opt_size in current_settings.optimizerswitches) and
  7403. (hp2.typ = ait_instruction) and
  7404. (
  7405. { Register sizes must exactly match }
  7406. (
  7407. (taicpu(hp2).opcode = A_CMP) and
  7408. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  7409. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7410. ) or (
  7411. (taicpu(hp2).opcode = A_TEST) and
  7412. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7413. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7414. )
  7415. ) and GetNextInstruction(hp2, hp3) and
  7416. (hp3.typ = ait_instruction) and
  7417. (taicpu(hp3).opcode = A_JCC) and
  7418. (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
  7419. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  7420. begin
  7421. { Check condition of jump }
  7422. { Always true? }
  7423. if condition_in(C_E, taicpu(hp3).condition) then
  7424. begin
  7425. { Copy label symbol and obtain matching label entry for the
  7426. conditional jump, as this will be our destination}
  7427. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  7428. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  7429. Result := True;
  7430. end
  7431. { Always false? }
  7432. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  7433. begin
  7434. { This is only worth it if there's a jump to take }
  7435. case hp2.typ of
  7436. ait_instruction:
  7437. begin
  7438. if taicpu(hp2).opcode = A_JMP then
  7439. begin
  7440. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7441. { An unconditional jump follows the conditional jump which will always be false,
  7442. so use this jump's destination for the new jump }
  7443. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  7444. Result := True;
  7445. end
  7446. else if taicpu(hp2).opcode = A_JCC then
  7447. begin
  7448. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7449. if condition_in(C_E, taicpu(hp2).condition) then
  7450. begin
  7451. { A second conditional jump follows the conditional jump which will always be false,
  7452. while the second jump is always True, so use this jump's destination for the new jump }
  7453. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  7454. Result := True;
  7455. end;
  7456. { Don't risk it if the jump isn't always true (Result remains False) }
  7457. end;
  7458. end;
  7459. else
  7460. { If anything else don't optimise };
  7461. end;
  7462. end;
  7463. if Result then
  7464. begin
  7465. { Just so we have something to insert as a paremeter}
  7466. reference_reset(NewRef, 1, []);
  7467. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  7468. { Now actually load the correct parameter (this also
  7469. increases the reference count) }
  7470. NewInstr.loadsymbol(0, DestLabel, 0);
  7471. { Get instruction before original label (may not be p under -O3) }
  7472. if not GetLastInstruction(hp1, hp2) then
  7473. { Shouldn't fail here }
  7474. InternalError(2021040701);
  7475. AsmL.InsertAfter(NewInstr, hp2);
  7476. { Add new alignment field }
  7477. (* AsmL.InsertAfter(
  7478. cai_align.create_max(
  7479. current_settings.alignment.jumpalign,
  7480. current_settings.alignment.jumpalignskipmax
  7481. ),
  7482. NewInstr
  7483. ); *)
  7484. end;
  7485. Exit;
  7486. end;
  7487. end;
  7488. else
  7489. ;
  7490. end;
  7491. end;
  7492. if not GetNextInstruction(p, hp1) then
  7493. Exit;
  7494. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  7495. and DoMovCmpMemOpt(p, hp1, True) then
  7496. begin
  7497. Result := True;
  7498. Exit;
  7499. end
  7500. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  7501. begin
  7502. { Sometimes the MOVs that OptPass2JMP produces can be improved
  7503. further, but we can't just put this jump optimisation in pass 1
  7504. because it tends to perform worse when conditional jumps are
  7505. nearby (e.g. when converting CMOV instructions). [Kit] }
  7506. if OptPass2JMP(hp1) then
  7507. { call OptPass1MOV once to potentially merge any MOVs that were created }
  7508. Result := OptPass1MOV(p)
  7509. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  7510. returned True and the instruction is still a MOV, thus checking
  7511. the optimisations below }
  7512. { If OptPass2JMP returned False, no optimisations were done to
  7513. the jump and there are no further optimisations that can be done
  7514. to the MOV instruction on this pass }
  7515. end
  7516. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7517. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7518. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7519. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7520. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7521. begin
  7522. { Change:
  7523. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  7524. addl/q $x,%reg2 subl/q $x,%reg2
  7525. To:
  7526. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  7527. }
  7528. if (taicpu(hp1).oper[0]^.typ = top_const) and
  7529. { be lazy, checking separately for sub would be slightly better }
  7530. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  7531. begin
  7532. TransferUsedRegs(TmpUsedRegs);
  7533. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7534. if TryMovArith2Lea(hp1) then
  7535. begin
  7536. Result := True;
  7537. Exit;
  7538. end
  7539. end
  7540. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  7541. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  7542. { Same as above, but also adds or subtracts to %reg2 in between.
  7543. It's still valid as long as the flags aren't in use }
  7544. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7545. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7546. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  7547. { be lazy, checking separately for sub would be slightly better }
  7548. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  7549. begin
  7550. TransferUsedRegs(TmpUsedRegs);
  7551. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7552. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7553. if TryMovArith2Lea(hp2) then
  7554. begin
  7555. Result := True;
  7556. Exit;
  7557. end;
  7558. end;
  7559. end
  7560. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7561. {$ifdef x86_64}
  7562. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  7563. {$else x86_64}
  7564. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  7565. {$endif x86_64}
  7566. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7567. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  7568. { mov reg1, reg2 mov reg1, reg2
  7569. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  7570. begin
  7571. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7572. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  7573. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  7574. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  7575. TransferUsedRegs(TmpUsedRegs);
  7576. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7577. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  7578. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  7579. then
  7580. begin
  7581. RemoveCurrentP(p, hp1);
  7582. Result:=true;
  7583. end;
  7584. exit;
  7585. end
  7586. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7587. IsXCHGAcceptable and
  7588. { XCHG doesn't support 8-byte registers }
  7589. (taicpu(p).opsize <> S_B) and
  7590. MatchInstruction(hp1, A_MOV, []) and
  7591. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7592. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7593. GetNextInstruction(hp1, hp2) and
  7594. MatchInstruction(hp2, A_MOV, []) and
  7595. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7596. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7597. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7598. begin
  7599. { mov %reg1,%reg2
  7600. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7601. mov %reg2,%reg3
  7602. (%reg2 not used afterwards)
  7603. Note that xchg takes 3 cycles to execute, and generally mov's take
  7604. only one cycle apiece, but the first two mov's can be executed in
  7605. parallel, only taking 2 cycles overall. Older processors should
  7606. therefore only optimise for size. [Kit]
  7607. }
  7608. TransferUsedRegs(TmpUsedRegs);
  7609. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7610. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7611. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7612. begin
  7613. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7614. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7615. taicpu(hp1).opcode := A_XCHG;
  7616. RemoveCurrentP(p, hp1);
  7617. RemoveInstruction(hp2);
  7618. Result := True;
  7619. Exit;
  7620. end;
  7621. end
  7622. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7623. MatchInstruction(hp1, A_SAR, []) then
  7624. begin
  7625. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  7626. begin
  7627. { the use of %edx also covers the opsize being S_L }
  7628. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7629. begin
  7630. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7631. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7632. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7633. begin
  7634. { Change:
  7635. movl %eax,%edx
  7636. sarl $31,%edx
  7637. To:
  7638. cltd
  7639. }
  7640. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7641. RemoveInstruction(hp1);
  7642. taicpu(p).opcode := A_CDQ;
  7643. taicpu(p).opsize := S_NO;
  7644. taicpu(p).clearop(1);
  7645. taicpu(p).clearop(0);
  7646. taicpu(p).ops:=0;
  7647. Result := True;
  7648. end
  7649. else if (cs_opt_size in current_settings.optimizerswitches) and
  7650. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7651. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7652. begin
  7653. { Change:
  7654. movl %edx,%eax
  7655. sarl $31,%edx
  7656. To:
  7657. movl %edx,%eax
  7658. cltd
  7659. Note that this creates a dependency between the two instructions,
  7660. so only perform if optimising for size.
  7661. }
  7662. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7663. taicpu(hp1).opcode := A_CDQ;
  7664. taicpu(hp1).opsize := S_NO;
  7665. taicpu(hp1).clearop(1);
  7666. taicpu(hp1).clearop(0);
  7667. taicpu(hp1).ops:=0;
  7668. end;
  7669. {$ifndef x86_64}
  7670. end
  7671. { Don't bother if CMOV is supported, because a more optimal
  7672. sequence would have been generated for the Abs() intrinsic }
  7673. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7674. { the use of %eax also covers the opsize being S_L }
  7675. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7676. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7677. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7678. GetNextInstruction(hp1, hp2) and
  7679. MatchInstruction(hp2, A_XOR, [S_L]) and
  7680. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7681. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7682. GetNextInstruction(hp2, hp3) and
  7683. MatchInstruction(hp3, A_SUB, [S_L]) and
  7684. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7685. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7686. begin
  7687. { Change:
  7688. movl %eax,%edx
  7689. sarl $31,%eax
  7690. xorl %eax,%edx
  7691. subl %eax,%edx
  7692. (Instruction that uses %edx)
  7693. (%eax deallocated)
  7694. (%edx deallocated)
  7695. To:
  7696. cltd
  7697. xorl %edx,%eax <-- Note the registers have swapped
  7698. subl %edx,%eax
  7699. (Instruction that uses %eax) <-- %eax rather than %edx
  7700. }
  7701. TransferUsedRegs(TmpUsedRegs);
  7702. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7703. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7704. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7705. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7706. begin
  7707. if GetNextInstruction(hp3, hp4) and
  7708. not RegModifiedByInstruction(NR_EDX, hp4) and
  7709. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7710. begin
  7711. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7712. taicpu(p).opcode := A_CDQ;
  7713. taicpu(p).clearop(1);
  7714. taicpu(p).clearop(0);
  7715. taicpu(p).ops:=0;
  7716. RemoveInstruction(hp1);
  7717. taicpu(hp2).loadreg(0, NR_EDX);
  7718. taicpu(hp2).loadreg(1, NR_EAX);
  7719. taicpu(hp3).loadreg(0, NR_EDX);
  7720. taicpu(hp3).loadreg(1, NR_EAX);
  7721. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7722. { Convert references in the following instruction (hp4) from %edx to %eax }
  7723. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7724. with taicpu(hp4).oper[OperIdx]^ do
  7725. case typ of
  7726. top_reg:
  7727. if getsupreg(reg) = RS_EDX then
  7728. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7729. top_ref:
  7730. begin
  7731. if getsupreg(reg) = RS_EDX then
  7732. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7733. if getsupreg(reg) = RS_EDX then
  7734. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7735. end;
  7736. else
  7737. ;
  7738. end;
  7739. end;
  7740. end;
  7741. {$else x86_64}
  7742. end;
  7743. end
  7744. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7745. { the use of %rdx also covers the opsize being S_Q }
  7746. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7747. begin
  7748. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7749. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7750. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7751. begin
  7752. { Change:
  7753. movq %rax,%rdx
  7754. sarq $63,%rdx
  7755. To:
  7756. cqto
  7757. }
  7758. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7759. RemoveInstruction(hp1);
  7760. taicpu(p).opcode := A_CQO;
  7761. taicpu(p).opsize := S_NO;
  7762. taicpu(p).clearop(1);
  7763. taicpu(p).clearop(0);
  7764. taicpu(p).ops:=0;
  7765. Result := True;
  7766. end
  7767. else if (cs_opt_size in current_settings.optimizerswitches) and
  7768. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7769. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7770. begin
  7771. { Change:
  7772. movq %rdx,%rax
  7773. sarq $63,%rdx
  7774. To:
  7775. movq %rdx,%rax
  7776. cqto
  7777. Note that this creates a dependency between the two instructions,
  7778. so only perform if optimising for size.
  7779. }
  7780. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7781. taicpu(hp1).opcode := A_CQO;
  7782. taicpu(hp1).opsize := S_NO;
  7783. taicpu(hp1).clearop(1);
  7784. taicpu(hp1).clearop(0);
  7785. taicpu(hp1).ops:=0;
  7786. {$endif x86_64}
  7787. end;
  7788. end;
  7789. end
  7790. else if MatchInstruction(hp1, A_MOV, []) and
  7791. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7792. { Though "GetNextInstruction" could be factored out, along with
  7793. the instructions that depend on hp2, it is an expensive call that
  7794. should be delayed for as long as possible, hence we do cheaper
  7795. checks first that are likely to be False. [Kit] }
  7796. begin
  7797. if (
  7798. (
  7799. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7800. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7801. (
  7802. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7803. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7804. )
  7805. ) or
  7806. (
  7807. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7808. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7809. (
  7810. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7811. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7812. )
  7813. )
  7814. ) and
  7815. GetNextInstruction(hp1, hp2) and
  7816. MatchInstruction(hp2, A_SAR, []) and
  7817. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7818. begin
  7819. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7820. begin
  7821. { Change:
  7822. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7823. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7824. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7825. To:
  7826. movl r/m,%eax <- Note the change in register
  7827. cltd
  7828. }
  7829. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7830. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7831. taicpu(p).loadreg(1, NR_EAX);
  7832. taicpu(hp1).opcode := A_CDQ;
  7833. taicpu(hp1).clearop(1);
  7834. taicpu(hp1).clearop(0);
  7835. taicpu(hp1).ops:=0;
  7836. RemoveInstruction(hp2);
  7837. (*
  7838. {$ifdef x86_64}
  7839. end
  7840. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7841. { This code sequence does not get generated - however it might become useful
  7842. if and when 128-bit signed integer types make an appearance, so the code
  7843. is kept here for when it is eventually needed. [Kit] }
  7844. (
  7845. (
  7846. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7847. (
  7848. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7849. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7850. )
  7851. ) or
  7852. (
  7853. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7854. (
  7855. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7856. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7857. )
  7858. )
  7859. ) and
  7860. GetNextInstruction(hp1, hp2) and
  7861. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7862. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7863. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7864. begin
  7865. { Change:
  7866. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7867. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7868. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7869. To:
  7870. movq r/m,%rax <- Note the change in register
  7871. cqto
  7872. }
  7873. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7874. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7875. taicpu(p).loadreg(1, NR_RAX);
  7876. taicpu(hp1).opcode := A_CQO;
  7877. taicpu(hp1).clearop(1);
  7878. taicpu(hp1).clearop(0);
  7879. taicpu(hp1).ops:=0;
  7880. RemoveInstruction(hp2);
  7881. {$endif x86_64}
  7882. *)
  7883. end;
  7884. end;
  7885. {$ifdef x86_64}
  7886. end
  7887. else if (taicpu(p).opsize = S_L) and
  7888. (taicpu(p).oper[1]^.typ = top_reg) and
  7889. (
  7890. MatchInstruction(hp1, A_MOV,[]) and
  7891. (taicpu(hp1).opsize = S_L) and
  7892. (taicpu(hp1).oper[1]^.typ = top_reg)
  7893. ) and (
  7894. GetNextInstruction(hp1, hp2) and
  7895. (tai(hp2).typ=ait_instruction) and
  7896. (taicpu(hp2).opsize = S_Q) and
  7897. (
  7898. (
  7899. MatchInstruction(hp2, A_ADD,[]) and
  7900. (taicpu(hp2).opsize = S_Q) and
  7901. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7902. (
  7903. (
  7904. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7905. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7906. ) or (
  7907. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7908. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7909. )
  7910. )
  7911. ) or (
  7912. MatchInstruction(hp2, A_LEA,[]) and
  7913. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7914. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7915. (
  7916. (
  7917. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7918. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7919. ) or (
  7920. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7921. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7922. )
  7923. ) and (
  7924. (
  7925. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7926. ) or (
  7927. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7928. )
  7929. )
  7930. )
  7931. )
  7932. ) and (
  7933. GetNextInstruction(hp2, hp3) and
  7934. MatchInstruction(hp3, A_SHR,[]) and
  7935. (taicpu(hp3).opsize = S_Q) and
  7936. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7937. (taicpu(hp3).oper[0]^.val = 1) and
  7938. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7939. ) then
  7940. begin
  7941. { Change movl x, reg1d movl x, reg1d
  7942. movl y, reg2d movl y, reg2d
  7943. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7944. shrq $1, reg1q shrq $1, reg1q
  7945. ( reg1d and reg2d can be switched around in the first two instructions )
  7946. To movl x, reg1d
  7947. addl y, reg1d
  7948. rcrl $1, reg1d
  7949. This corresponds to the common expression (x + y) shr 1, where
  7950. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7951. smaller code, but won't account for x + y causing an overflow). [Kit]
  7952. }
  7953. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7954. { Change first MOV command to have the same register as the final output }
  7955. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7956. else
  7957. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7958. { Change second MOV command to an ADD command. This is easier than
  7959. converting the existing command because it means we don't have to
  7960. touch 'y', which might be a complicated reference, and also the
  7961. fact that the third command might either be ADD or LEA. [Kit] }
  7962. taicpu(hp1).opcode := A_ADD;
  7963. { Delete old ADD/LEA instruction }
  7964. RemoveInstruction(hp2);
  7965. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7966. taicpu(hp3).opcode := A_RCR;
  7967. taicpu(hp3).changeopsize(S_L);
  7968. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7969. {$endif x86_64}
  7970. end;
  7971. end;
  7972. {$push}
  7973. {$q-}{$r-}
  7974. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7975. var
  7976. ThisReg: TRegister;
  7977. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7978. TargetSubReg: TSubRegister;
  7979. hp1, hp2: tai;
  7980. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  7981. { Store list of found instructions so we don't have to call
  7982. GetNextInstructionUsingReg multiple times }
  7983. InstrList: array of taicpu;
  7984. InstrMax, Index: Integer;
  7985. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7986. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7987. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7988. WorkingValue: TCgInt;
  7989. PreMessage: string;
  7990. { Data flow analysis }
  7991. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7992. BitwiseOnly, OrXorUsed,
  7993. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7994. function CheckOverflowConditions: Boolean;
  7995. begin
  7996. Result := True;
  7997. if (TestValSignedMax > SignedUpperLimit) then
  7998. UpperSignedOverflow := True;
  7999. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  8000. LowerSignedOverflow := True;
  8001. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  8002. LowerUnsignedOverflow := True;
  8003. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  8004. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  8005. begin
  8006. { Absolute overflow }
  8007. Result := False;
  8008. Exit;
  8009. end;
  8010. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  8011. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  8012. ShiftDownOverflow := True;
  8013. if (TestValMin < 0) or (TestValMax < 0) then
  8014. begin
  8015. LowerUnsignedOverflow := True;
  8016. UpperUnsignedOverflow := True;
  8017. end;
  8018. end;
  8019. function AdjustInitialLoadAndSize: Boolean;
  8020. begin
  8021. Result := False;
  8022. if not p_removed then
  8023. begin
  8024. if TargetSize = MinSize then
  8025. begin
  8026. { Convert the input MOVZX to a MOV }
  8027. if (taicpu(p).oper[0]^.typ = top_reg) and
  8028. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8029. begin
  8030. { Or remove it completely! }
  8031. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  8032. RemoveCurrentP(p);
  8033. p_removed := True;
  8034. end
  8035. else
  8036. begin
  8037. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  8038. taicpu(p).opcode := A_MOV;
  8039. taicpu(p).oper[1]^.reg := ThisReg;
  8040. taicpu(p).opsize := TargetSize;
  8041. end;
  8042. Result := True;
  8043. end
  8044. else if TargetSize <> MaxSize then
  8045. begin
  8046. case MaxSize of
  8047. S_L:
  8048. if TargetSize = S_W then
  8049. begin
  8050. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  8051. taicpu(p).opsize := S_BW;
  8052. taicpu(p).oper[1]^.reg := ThisReg;
  8053. Result := True;
  8054. end
  8055. else
  8056. InternalError(2020112341);
  8057. S_W:
  8058. if TargetSize = S_L then
  8059. begin
  8060. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  8061. taicpu(p).opsize := S_BL;
  8062. taicpu(p).oper[1]^.reg := ThisReg;
  8063. Result := True;
  8064. end
  8065. else
  8066. InternalError(2020112342);
  8067. else
  8068. ;
  8069. end;
  8070. end
  8071. else if not hp1_removed and not RegInUse then
  8072. begin
  8073. { If we have something like:
  8074. movzbl (oper),%regd
  8075. add x, %regd
  8076. movzbl %regb, %regd
  8077. We can reduce the register size to the input of the final
  8078. movzbl instruction. Overflows won't have any effect.
  8079. }
  8080. if (taicpu(p).opsize in [S_BW, S_BL]) and
  8081. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8082. begin
  8083. TargetSize := S_B;
  8084. setsubreg(ThisReg, R_SUBL);
  8085. Result := True;
  8086. end
  8087. else if (taicpu(p).opsize = S_WL) and
  8088. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8089. begin
  8090. TargetSize := S_W;
  8091. setsubreg(ThisReg, R_SUBW);
  8092. Result := True;
  8093. end;
  8094. if Result then
  8095. begin
  8096. { Convert the input MOVZX to a MOV }
  8097. if (taicpu(p).oper[0]^.typ = top_reg) and
  8098. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8099. begin
  8100. { Or remove it completely! }
  8101. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  8102. RemoveCurrentP(p);
  8103. p_removed := True;
  8104. end
  8105. else
  8106. begin
  8107. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  8108. taicpu(p).opcode := A_MOV;
  8109. taicpu(p).oper[1]^.reg := ThisReg;
  8110. taicpu(p).opsize := TargetSize;
  8111. end;
  8112. end;
  8113. end;
  8114. end;
  8115. end;
  8116. procedure AdjustFinalLoad;
  8117. begin
  8118. if not LowerUnsignedOverflow then
  8119. begin
  8120. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  8121. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  8122. begin
  8123. { Convert the output MOVZX to a MOV }
  8124. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8125. begin
  8126. { Or remove it completely! }
  8127. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  8128. { Be careful; if p = hp1 and p was also removed, p
  8129. will become a dangling pointer }
  8130. if p = hp1 then
  8131. begin
  8132. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8133. p_removed := True;
  8134. end
  8135. else
  8136. RemoveInstruction(hp1);
  8137. hp1_removed := True;
  8138. end
  8139. else
  8140. begin
  8141. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  8142. taicpu(hp1).opcode := A_MOV;
  8143. taicpu(hp1).oper[0]^.reg := ThisReg;
  8144. taicpu(hp1).opsize := TargetSize;
  8145. end;
  8146. end
  8147. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  8148. begin
  8149. { Need to change the size of the output }
  8150. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  8151. taicpu(hp1).oper[0]^.reg := ThisReg;
  8152. taicpu(hp1).opsize := S_BL;
  8153. end;
  8154. end;
  8155. end;
  8156. function CompressInstructions: Boolean;
  8157. var
  8158. LocalIndex: Integer;
  8159. begin
  8160. Result := False;
  8161. { The objective here is to try to find a combination that
  8162. removes one of the MOV/Z instructions. }
  8163. if (
  8164. (taicpu(p).oper[0]^.typ <> top_reg) or
  8165. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  8166. ) and
  8167. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8168. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8169. begin
  8170. { Make a preference to remove the second MOVZX instruction }
  8171. case taicpu(hp1).opsize of
  8172. S_BL, S_WL:
  8173. begin
  8174. TargetSize := S_L;
  8175. TargetSubReg := R_SUBD;
  8176. end;
  8177. S_BW:
  8178. begin
  8179. TargetSize := S_W;
  8180. TargetSubReg := R_SUBW;
  8181. end;
  8182. else
  8183. InternalError(2020112302);
  8184. end;
  8185. end
  8186. else
  8187. begin
  8188. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8189. begin
  8190. { Exceeded lower bound but not upper bound }
  8191. TargetSize := MaxSize;
  8192. end
  8193. else if not LowerUnsignedOverflow then
  8194. begin
  8195. { Size didn't exceed lower bound }
  8196. TargetSize := MinSize;
  8197. end
  8198. else
  8199. Exit;
  8200. end;
  8201. case TargetSize of
  8202. S_B:
  8203. TargetSubReg := R_SUBL;
  8204. S_W:
  8205. TargetSubReg := R_SUBW;
  8206. S_L:
  8207. TargetSubReg := R_SUBD;
  8208. else
  8209. InternalError(2020112350);
  8210. end;
  8211. { Update the register to its new size }
  8212. setsubreg(ThisReg, TargetSubReg);
  8213. RegInUse := False;
  8214. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8215. begin
  8216. { Check to see if the active register is used afterwards;
  8217. if not, we can change it and make a saving. }
  8218. TransferUsedRegs(TmpUsedRegs);
  8219. { The target register may be marked as in use to cross
  8220. a jump to a distant label, so exclude it }
  8221. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  8222. hp2 := p;
  8223. repeat
  8224. { Explicitly check for the excluded register (don't include the first
  8225. instruction as it may be reading from here }
  8226. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  8227. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  8228. begin
  8229. RegInUse := True;
  8230. Break;
  8231. end;
  8232. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  8233. if not GetNextInstruction(hp2, hp2) then
  8234. InternalError(2020112340);
  8235. until (hp2 = hp1);
  8236. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8237. { We might still be able to get away with this }
  8238. RegInUse := not
  8239. (
  8240. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  8241. (hp2.typ = ait_instruction) and
  8242. (
  8243. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8244. instruction that doesn't actually contain ThisReg }
  8245. (cs_opt_level3 in current_settings.optimizerswitches) or
  8246. RegInInstruction(ThisReg, hp2)
  8247. ) and
  8248. RegLoadedWithNewValue(ThisReg, hp2)
  8249. );
  8250. if not RegInUse then
  8251. begin
  8252. { Force the register size to the same as this instruction so it can be removed}
  8253. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  8254. begin
  8255. TargetSize := S_L;
  8256. TargetSubReg := R_SUBD;
  8257. end
  8258. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  8259. begin
  8260. TargetSize := S_W;
  8261. TargetSubReg := R_SUBW;
  8262. end;
  8263. ThisReg := taicpu(hp1).oper[1]^.reg;
  8264. setsubreg(ThisReg, TargetSubReg);
  8265. RegChanged := True;
  8266. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  8267. TransferUsedRegs(TmpUsedRegs);
  8268. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  8269. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  8270. if p = hp1 then
  8271. begin
  8272. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8273. p_removed := True;
  8274. end
  8275. else
  8276. RemoveInstruction(hp1);
  8277. hp1_removed := True;
  8278. { Instruction will become "mov %reg,%reg" }
  8279. if not p_removed and (taicpu(p).opcode = A_MOV) and
  8280. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  8281. begin
  8282. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  8283. RemoveCurrentP(p);
  8284. p_removed := True;
  8285. end
  8286. else
  8287. taicpu(p).oper[1]^.reg := ThisReg;
  8288. Result := True;
  8289. end
  8290. else
  8291. begin
  8292. if TargetSize <> MaxSize then
  8293. begin
  8294. { Since the register is in use, we have to force it to
  8295. MaxSize otherwise part of it may become undefined later on }
  8296. TargetSize := MaxSize;
  8297. case TargetSize of
  8298. S_B:
  8299. TargetSubReg := R_SUBL;
  8300. S_W:
  8301. TargetSubReg := R_SUBW;
  8302. S_L:
  8303. TargetSubReg := R_SUBD;
  8304. else
  8305. InternalError(2020112351);
  8306. end;
  8307. setsubreg(ThisReg, TargetSubReg);
  8308. end;
  8309. AdjustFinalLoad;
  8310. end;
  8311. end
  8312. else
  8313. AdjustFinalLoad;
  8314. Result := AdjustInitialLoadAndSize or Result;
  8315. { Now go through every instruction we found and change the
  8316. size. If TargetSize = MaxSize, then almost no changes are
  8317. needed and Result can remain False if it hasn't been set
  8318. yet.
  8319. If RegChanged is True, then the register requires changing
  8320. and so the point about TargetSize = MaxSize doesn't apply. }
  8321. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  8322. begin
  8323. for LocalIndex := 0 to InstrMax do
  8324. begin
  8325. { If p_removed is true, then the original MOV/Z was removed
  8326. and removing the AND instruction may not be safe if it
  8327. appears first }
  8328. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  8329. InternalError(2020112310);
  8330. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  8331. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  8332. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  8333. InstrList[LocalIndex].opsize := TargetSize;
  8334. end;
  8335. Result := True;
  8336. end;
  8337. end;
  8338. begin
  8339. Result := False;
  8340. p_removed := False;
  8341. hp1_removed := False;
  8342. ThisReg := taicpu(p).oper[1]^.reg;
  8343. { Check for:
  8344. movs/z ###,%ecx (or %cx or %rcx)
  8345. ...
  8346. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8347. (dealloc %ecx)
  8348. Change to:
  8349. mov ###,%cl (if ### = %cl, then remove completely)
  8350. ...
  8351. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8352. }
  8353. if (getsupreg(ThisReg) = RS_ECX) and
  8354. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8355. (hp1.typ = ait_instruction) and
  8356. (
  8357. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8358. instruction that doesn't actually contain ECX }
  8359. (cs_opt_level3 in current_settings.optimizerswitches) or
  8360. RegInInstruction(NR_ECX, hp1) or
  8361. (
  8362. { It's common for the shift/rotate's read/write register to be
  8363. initialised in between, so under -O2 and under, search ahead
  8364. one more instruction
  8365. }
  8366. GetNextInstruction(hp1, hp1) and
  8367. (hp1.typ = ait_instruction) and
  8368. RegInInstruction(NR_ECX, hp1)
  8369. )
  8370. ) and
  8371. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8372. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8373. begin
  8374. TransferUsedRegs(TmpUsedRegs);
  8375. hp2 := p;
  8376. repeat
  8377. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8378. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8379. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8380. begin
  8381. case taicpu(p).opsize of
  8382. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8383. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  8384. begin
  8385. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  8386. RemoveCurrentP(p);
  8387. end
  8388. else
  8389. begin
  8390. taicpu(p).opcode := A_MOV;
  8391. taicpu(p).opsize := S_B;
  8392. taicpu(p).oper[1]^.reg := NR_CL;
  8393. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  8394. end;
  8395. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8396. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  8397. begin
  8398. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  8399. RemoveCurrentP(p);
  8400. end
  8401. else
  8402. begin
  8403. taicpu(p).opcode := A_MOV;
  8404. taicpu(p).opsize := S_W;
  8405. taicpu(p).oper[1]^.reg := NR_CX;
  8406. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  8407. end;
  8408. {$ifdef x86_64}
  8409. S_LQ:
  8410. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  8411. begin
  8412. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  8413. RemoveCurrentP(p);
  8414. end
  8415. else
  8416. begin
  8417. taicpu(p).opcode := A_MOV;
  8418. taicpu(p).opsize := S_L;
  8419. taicpu(p).oper[1]^.reg := NR_ECX;
  8420. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  8421. end;
  8422. {$endif x86_64}
  8423. else
  8424. InternalError(2021120401);
  8425. end;
  8426. Result := True;
  8427. Exit;
  8428. end;
  8429. end;
  8430. { This is anything but quick! }
  8431. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  8432. Exit;
  8433. SetLength(InstrList, 0);
  8434. InstrMax := -1;
  8435. case taicpu(p).opsize of
  8436. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8437. begin
  8438. {$if defined(i386) or defined(i8086)}
  8439. { If the target size is 8-bit, make sure we can actually encode it }
  8440. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  8441. Exit;
  8442. {$endif i386 or i8086}
  8443. LowerLimit := $FF;
  8444. SignedLowerLimit := $7F;
  8445. SignedLowerLimitBottom := -128;
  8446. MinSize := S_B;
  8447. if taicpu(p).opsize = S_BW then
  8448. begin
  8449. MaxSize := S_W;
  8450. UpperLimit := $FFFF;
  8451. SignedUpperLimit := $7FFF;
  8452. SignedUpperLimitBottom := -32768;
  8453. end
  8454. else
  8455. begin
  8456. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  8457. MaxSize := S_L;
  8458. UpperLimit := $FFFFFFFF;
  8459. SignedUpperLimit := $7FFFFFFF;
  8460. SignedUpperLimitBottom := -2147483648;
  8461. end;
  8462. end;
  8463. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8464. begin
  8465. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  8466. LowerLimit := $FFFF;
  8467. SignedLowerLimit := $7FFF;
  8468. SignedLowerLimitBottom := -32768;
  8469. UpperLimit := $FFFFFFFF;
  8470. SignedUpperLimit := $7FFFFFFF;
  8471. SignedUpperLimitBottom := -2147483648;
  8472. MinSize := S_W;
  8473. MaxSize := S_L;
  8474. end;
  8475. {$ifdef x86_64}
  8476. S_LQ:
  8477. begin
  8478. { Both the lower and upper limits are set to 32-bit. If a limit
  8479. is breached, then optimisation is impossible }
  8480. LowerLimit := $FFFFFFFF;
  8481. SignedLowerLimit := $7FFFFFFF;
  8482. SignedLowerLimitBottom := -2147483648;
  8483. UpperLimit := $FFFFFFFF;
  8484. SignedUpperLimit := $7FFFFFFF;
  8485. SignedUpperLimitBottom := -2147483648;
  8486. MinSize := S_L;
  8487. MaxSize := S_L;
  8488. end;
  8489. {$endif x86_64}
  8490. else
  8491. InternalError(2020112301);
  8492. end;
  8493. TestValMin := 0;
  8494. TestValMax := LowerLimit;
  8495. TestValSignedMax := SignedLowerLimit;
  8496. TryShiftDownLimit := LowerLimit;
  8497. TryShiftDown := S_NO;
  8498. ShiftDownOverflow := False;
  8499. RegChanged := False;
  8500. BitwiseOnly := True;
  8501. OrXorUsed := False;
  8502. UpperSignedOverflow := False;
  8503. LowerSignedOverflow := False;
  8504. UpperUnsignedOverflow := False;
  8505. LowerUnsignedOverflow := False;
  8506. hp1 := p;
  8507. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  8508. (hp1.typ = ait_instruction) and
  8509. (
  8510. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8511. instruction that doesn't actually contain ThisReg }
  8512. (cs_opt_level3 in current_settings.optimizerswitches) or
  8513. { This allows this Movx optimisation to work through the SETcc instructions
  8514. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8515. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8516. skip over these SETcc instructions). }
  8517. (taicpu(hp1).opcode = A_SETcc) or
  8518. RegInInstruction(ThisReg, hp1)
  8519. ) do
  8520. begin
  8521. case taicpu(hp1).opcode of
  8522. A_INC,A_DEC:
  8523. begin
  8524. { Has to be an exact match on the register }
  8525. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  8526. Break;
  8527. if taicpu(hp1).opcode = A_INC then
  8528. begin
  8529. Inc(TestValMin);
  8530. Inc(TestValMax);
  8531. Inc(TestValSignedMax);
  8532. end
  8533. else
  8534. begin
  8535. Dec(TestValMin);
  8536. Dec(TestValMax);
  8537. Dec(TestValSignedMax);
  8538. end;
  8539. end;
  8540. A_TEST, A_CMP:
  8541. begin
  8542. if (
  8543. { Too high a risk of non-linear behaviour that breaks DFA
  8544. here, unless it's cmp $0,%reg, which is equivalent to
  8545. test %reg,%reg }
  8546. OrXorUsed and
  8547. (taicpu(hp1).opcode = A_CMP) and
  8548. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  8549. ) or
  8550. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8551. { Has to be an exact match on the register }
  8552. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8553. (
  8554. { Permit "test %reg,%reg" }
  8555. (taicpu(hp1).opcode = A_TEST) and
  8556. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8557. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  8558. ) or
  8559. (taicpu(hp1).oper[0]^.typ <> top_const) or
  8560. { Make sure the comparison value is not smaller than the
  8561. smallest allowed signed value for the minimum size (e.g.
  8562. -128 for 8-bit) }
  8563. not (
  8564. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  8565. { Is it in the negative range? }
  8566. (
  8567. (taicpu(hp1).oper[0]^.val < 0) and
  8568. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  8569. )
  8570. ) then
  8571. Break;
  8572. { Check to see if the active register is used afterwards }
  8573. TransferUsedRegs(TmpUsedRegs);
  8574. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  8575. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8576. begin
  8577. { Make sure the comparison or any previous instructions
  8578. hasn't pushed the test values outside of the range of
  8579. MinSize }
  8580. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8581. begin
  8582. { Exceeded lower bound but not upper bound }
  8583. Exit;
  8584. end
  8585. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  8586. begin
  8587. { Size didn't exceed lower bound }
  8588. TargetSize := MinSize;
  8589. end
  8590. else
  8591. Break;
  8592. case TargetSize of
  8593. S_B:
  8594. TargetSubReg := R_SUBL;
  8595. S_W:
  8596. TargetSubReg := R_SUBW;
  8597. S_L:
  8598. TargetSubReg := R_SUBD;
  8599. else
  8600. InternalError(2021051002);
  8601. end;
  8602. if TargetSize <> MaxSize then
  8603. begin
  8604. { Update the register to its new size }
  8605. setsubreg(ThisReg, TargetSubReg);
  8606. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  8607. taicpu(hp1).oper[1]^.reg := ThisReg;
  8608. taicpu(hp1).opsize := TargetSize;
  8609. { Convert the input MOVZX to a MOV if necessary }
  8610. AdjustInitialLoadAndSize;
  8611. if (InstrMax >= 0) then
  8612. begin
  8613. for Index := 0 to InstrMax do
  8614. begin
  8615. { If p_removed is true, then the original MOV/Z was removed
  8616. and removing the AND instruction may not be safe if it
  8617. appears first }
  8618. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  8619. InternalError(2020112311);
  8620. if InstrList[Index].oper[0]^.typ = top_reg then
  8621. InstrList[Index].oper[0]^.reg := ThisReg;
  8622. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8623. InstrList[Index].opsize := MinSize;
  8624. end;
  8625. end;
  8626. Result := True;
  8627. end;
  8628. Exit;
  8629. end;
  8630. end;
  8631. A_SETcc:
  8632. begin
  8633. { This allows this Movx optimisation to work through the SETcc instructions
  8634. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8635. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8636. skip over these SETcc instructions). }
  8637. if (cs_opt_level3 in current_settings.optimizerswitches) or
  8638. { Of course, break out if the current register is used }
  8639. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  8640. Break
  8641. else
  8642. { We must use Continue so the instruction doesn't get added
  8643. to InstrList }
  8644. Continue;
  8645. end;
  8646. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  8647. begin
  8648. if
  8649. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8650. { Has to be an exact match on the register }
  8651. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  8652. (
  8653. (
  8654. (taicpu(hp1).oper[0]^.typ = top_const) and
  8655. (
  8656. (
  8657. (taicpu(hp1).opcode = A_SHL) and
  8658. (
  8659. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  8660. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  8661. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  8662. )
  8663. ) or (
  8664. (taicpu(hp1).opcode <> A_SHL) and
  8665. (
  8666. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8667. { Is it in the negative range? }
  8668. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  8669. )
  8670. )
  8671. )
  8672. ) or (
  8673. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  8674. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  8675. )
  8676. ) then
  8677. Break;
  8678. { Only process OR and XOR if there are only bitwise operations,
  8679. since otherwise they can too easily fool the data flow
  8680. analysis (they can cause non-linear behaviour) }
  8681. case taicpu(hp1).opcode of
  8682. A_ADD:
  8683. begin
  8684. if OrXorUsed then
  8685. { Too high a risk of non-linear behaviour that breaks DFA here }
  8686. Break
  8687. else
  8688. BitwiseOnly := False;
  8689. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8690. begin
  8691. TestValMin := TestValMin * 2;
  8692. TestValMax := TestValMax * 2;
  8693. TestValSignedMax := TestValSignedMax * 2;
  8694. end
  8695. else
  8696. begin
  8697. WorkingValue := taicpu(hp1).oper[0]^.val;
  8698. TestValMin := TestValMin + WorkingValue;
  8699. TestValMax := TestValMax + WorkingValue;
  8700. TestValSignedMax := TestValSignedMax + WorkingValue;
  8701. end;
  8702. end;
  8703. A_SUB:
  8704. begin
  8705. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8706. begin
  8707. TestValMin := 0;
  8708. TestValMax := 0;
  8709. TestValSignedMax := 0;
  8710. end
  8711. else
  8712. begin
  8713. if OrXorUsed then
  8714. { Too high a risk of non-linear behaviour that breaks DFA here }
  8715. Break
  8716. else
  8717. BitwiseOnly := False;
  8718. WorkingValue := taicpu(hp1).oper[0]^.val;
  8719. TestValMin := TestValMin - WorkingValue;
  8720. TestValMax := TestValMax - WorkingValue;
  8721. TestValSignedMax := TestValSignedMax - WorkingValue;
  8722. end;
  8723. end;
  8724. A_AND:
  8725. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8726. begin
  8727. { we might be able to go smaller if AND appears first }
  8728. if InstrMax = -1 then
  8729. case MinSize of
  8730. S_B:
  8731. ;
  8732. S_W:
  8733. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8734. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8735. begin
  8736. TryShiftDown := S_B;
  8737. TryShiftDownLimit := $FF;
  8738. end;
  8739. S_L:
  8740. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8741. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8742. begin
  8743. TryShiftDown := S_B;
  8744. TryShiftDownLimit := $FF;
  8745. end
  8746. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8747. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8748. begin
  8749. TryShiftDown := S_W;
  8750. TryShiftDownLimit := $FFFF;
  8751. end;
  8752. else
  8753. InternalError(2020112320);
  8754. end;
  8755. WorkingValue := taicpu(hp1).oper[0]^.val;
  8756. TestValMin := TestValMin and WorkingValue;
  8757. TestValMax := TestValMax and WorkingValue;
  8758. TestValSignedMax := TestValSignedMax and WorkingValue;
  8759. end;
  8760. A_OR:
  8761. begin
  8762. if not BitwiseOnly then
  8763. Break;
  8764. OrXorUsed := True;
  8765. WorkingValue := taicpu(hp1).oper[0]^.val;
  8766. TestValMin := TestValMin or WorkingValue;
  8767. TestValMax := TestValMax or WorkingValue;
  8768. TestValSignedMax := TestValSignedMax or WorkingValue;
  8769. end;
  8770. A_XOR:
  8771. begin
  8772. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8773. begin
  8774. TestValMin := 0;
  8775. TestValMax := 0;
  8776. TestValSignedMax := 0;
  8777. end
  8778. else
  8779. begin
  8780. if not BitwiseOnly then
  8781. Break;
  8782. OrXorUsed := True;
  8783. WorkingValue := taicpu(hp1).oper[0]^.val;
  8784. TestValMin := TestValMin xor WorkingValue;
  8785. TestValMax := TestValMax xor WorkingValue;
  8786. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8787. end;
  8788. end;
  8789. A_SHL:
  8790. begin
  8791. BitwiseOnly := False;
  8792. WorkingValue := taicpu(hp1).oper[0]^.val;
  8793. TestValMin := TestValMin shl WorkingValue;
  8794. TestValMax := TestValMax shl WorkingValue;
  8795. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8796. end;
  8797. A_SHR,
  8798. { The first instruction was MOVZX, so the value won't be negative }
  8799. A_SAR:
  8800. begin
  8801. if InstrMax <> -1 then
  8802. BitwiseOnly := False
  8803. else
  8804. { we might be able to go smaller if SHR appears first }
  8805. case MinSize of
  8806. S_B:
  8807. ;
  8808. S_W:
  8809. if (taicpu(hp1).oper[0]^.val >= 8) then
  8810. begin
  8811. TryShiftDown := S_B;
  8812. TryShiftDownLimit := $FF;
  8813. TryShiftDownSignedLimit := $7F;
  8814. TryShiftDownSignedLimitLower := -128;
  8815. end;
  8816. S_L:
  8817. if (taicpu(hp1).oper[0]^.val >= 24) then
  8818. begin
  8819. TryShiftDown := S_B;
  8820. TryShiftDownLimit := $FF;
  8821. TryShiftDownSignedLimit := $7F;
  8822. TryShiftDownSignedLimitLower := -128;
  8823. end
  8824. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8825. begin
  8826. TryShiftDown := S_W;
  8827. TryShiftDownLimit := $FFFF;
  8828. TryShiftDownSignedLimit := $7FFF;
  8829. TryShiftDownSignedLimitLower := -32768;
  8830. end;
  8831. else
  8832. InternalError(2020112321);
  8833. end;
  8834. WorkingValue := taicpu(hp1).oper[0]^.val;
  8835. if taicpu(hp1).opcode = A_SAR then
  8836. begin
  8837. TestValMin := SarInt64(TestValMin, WorkingValue);
  8838. TestValMax := SarInt64(TestValMax, WorkingValue);
  8839. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8840. end
  8841. else
  8842. begin
  8843. TestValMin := TestValMin shr WorkingValue;
  8844. TestValMax := TestValMax shr WorkingValue;
  8845. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8846. end;
  8847. end;
  8848. else
  8849. InternalError(2020112303);
  8850. end;
  8851. end;
  8852. (*
  8853. A_IMUL:
  8854. case taicpu(hp1).ops of
  8855. 2:
  8856. begin
  8857. if not MatchOpType(hp1, top_reg, top_reg) or
  8858. { Has to be an exact match on the register }
  8859. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8860. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8861. Break;
  8862. TestValMin := TestValMin * TestValMin;
  8863. TestValMax := TestValMax * TestValMax;
  8864. TestValSignedMax := TestValSignedMax * TestValMax;
  8865. end;
  8866. 3:
  8867. begin
  8868. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8869. { Has to be an exact match on the register }
  8870. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8871. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8872. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8873. { Is it in the negative range? }
  8874. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8875. Break;
  8876. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8877. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8878. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8879. end;
  8880. else
  8881. Break;
  8882. end;
  8883. A_IDIV:
  8884. case taicpu(hp1).ops of
  8885. 3:
  8886. begin
  8887. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8888. { Has to be an exact match on the register }
  8889. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8890. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8891. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8892. { Is it in the negative range? }
  8893. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8894. Break;
  8895. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  8896. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  8897. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  8898. end;
  8899. else
  8900. Break;
  8901. end;
  8902. *)
  8903. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8904. begin
  8905. { If there are no instructions in between, then we might be able to make a saving }
  8906. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  8907. Break;
  8908. { We have something like:
  8909. movzbw %dl,%dx
  8910. ...
  8911. movswl %dx,%edx
  8912. Change the latter to a zero-extension then enter the
  8913. A_MOVZX case branch.
  8914. }
  8915. {$ifdef x86_64}
  8916. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8917. begin
  8918. { this becomes a zero extension from 32-bit to 64-bit, but
  8919. the upper 32 bits are already zero, so just delete the
  8920. instruction }
  8921. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  8922. RemoveInstruction(hp1);
  8923. Result := True;
  8924. Exit;
  8925. end
  8926. else
  8927. {$endif x86_64}
  8928. begin
  8929. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  8930. taicpu(hp1).opcode := A_MOVZX;
  8931. {$ifdef x86_64}
  8932. case taicpu(hp1).opsize of
  8933. S_BQ:
  8934. begin
  8935. taicpu(hp1).opsize := S_BL;
  8936. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8937. end;
  8938. S_WQ:
  8939. begin
  8940. taicpu(hp1).opsize := S_WL;
  8941. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8942. end;
  8943. S_LQ:
  8944. begin
  8945. taicpu(hp1).opcode := A_MOV;
  8946. taicpu(hp1).opsize := S_L;
  8947. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8948. { In this instance, we need to break out because the
  8949. instruction is no longer MOVZX or MOVSXD }
  8950. Result := True;
  8951. Exit;
  8952. end;
  8953. else
  8954. ;
  8955. end;
  8956. {$endif x86_64}
  8957. Result := CompressInstructions;
  8958. Exit;
  8959. end;
  8960. end;
  8961. A_MOVZX:
  8962. begin
  8963. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  8964. Break;
  8965. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  8966. begin
  8967. if (InstrMax = -1) and
  8968. { Will return false if the second parameter isn't ThisReg
  8969. (can happen on -O2 and under) }
  8970. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8971. begin
  8972. { The two MOVZX instructions are adjacent, so remove the first one }
  8973. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  8974. RemoveCurrentP(p);
  8975. Result := True;
  8976. Exit;
  8977. end;
  8978. Break;
  8979. end;
  8980. Result := CompressInstructions;
  8981. Exit;
  8982. end;
  8983. else
  8984. { This includes ADC, SBB and IDIV }
  8985. Break;
  8986. end;
  8987. if not CheckOverflowConditions then
  8988. Break;
  8989. { Contains highest index (so instruction count - 1) }
  8990. Inc(InstrMax);
  8991. if InstrMax > High(InstrList) then
  8992. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8993. InstrList[InstrMax] := taicpu(hp1);
  8994. end;
  8995. end;
  8996. {$pop}
  8997. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  8998. var
  8999. hp1 : tai;
  9000. begin
  9001. Result:=false;
  9002. if (taicpu(p).ops >= 2) and
  9003. ((taicpu(p).oper[0]^.typ = top_const) or
  9004. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  9005. (taicpu(p).oper[1]^.typ = top_reg) and
  9006. ((taicpu(p).ops = 2) or
  9007. ((taicpu(p).oper[2]^.typ = top_reg) and
  9008. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  9009. GetLastInstruction(p,hp1) and
  9010. MatchInstruction(hp1,A_MOV,[]) and
  9011. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9012. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9013. begin
  9014. TransferUsedRegs(TmpUsedRegs);
  9015. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  9016. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  9017. { change
  9018. mov reg1,reg2
  9019. imul y,reg2 to imul y,reg1,reg2 }
  9020. begin
  9021. taicpu(p).ops := 3;
  9022. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  9023. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  9024. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  9025. RemoveInstruction(hp1);
  9026. result:=true;
  9027. end;
  9028. end;
  9029. end;
  9030. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  9031. var
  9032. ThisLabel: TAsmLabel;
  9033. begin
  9034. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  9035. ThisLabel.decrefs;
  9036. taicpu(p).opcode := A_RET;
  9037. taicpu(p).is_jmp := false;
  9038. taicpu(p).ops := taicpu(ret_p).ops;
  9039. case taicpu(ret_p).ops of
  9040. 0:
  9041. taicpu(p).clearop(0);
  9042. 1:
  9043. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  9044. else
  9045. internalerror(2016041301);
  9046. end;
  9047. { If the original label is now dead, it might turn out that the label
  9048. immediately follows p. As a result, everything beyond it, which will
  9049. be just some final register configuration and a RET instruction, is
  9050. now dead code. [Kit] }
  9051. { NOTE: This is much faster than introducing a OptPass2RET routine and
  9052. running RemoveDeadCodeAfterJump for each RET instruction, because
  9053. this optimisation rarely happens and most RETs appear at the end of
  9054. routines where there is nothing that can be stripped. [Kit] }
  9055. if not ThisLabel.is_used then
  9056. RemoveDeadCodeAfterJump(p);
  9057. end;
  9058. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  9059. var
  9060. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  9061. Unconditional, PotentialModified: Boolean;
  9062. OperPtr: POper;
  9063. NewRef: TReference;
  9064. InstrList: array of taicpu;
  9065. InstrMax, Index: Integer;
  9066. const
  9067. {$ifdef DEBUG_AOPTCPU}
  9068. SNoFlags: shortstring = ' so the flags aren''t modified';
  9069. {$else DEBUG_AOPTCPU}
  9070. SNoFlags = '';
  9071. {$endif DEBUG_AOPTCPU}
  9072. begin
  9073. Result:=false;
  9074. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  9075. begin
  9076. if MatchInstruction(hp1, A_TEST, [S_B]) and
  9077. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9078. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9079. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9080. GetNextInstruction(hp1, hp2) and
  9081. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  9082. { Change from: To:
  9083. set(C) %reg j(~C) label
  9084. test %reg,%reg/cmp $0,%reg
  9085. je label
  9086. set(C) %reg j(C) label
  9087. test %reg,%reg/cmp $0,%reg
  9088. jne label
  9089. (Also do something similar with sete/setne instead of je/jne)
  9090. }
  9091. begin
  9092. { Before we do anything else, we need to check the instructions
  9093. in between SETcc and TEST to make sure they don't modify the
  9094. FLAGS register - if -O2 or under, there won't be any
  9095. instructions between SET and TEST }
  9096. TransferUsedRegs(TmpUsedRegs);
  9097. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9098. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9099. begin
  9100. next := p;
  9101. SetLength(InstrList, 0);
  9102. InstrMax := -1;
  9103. PotentialModified := False;
  9104. { Make a note of every instruction that modifies the FLAGS
  9105. register }
  9106. while GetNextInstruction(next, next) and (next <> hp1) do
  9107. begin
  9108. if next.typ <> ait_instruction then
  9109. { GetNextInstructionUsingReg should have returned False }
  9110. InternalError(2021051701);
  9111. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  9112. begin
  9113. case taicpu(next).opcode of
  9114. A_SETcc,
  9115. A_CMOVcc,
  9116. A_Jcc:
  9117. begin
  9118. if PotentialModified then
  9119. { Not safe because the flags were modified earlier }
  9120. Exit
  9121. else
  9122. { Condition is the same as the initial SETcc, so this is safe
  9123. (don't add to instruction list though) }
  9124. Continue;
  9125. end;
  9126. A_ADD:
  9127. begin
  9128. if (taicpu(next).opsize = S_B) or
  9129. { LEA doesn't support 8-bit operands }
  9130. (taicpu(next).oper[1]^.typ <> top_reg) or
  9131. { Must write to a register }
  9132. (taicpu(next).oper[0]^.typ = top_ref) then
  9133. { Require a constant or a register }
  9134. Exit;
  9135. PotentialModified := True;
  9136. end;
  9137. A_SUB:
  9138. begin
  9139. if (taicpu(next).opsize = S_B) or
  9140. { LEA doesn't support 8-bit operands }
  9141. (taicpu(next).oper[1]^.typ <> top_reg) or
  9142. { Must write to a register }
  9143. (taicpu(next).oper[0]^.typ <> top_const) or
  9144. (taicpu(next).oper[0]^.val = $80000000) then
  9145. { Can't subtract a register with LEA - also
  9146. check that the value isn't -2^31, as this
  9147. can't be negated }
  9148. Exit;
  9149. PotentialModified := True;
  9150. end;
  9151. A_SAL,
  9152. A_SHL:
  9153. begin
  9154. if (taicpu(next).opsize = S_B) or
  9155. { LEA doesn't support 8-bit operands }
  9156. (taicpu(next).oper[1]^.typ <> top_reg) or
  9157. { Must write to a register }
  9158. (taicpu(next).oper[0]^.typ <> top_const) or
  9159. (taicpu(next).oper[0]^.val < 0) or
  9160. (taicpu(next).oper[0]^.val > 3) then
  9161. Exit;
  9162. PotentialModified := True;
  9163. end;
  9164. A_IMUL:
  9165. begin
  9166. if (taicpu(next).ops <> 3) or
  9167. (taicpu(next).oper[1]^.typ <> top_reg) or
  9168. { Must write to a register }
  9169. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  9170. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  9171. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  9172. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  9173. Exit
  9174. else
  9175. PotentialModified := True;
  9176. end;
  9177. else
  9178. { Don't know how to change this, so abort }
  9179. Exit;
  9180. end;
  9181. { Contains highest index (so instruction count - 1) }
  9182. Inc(InstrMax);
  9183. if InstrMax > High(InstrList) then
  9184. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9185. InstrList[InstrMax] := taicpu(next);
  9186. end;
  9187. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  9188. end;
  9189. if not Assigned(next) or (next <> hp1) then
  9190. { It should be equal to hp1 }
  9191. InternalError(2021051702);
  9192. { Cycle through each instruction and check to see if we can
  9193. change them to versions that don't modify the flags }
  9194. if (InstrMax >= 0) then
  9195. begin
  9196. for Index := 0 to InstrMax do
  9197. case InstrList[Index].opcode of
  9198. A_ADD:
  9199. begin
  9200. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  9201. InstrList[Index].opcode := A_LEA;
  9202. reference_reset(NewRef, 1, []);
  9203. NewRef.base := InstrList[Index].oper[1]^.reg;
  9204. if InstrList[Index].oper[0]^.typ = top_reg then
  9205. begin
  9206. NewRef.index := InstrList[Index].oper[0]^.reg;
  9207. NewRef.scalefactor := 1;
  9208. end
  9209. else
  9210. NewRef.offset := InstrList[Index].oper[0]^.val;
  9211. InstrList[Index].loadref(0, NewRef);
  9212. end;
  9213. A_SUB:
  9214. begin
  9215. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  9216. InstrList[Index].opcode := A_LEA;
  9217. reference_reset(NewRef, 1, []);
  9218. NewRef.base := InstrList[Index].oper[1]^.reg;
  9219. NewRef.offset := -InstrList[Index].oper[0]^.val;
  9220. InstrList[Index].loadref(0, NewRef);
  9221. end;
  9222. A_SHL,
  9223. A_SAL:
  9224. begin
  9225. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  9226. InstrList[Index].opcode := A_LEA;
  9227. reference_reset(NewRef, 1, []);
  9228. NewRef.index := InstrList[Index].oper[1]^.reg;
  9229. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  9230. InstrList[Index].loadref(0, NewRef);
  9231. end;
  9232. A_IMUL:
  9233. begin
  9234. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  9235. InstrList[Index].opcode := A_LEA;
  9236. reference_reset(NewRef, 1, []);
  9237. NewRef.index := InstrList[Index].oper[1]^.reg;
  9238. case InstrList[Index].oper[0]^.val of
  9239. 2, 4, 8:
  9240. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  9241. else {3, 5 and 9}
  9242. begin
  9243. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  9244. NewRef.base := InstrList[Index].oper[1]^.reg;
  9245. end;
  9246. end;
  9247. InstrList[Index].loadref(0, NewRef);
  9248. end;
  9249. else
  9250. InternalError(2021051710);
  9251. end;
  9252. end;
  9253. { Mark the FLAGS register as used across this whole block }
  9254. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  9255. end;
  9256. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9257. JumpC := taicpu(hp2).condition;
  9258. Unconditional := False;
  9259. if conditions_equal(JumpC, C_E) then
  9260. SetC := inverse_cond(taicpu(p).condition)
  9261. else if conditions_equal(JumpC, C_NE) then
  9262. SetC := taicpu(p).condition
  9263. else
  9264. { We've got something weird here (and inefficent) }
  9265. begin
  9266. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  9267. SetC := C_NONE;
  9268. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  9269. if condition_in(C_AE, JumpC) then
  9270. Unconditional := True
  9271. else
  9272. { Not sure what to do with this jump - drop out }
  9273. Exit;
  9274. end;
  9275. RemoveInstruction(hp1);
  9276. if Unconditional then
  9277. MakeUnconditional(taicpu(hp2))
  9278. else
  9279. begin
  9280. if SetC = C_NONE then
  9281. InternalError(2018061402);
  9282. taicpu(hp2).SetCondition(SetC);
  9283. end;
  9284. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  9285. TmpUsedRegs }
  9286. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  9287. begin
  9288. RemoveCurrentp(p, hp2);
  9289. if taicpu(hp2).opcode = A_SETcc then
  9290. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  9291. else
  9292. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  9293. end
  9294. else
  9295. if taicpu(hp2).opcode = A_SETcc then
  9296. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  9297. else
  9298. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  9299. Result := True;
  9300. end
  9301. else if
  9302. { Make sure the instructions are adjacent }
  9303. (
  9304. not (cs_opt_level3 in current_settings.optimizerswitches) or
  9305. GetNextInstruction(p, hp1)
  9306. ) and
  9307. MatchInstruction(hp1, A_MOV, [S_B]) and
  9308. { Writing to memory is allowed }
  9309. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  9310. begin
  9311. {
  9312. Watch out for sequences such as:
  9313. set(c)b %regb
  9314. movb %regb,(ref)
  9315. movb $0,1(ref)
  9316. movb $0,2(ref)
  9317. movb $0,3(ref)
  9318. Much more efficient to turn it into:
  9319. movl $0,%regl
  9320. set(c)b %regb
  9321. movl %regl,(ref)
  9322. Or:
  9323. set(c)b %regb
  9324. movzbl %regb,%regl
  9325. movl %regl,(ref)
  9326. }
  9327. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  9328. GetNextInstruction(hp1, hp2) and
  9329. MatchInstruction(hp2, A_MOV, [S_B]) and
  9330. (taicpu(hp2).oper[1]^.typ = top_ref) and
  9331. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  9332. begin
  9333. { Don't do anything else except set Result to True }
  9334. end
  9335. else
  9336. begin
  9337. if taicpu(p).oper[0]^.typ = top_reg then
  9338. begin
  9339. TransferUsedRegs(TmpUsedRegs);
  9340. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9341. end;
  9342. { If it's not a register, it's a memory address }
  9343. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9344. begin
  9345. { Even if the register is still in use, we can minimise the
  9346. pipeline stall by changing the MOV into another SETcc. }
  9347. taicpu(hp1).opcode := A_SETcc;
  9348. taicpu(hp1).condition := taicpu(p).condition;
  9349. if taicpu(hp1).oper[1]^.typ = top_ref then
  9350. begin
  9351. { Swapping the operand pointers like this is probably a
  9352. bit naughty, but it is far faster than using loadoper
  9353. to transfer the reference from oper[1] to oper[0] if
  9354. you take into account the extra procedure calls and
  9355. the memory allocation and deallocation required }
  9356. OperPtr := taicpu(hp1).oper[1];
  9357. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9358. taicpu(hp1).oper[0] := OperPtr;
  9359. end
  9360. else
  9361. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9362. taicpu(hp1).clearop(1);
  9363. taicpu(hp1).ops := 1;
  9364. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9365. end
  9366. else
  9367. begin
  9368. if taicpu(hp1).oper[1]^.typ = top_reg then
  9369. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9370. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9371. RemoveInstruction(hp1);
  9372. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9373. end
  9374. end;
  9375. Result := True;
  9376. end;
  9377. end;
  9378. end;
  9379. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  9380. var
  9381. hp1: tai;
  9382. Count: Integer;
  9383. OrigLabel: TAsmLabel;
  9384. begin
  9385. result := False;
  9386. { Sometimes, the optimisations below can permit this }
  9387. RemoveDeadCodeAfterJump(p);
  9388. 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
  9389. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  9390. begin
  9391. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9392. { Also a side-effect of optimisations }
  9393. if CollapseZeroDistJump(p, OrigLabel) then
  9394. begin
  9395. Result := True;
  9396. Exit;
  9397. end;
  9398. hp1 := GetLabelWithSym(OrigLabel);
  9399. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  9400. begin
  9401. if taicpu(hp1).opcode = A_RET then
  9402. begin
  9403. {
  9404. change
  9405. jmp .L1
  9406. ...
  9407. .L1:
  9408. ret
  9409. into
  9410. ret
  9411. }
  9412. begin
  9413. ConvertJumpToRET(p, hp1);
  9414. result:=true;
  9415. end;
  9416. end
  9417. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  9418. not (cs_opt_size in current_settings.optimizerswitches) and
  9419. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  9420. begin
  9421. Result := True;
  9422. Exit;
  9423. end;
  9424. end;
  9425. end;
  9426. end;
  9427. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  9428. begin
  9429. CanBeCMOV:=assigned(p) and
  9430. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  9431. { we can't use cmov ref,reg because
  9432. ref could be nil and cmov still throws an exception
  9433. if ref=nil but the mov isn't done (FK)
  9434. or ((taicpu(p).oper[0]^.typ = top_ref) and
  9435. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  9436. }
  9437. (taicpu(p).oper[1]^.typ = top_reg) and
  9438. (
  9439. (taicpu(p).oper[0]^.typ = top_reg) or
  9440. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  9441. it is not expected that this can cause a seg. violation }
  9442. (
  9443. (taicpu(p).oper[0]^.typ = top_ref) and
  9444. IsRefSafe(taicpu(p).oper[0]^.ref)
  9445. )
  9446. );
  9447. end;
  9448. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  9449. var
  9450. hp1,hp2: tai;
  9451. {$ifndef i8086}
  9452. hp3,hp4,hpmov2, hp5: tai;
  9453. l : Longint;
  9454. condition : TAsmCond;
  9455. {$endif i8086}
  9456. carryadd_opcode : TAsmOp;
  9457. symbol: TAsmSymbol;
  9458. increg, tmpreg: TRegister;
  9459. begin
  9460. result:=false;
  9461. if GetNextInstruction(p,hp1) then
  9462. begin
  9463. if (hp1.typ=ait_label) then
  9464. begin
  9465. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  9466. Exit;
  9467. end
  9468. else if (hp1.typ<>ait_instruction) then
  9469. Exit;
  9470. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9471. if (
  9472. (
  9473. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  9474. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  9475. (Taicpu(hp1).oper[0]^.val=1)
  9476. ) or
  9477. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  9478. ) and
  9479. GetNextInstruction(hp1,hp2) and
  9480. SkipAligns(hp2, hp2) and
  9481. (hp2.typ = ait_label) and
  9482. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  9483. { jb @@1 cmc
  9484. inc/dec operand --> adc/sbb operand,0
  9485. @@1:
  9486. ... and ...
  9487. jnb @@1
  9488. inc/dec operand --> adc/sbb operand,0
  9489. @@1: }
  9490. begin
  9491. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  9492. begin
  9493. case taicpu(hp1).opcode of
  9494. A_INC,
  9495. A_ADD:
  9496. carryadd_opcode:=A_ADC;
  9497. A_DEC,
  9498. A_SUB:
  9499. carryadd_opcode:=A_SBB;
  9500. else
  9501. InternalError(2021011001);
  9502. end;
  9503. Taicpu(p).clearop(0);
  9504. Taicpu(p).ops:=0;
  9505. Taicpu(p).is_jmp:=false;
  9506. Taicpu(p).opcode:=A_CMC;
  9507. Taicpu(p).condition:=C_NONE;
  9508. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  9509. Taicpu(hp1).ops:=2;
  9510. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9511. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9512. else
  9513. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9514. Taicpu(hp1).loadconst(0,0);
  9515. Taicpu(hp1).opcode:=carryadd_opcode;
  9516. result:=true;
  9517. exit;
  9518. end
  9519. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  9520. begin
  9521. case taicpu(hp1).opcode of
  9522. A_INC,
  9523. A_ADD:
  9524. carryadd_opcode:=A_ADC;
  9525. A_DEC,
  9526. A_SUB:
  9527. carryadd_opcode:=A_SBB;
  9528. else
  9529. InternalError(2021011002);
  9530. end;
  9531. Taicpu(hp1).ops:=2;
  9532. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  9533. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9534. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9535. else
  9536. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9537. Taicpu(hp1).loadconst(0,0);
  9538. Taicpu(hp1).opcode:=carryadd_opcode;
  9539. RemoveCurrentP(p, hp1);
  9540. result:=true;
  9541. exit;
  9542. end
  9543. {
  9544. jcc @@1 setcc tmpreg
  9545. inc/dec/add/sub operand -> (movzx tmpreg)
  9546. @@1: add/sub tmpreg,operand
  9547. While this increases code size slightly, it makes the code much faster if the
  9548. jump is unpredictable
  9549. }
  9550. else if not(cs_opt_size in current_settings.optimizerswitches) then
  9551. begin
  9552. { search for an available register which is volatile }
  9553. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  9554. if increg <> NR_NO then
  9555. begin
  9556. { We don't need to check if tmpreg is in hp1 or not, because
  9557. it will be marked as in use at p (if not, this is
  9558. indictive of a compiler bug). }
  9559. TAsmLabel(symbol).decrefs;
  9560. Taicpu(p).clearop(0);
  9561. Taicpu(p).ops:=1;
  9562. Taicpu(p).is_jmp:=false;
  9563. Taicpu(p).opcode:=A_SETcc;
  9564. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  9565. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  9566. Taicpu(p).loadreg(0,increg);
  9567. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  9568. begin
  9569. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  9570. R_SUBW:
  9571. begin
  9572. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  9573. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  9574. end;
  9575. R_SUBD:
  9576. begin
  9577. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9578. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9579. end;
  9580. {$ifdef x86_64}
  9581. R_SUBQ:
  9582. begin
  9583. { MOVZX doesn't have a 64-bit variant, because
  9584. the 32-bit version implicitly zeroes the
  9585. upper 32-bits of the destination register }
  9586. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9587. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9588. setsubreg(tmpreg, R_SUBQ);
  9589. end;
  9590. {$endif x86_64}
  9591. else
  9592. Internalerror(2020030601);
  9593. end;
  9594. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  9595. asml.InsertAfter(hp2,p);
  9596. end
  9597. else
  9598. tmpreg := increg;
  9599. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  9600. begin
  9601. Taicpu(hp1).ops:=2;
  9602. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9603. end;
  9604. Taicpu(hp1).loadreg(0,tmpreg);
  9605. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9606. Result := True;
  9607. { p is no longer a Jcc instruction, so exit }
  9608. Exit;
  9609. end;
  9610. end;
  9611. end;
  9612. { Detect the following:
  9613. jmp<cond> @Lbl1
  9614. jmp @Lbl2
  9615. ...
  9616. @Lbl1:
  9617. ret
  9618. Change to:
  9619. jmp<inv_cond> @Lbl2
  9620. ret
  9621. }
  9622. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9623. begin
  9624. hp2:=getlabelwithsym(TAsmLabel(symbol));
  9625. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  9626. MatchInstruction(hp2,A_RET,[S_NO]) then
  9627. begin
  9628. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  9629. { Change label address to that of the unconditional jump }
  9630. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  9631. TAsmLabel(symbol).DecRefs;
  9632. taicpu(hp1).opcode := A_RET;
  9633. taicpu(hp1).is_jmp := false;
  9634. taicpu(hp1).ops := taicpu(hp2).ops;
  9635. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  9636. case taicpu(hp2).ops of
  9637. 0:
  9638. taicpu(hp1).clearop(0);
  9639. 1:
  9640. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  9641. else
  9642. internalerror(2016041302);
  9643. end;
  9644. end;
  9645. {$ifndef i8086}
  9646. end
  9647. {
  9648. convert
  9649. j<c> .L1
  9650. mov 1,reg
  9651. jmp .L2
  9652. .L1
  9653. mov 0,reg
  9654. .L2
  9655. into
  9656. mov 0,reg
  9657. set<not(c)> reg
  9658. take care of alignment and that the mov 0,reg is not converted into a xor as this
  9659. would destroy the flag contents
  9660. }
  9661. else if MatchInstruction(hp1,A_MOV,[]) and
  9662. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9663. {$ifdef i386}
  9664. (
  9665. { Under i386, ESI, EDI, EBP and ESP
  9666. don't have an 8-bit representation }
  9667. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9668. ) and
  9669. {$endif i386}
  9670. (taicpu(hp1).oper[0]^.val=1) and
  9671. GetNextInstruction(hp1,hp2) and
  9672. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9673. GetNextInstruction(hp2,hp3) and
  9674. { skip align }
  9675. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9676. (hp3.typ=ait_label) and
  9677. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9678. (tai_label(hp3).labsym.getrefs=1) and
  9679. GetNextInstruction(hp3,hp4) and
  9680. MatchInstruction(hp4,A_MOV,[]) and
  9681. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9682. (taicpu(hp4).oper[0]^.val=0) and
  9683. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9684. GetNextInstruction(hp4,hp5) and
  9685. (hp5.typ=ait_label) and
  9686. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9687. (tai_label(hp5).labsym.getrefs=1) then
  9688. begin
  9689. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9690. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9691. { remove last label }
  9692. RemoveInstruction(hp5);
  9693. { remove second label }
  9694. RemoveInstruction(hp3);
  9695. { if align is present remove it }
  9696. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9697. RemoveInstruction(hp3);
  9698. { remove jmp }
  9699. RemoveInstruction(hp2);
  9700. if taicpu(hp1).opsize=S_B then
  9701. RemoveInstruction(hp1)
  9702. else
  9703. taicpu(hp1).loadconst(0,0);
  9704. taicpu(hp4).opcode:=A_SETcc;
  9705. taicpu(hp4).opsize:=S_B;
  9706. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9707. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9708. taicpu(hp4).opercnt:=1;
  9709. taicpu(hp4).ops:=1;
  9710. taicpu(hp4).freeop(1);
  9711. RemoveCurrentP(p);
  9712. Result:=true;
  9713. exit;
  9714. end
  9715. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9716. begin
  9717. { check for
  9718. jCC xxx
  9719. <several movs>
  9720. xxx:
  9721. Also spot:
  9722. Jcc xxx
  9723. <several movs>
  9724. jmp xxx
  9725. Change to:
  9726. <several cmovs with inverted condition>
  9727. jmp xxx
  9728. }
  9729. l:=0;
  9730. while assigned(hp1) and
  9731. CanBeCMOV(hp1) and
  9732. { stop on labels }
  9733. not(hp1.typ=ait_label) do
  9734. begin
  9735. inc(l);
  9736. hp5 := hp1;
  9737. GetNextInstruction(hp1,hp1);
  9738. end;
  9739. if assigned(hp1) then
  9740. begin
  9741. TransferUsedRegs(TmpUsedRegs);
  9742. if (
  9743. MatchInstruction(hp1, A_JMP, []) and
  9744. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  9745. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  9746. ) or
  9747. FindLabel(tasmlabel(symbol),hp1) then
  9748. begin
  9749. if (l<=4) and (l>0) then
  9750. begin
  9751. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9752. condition:=inverse_cond(taicpu(p).condition);
  9753. UpdateUsedRegs(tai(p.next));
  9754. GetNextInstruction(p,hp1);
  9755. repeat
  9756. if not Assigned(hp1) then
  9757. InternalError(2018062900);
  9758. taicpu(hp1).opcode:=A_CMOVcc;
  9759. taicpu(hp1).condition:=condition;
  9760. UpdateUsedRegs(tai(hp1.next));
  9761. GetNextInstruction(hp1,hp1);
  9762. until not(CanBeCMOV(hp1));
  9763. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9764. hp2 := hp1;
  9765. repeat
  9766. if not Assigned(hp2) then
  9767. InternalError(2018062910);
  9768. case hp2.typ of
  9769. ait_label:
  9770. { What we expected - break out of the loop (it won't be a dead label at the top of
  9771. a cluster because that was optimised at an earlier stage) }
  9772. Break;
  9773. ait_align:
  9774. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9775. begin
  9776. hp2 := tai(hp2.Next);
  9777. Continue;
  9778. end;
  9779. ait_instruction:
  9780. begin
  9781. if taicpu(hp2).opcode<>A_JMP then
  9782. InternalError(2018062912);
  9783. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  9784. Break;
  9785. end
  9786. else
  9787. begin
  9788. { Might be a comment or temporary allocation entry }
  9789. if not (hp2.typ in SkipInstr) then
  9790. InternalError(2018062911);
  9791. hp2 := tai(hp2.Next);
  9792. Continue;
  9793. end;
  9794. end;
  9795. until False;
  9796. { Now we can safely decrement the reference count }
  9797. tasmlabel(symbol).decrefs;
  9798. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9799. { Remove the original jump }
  9800. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9801. if hp2.typ=ait_instruction then
  9802. begin
  9803. p:=hp2;
  9804. Result:=True;
  9805. end
  9806. else
  9807. begin
  9808. UpdateUsedRegs(tai(hp2.next));
  9809. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  9810. { Remove the label if this is its final reference }
  9811. if (tasmlabel(symbol).getrefs=0) then
  9812. StripLabelFast(hp1);
  9813. end;
  9814. exit;
  9815. end;
  9816. end
  9817. else
  9818. begin
  9819. { check further for
  9820. jCC xxx
  9821. <several movs 1>
  9822. jmp yyy
  9823. xxx:
  9824. <several movs 2>
  9825. yyy:
  9826. }
  9827. { hp2 points to jmp yyy }
  9828. hp2:=hp1;
  9829. { skip hp1 to xxx (or an align right before it) }
  9830. GetNextInstruction(hp1, hp1);
  9831. if assigned(hp2) and
  9832. assigned(hp1) and
  9833. (l<=3) and
  9834. (hp2.typ=ait_instruction) and
  9835. (taicpu(hp2).is_jmp) and
  9836. (taicpu(hp2).condition=C_None) and
  9837. { real label and jump, no further references to the
  9838. label are allowed }
  9839. (tasmlabel(symbol).getrefs=1) and
  9840. FindLabel(tasmlabel(symbol),hp1) then
  9841. begin
  9842. l:=0;
  9843. { skip hp1 to <several moves 2> }
  9844. if (hp1.typ = ait_align) then
  9845. GetNextInstruction(hp1, hp1);
  9846. GetNextInstruction(hp1, hpmov2);
  9847. hp1 := hpmov2;
  9848. while assigned(hp1) and
  9849. CanBeCMOV(hp1) do
  9850. begin
  9851. inc(l);
  9852. hp5 := hp1;
  9853. GetNextInstruction(hp1, hp1);
  9854. end;
  9855. { hp1 points to yyy (or an align right before it) }
  9856. hp3 := hp1;
  9857. if assigned(hp1) and
  9858. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9859. begin
  9860. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9861. condition:=inverse_cond(taicpu(p).condition);
  9862. UpdateUsedRegs(tai(p.next));
  9863. GetNextInstruction(p,hp1);
  9864. repeat
  9865. taicpu(hp1).opcode:=A_CMOVcc;
  9866. taicpu(hp1).condition:=condition;
  9867. UpdateUsedRegs(tai(hp1.next));
  9868. GetNextInstruction(hp1,hp1);
  9869. until not(assigned(hp1)) or
  9870. not(CanBeCMOV(hp1));
  9871. condition:=inverse_cond(condition);
  9872. if GetLastInstruction(hpmov2,hp1) then
  9873. UpdateUsedRegs(tai(hp1.next));
  9874. hp1 := hpmov2;
  9875. { hp1 is now at <several movs 2> }
  9876. while Assigned(hp1) and CanBeCMOV(hp1) do
  9877. begin
  9878. taicpu(hp1).opcode:=A_CMOVcc;
  9879. taicpu(hp1).condition:=condition;
  9880. UpdateUsedRegs(tai(hp1.next));
  9881. GetNextInstruction(hp1,hp1);
  9882. end;
  9883. hp1 := p;
  9884. { Get first instruction after label }
  9885. UpdateUsedRegs(tai(hp3.next));
  9886. GetNextInstruction(hp3, p);
  9887. if assigned(p) and (hp3.typ = ait_align) then
  9888. GetNextInstruction(p, p);
  9889. { Don't dereference yet, as doing so will cause
  9890. GetNextInstruction to skip the label and
  9891. optional align marker. [Kit] }
  9892. GetNextInstruction(hp2, hp4);
  9893. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9894. { remove jCC }
  9895. RemoveInstruction(hp1);
  9896. { Now we can safely decrement it }
  9897. tasmlabel(symbol).decrefs;
  9898. { Remove label xxx (it will have a ref of zero due to the initial check }
  9899. StripLabelFast(hp4);
  9900. { remove jmp }
  9901. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9902. RemoveInstruction(hp2);
  9903. { As before, now we can safely decrement it }
  9904. tasmlabel(symbol).decrefs;
  9905. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9906. if tasmlabel(symbol).getrefs = 0 then
  9907. StripLabelFast(hp3);
  9908. if Assigned(p) then
  9909. result:=true;
  9910. exit;
  9911. end;
  9912. end;
  9913. end;
  9914. end;
  9915. {$endif i8086}
  9916. end;
  9917. end;
  9918. end;
  9919. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9920. var
  9921. hp1,hp2,hp3: tai;
  9922. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9923. NewSize: TOpSize;
  9924. NewRegSize: TSubRegister;
  9925. Limit: TCgInt;
  9926. SwapOper: POper;
  9927. begin
  9928. result:=false;
  9929. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9930. GetNextInstruction(p,hp1) and
  9931. (hp1.typ = ait_instruction);
  9932. if reg_and_hp1_is_instr and
  9933. (
  9934. (taicpu(hp1).opcode <> A_LEA) or
  9935. { If the LEA instruction can be converted into an arithmetic instruction,
  9936. it may be possible to then fold it. }
  9937. (
  9938. { If the flags register is in use, don't change the instruction
  9939. to an ADD otherwise this will scramble the flags. [Kit] }
  9940. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9941. ConvertLEA(taicpu(hp1))
  9942. )
  9943. ) and
  9944. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9945. GetNextInstruction(hp1,hp2) and
  9946. MatchInstruction(hp2,A_MOV,[]) and
  9947. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9948. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9949. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9950. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9951. {$ifdef i386}
  9952. { not all registers have byte size sub registers on i386 }
  9953. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9954. {$endif i386}
  9955. (((taicpu(hp1).ops=2) and
  9956. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9957. ((taicpu(hp1).ops=1) and
  9958. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9959. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9960. begin
  9961. { change movsX/movzX reg/ref, reg2
  9962. add/sub/or/... reg3/$const, reg2
  9963. mov reg2 reg/ref
  9964. to add/sub/or/... reg3/$const, reg/ref }
  9965. { by example:
  9966. movswl %si,%eax movswl %si,%eax p
  9967. decl %eax addl %edx,%eax hp1
  9968. movw %ax,%si movw %ax,%si hp2
  9969. ->
  9970. movswl %si,%eax movswl %si,%eax p
  9971. decw %eax addw %edx,%eax hp1
  9972. movw %ax,%si movw %ax,%si hp2
  9973. }
  9974. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9975. {
  9976. ->
  9977. movswl %si,%eax movswl %si,%eax p
  9978. decw %si addw %dx,%si hp1
  9979. movw %ax,%si movw %ax,%si hp2
  9980. }
  9981. case taicpu(hp1).ops of
  9982. 1:
  9983. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9984. 2:
  9985. begin
  9986. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9987. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9988. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9989. end;
  9990. else
  9991. internalerror(2008042702);
  9992. end;
  9993. {
  9994. ->
  9995. decw %si addw %dx,%si p
  9996. }
  9997. DebugMsg(SPeepholeOptimization + 'var3',p);
  9998. RemoveCurrentP(p, hp1);
  9999. RemoveInstruction(hp2);
  10000. Result := True;
  10001. Exit;
  10002. end;
  10003. if reg_and_hp1_is_instr and
  10004. (taicpu(hp1).opcode = A_MOV) and
  10005. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10006. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  10007. {$ifdef x86_64}
  10008. { check for implicit extension to 64 bit }
  10009. or
  10010. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10011. (taicpu(hp1).opsize=S_Q) and
  10012. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  10013. )
  10014. {$endif x86_64}
  10015. )
  10016. then
  10017. begin
  10018. { change
  10019. movx %reg1,%reg2
  10020. mov %reg2,%reg3
  10021. dealloc %reg2
  10022. into
  10023. movx %reg,%reg3
  10024. }
  10025. TransferUsedRegs(TmpUsedRegs);
  10026. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10027. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  10028. begin
  10029. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  10030. {$ifdef x86_64}
  10031. if (taicpu(p).opsize in [S_BL,S_WL]) and
  10032. (taicpu(hp1).opsize=S_Q) then
  10033. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  10034. else
  10035. {$endif x86_64}
  10036. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  10037. RemoveInstruction(hp1);
  10038. Result := True;
  10039. Exit;
  10040. end;
  10041. end;
  10042. if reg_and_hp1_is_instr and
  10043. ((taicpu(hp1).opcode=A_MOV) or
  10044. (taicpu(hp1).opcode=A_ADD) or
  10045. (taicpu(hp1).opcode=A_SUB) or
  10046. (taicpu(hp1).opcode=A_CMP) or
  10047. (taicpu(hp1).opcode=A_OR) or
  10048. (taicpu(hp1).opcode=A_XOR) or
  10049. (taicpu(hp1).opcode=A_AND)
  10050. ) and
  10051. (taicpu(hp1).oper[1]^.typ = top_reg) then
  10052. begin
  10053. AndTest := (taicpu(hp1).opcode=A_AND) and
  10054. GetNextInstruction(hp1, hp2) and
  10055. (hp2.typ = ait_instruction) and
  10056. (
  10057. (
  10058. (taicpu(hp2).opcode=A_TEST) and
  10059. (
  10060. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  10061. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  10062. (
  10063. { If the AND and TEST instructions share a constant, this is also valid }
  10064. (taicpu(hp1).oper[0]^.typ = top_const) and
  10065. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  10066. )
  10067. ) and
  10068. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10069. ) or
  10070. (
  10071. (taicpu(hp2).opcode=A_CMP) and
  10072. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  10073. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10074. )
  10075. );
  10076. { change
  10077. movx (oper),%reg2
  10078. and $x,%reg2
  10079. test %reg2,%reg2
  10080. dealloc %reg2
  10081. into
  10082. op %reg1,%reg3
  10083. if the second op accesses only the bits stored in reg1
  10084. }
  10085. if ((taicpu(p).oper[0]^.typ=top_reg) or
  10086. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  10087. (taicpu(hp1).oper[0]^.typ = top_const) and
  10088. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  10089. AndTest then
  10090. begin
  10091. { Check if the AND constant is in range }
  10092. case taicpu(p).opsize of
  10093. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10094. begin
  10095. NewSize := S_B;
  10096. Limit := $FF;
  10097. end;
  10098. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10099. begin
  10100. NewSize := S_W;
  10101. Limit := $FFFF;
  10102. end;
  10103. {$ifdef x86_64}
  10104. S_LQ:
  10105. begin
  10106. NewSize := S_L;
  10107. Limit := $FFFFFFFF;
  10108. end;
  10109. {$endif x86_64}
  10110. else
  10111. InternalError(2021120303);
  10112. end;
  10113. if (
  10114. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  10115. { Check for negative operands }
  10116. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  10117. ) and
  10118. GetNextInstruction(hp2,hp3) and
  10119. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  10120. (taicpu(hp3).condition in [C_E,C_NE]) then
  10121. begin
  10122. TransferUsedRegs(TmpUsedRegs);
  10123. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10124. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10125. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  10126. begin
  10127. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  10128. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10129. taicpu(hp1).opcode := A_TEST;
  10130. taicpu(hp1).opsize := NewSize;
  10131. RemoveInstruction(hp2);
  10132. RemoveCurrentP(p, hp1);
  10133. Result:=true;
  10134. exit;
  10135. end;
  10136. end;
  10137. end;
  10138. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10139. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  10140. (taicpu(hp1).opsize=S_B)) or
  10141. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  10142. (taicpu(hp1).opsize=S_W))
  10143. {$ifdef x86_64}
  10144. or ((taicpu(p).opsize=S_LQ) and
  10145. (taicpu(hp1).opsize=S_L))
  10146. {$endif x86_64}
  10147. ) and
  10148. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  10149. begin
  10150. { change
  10151. movx %reg1,%reg2
  10152. op %reg2,%reg3
  10153. dealloc %reg2
  10154. into
  10155. op %reg1,%reg3
  10156. if the second op accesses only the bits stored in reg1
  10157. }
  10158. TransferUsedRegs(TmpUsedRegs);
  10159. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10160. if AndTest then
  10161. begin
  10162. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10163. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10164. end
  10165. else
  10166. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10167. if not RegUsed then
  10168. begin
  10169. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  10170. if taicpu(p).oper[0]^.typ=top_reg then
  10171. begin
  10172. case taicpu(hp1).opsize of
  10173. S_B:
  10174. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  10175. S_W:
  10176. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  10177. S_L:
  10178. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  10179. else
  10180. Internalerror(2020102301);
  10181. end;
  10182. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  10183. end
  10184. else
  10185. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  10186. RemoveCurrentP(p);
  10187. if AndTest then
  10188. RemoveInstruction(hp2);
  10189. result:=true;
  10190. exit;
  10191. end;
  10192. end
  10193. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10194. (
  10195. { Bitwise operations only }
  10196. (taicpu(hp1).opcode=A_AND) or
  10197. (taicpu(hp1).opcode=A_TEST) or
  10198. (
  10199. (taicpu(hp1).oper[0]^.typ = top_const) and
  10200. (
  10201. (taicpu(hp1).opcode=A_OR) or
  10202. (taicpu(hp1).opcode=A_XOR)
  10203. )
  10204. )
  10205. ) and
  10206. (
  10207. (taicpu(hp1).oper[0]^.typ = top_const) or
  10208. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  10209. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  10210. ) then
  10211. begin
  10212. { change
  10213. movx %reg2,%reg2
  10214. op const,%reg2
  10215. into
  10216. op const,%reg2 (smaller version)
  10217. movx %reg2,%reg2
  10218. also change
  10219. movx %reg1,%reg2
  10220. and/test (oper),%reg2
  10221. dealloc %reg2
  10222. into
  10223. and/test (oper),%reg1
  10224. }
  10225. case taicpu(p).opsize of
  10226. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10227. begin
  10228. NewSize := S_B;
  10229. NewRegSize := R_SUBL;
  10230. Limit := $FF;
  10231. end;
  10232. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10233. begin
  10234. NewSize := S_W;
  10235. NewRegSize := R_SUBW;
  10236. Limit := $FFFF;
  10237. end;
  10238. {$ifdef x86_64}
  10239. S_LQ:
  10240. begin
  10241. NewSize := S_L;
  10242. NewRegSize := R_SUBD;
  10243. Limit := $FFFFFFFF;
  10244. end;
  10245. {$endif x86_64}
  10246. else
  10247. Internalerror(2021120302);
  10248. end;
  10249. TransferUsedRegs(TmpUsedRegs);
  10250. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10251. if AndTest then
  10252. begin
  10253. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10254. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10255. end
  10256. else
  10257. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10258. if
  10259. (
  10260. (taicpu(p).opcode = A_MOVZX) and
  10261. (
  10262. (taicpu(hp1).opcode=A_AND) or
  10263. (taicpu(hp1).opcode=A_TEST)
  10264. ) and
  10265. not (
  10266. { If both are references, then the final instruction will have
  10267. both operands as references, which is not allowed }
  10268. (taicpu(p).oper[0]^.typ = top_ref) and
  10269. (taicpu(hp1).oper[0]^.typ = top_ref)
  10270. ) and
  10271. not RegUsed
  10272. ) or
  10273. (
  10274. (
  10275. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  10276. not RegUsed
  10277. ) and
  10278. (taicpu(p).oper[0]^.typ = top_reg) and
  10279. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10280. (taicpu(hp1).oper[0]^.typ = top_const) and
  10281. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  10282. ) then
  10283. begin
  10284. {$if defined(i386) or defined(i8086)}
  10285. { If the target size is 8-bit, make sure we can actually encode it }
  10286. 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
  10287. Exit;
  10288. {$endif i386 or i8086}
  10289. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  10290. taicpu(hp1).opsize := NewSize;
  10291. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10292. if AndTest then
  10293. begin
  10294. RemoveInstruction(hp2);
  10295. if not RegUsed then
  10296. begin
  10297. taicpu(hp1).opcode := A_TEST;
  10298. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  10299. begin
  10300. { Make sure the reference is the second operand }
  10301. SwapOper := taicpu(hp1).oper[0];
  10302. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  10303. taicpu(hp1).oper[1] := SwapOper;
  10304. end;
  10305. end;
  10306. end;
  10307. case taicpu(hp1).oper[0]^.typ of
  10308. top_reg:
  10309. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  10310. top_const:
  10311. { For the AND/TEST case }
  10312. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  10313. else
  10314. ;
  10315. end;
  10316. if RegUsed then
  10317. begin
  10318. AsmL.Remove(p);
  10319. AsmL.InsertAfter(p, hp1);
  10320. p := hp1;
  10321. end
  10322. else
  10323. RemoveCurrentP(p, hp1);
  10324. result:=true;
  10325. exit;
  10326. end;
  10327. end;
  10328. end;
  10329. if reg_and_hp1_is_instr and
  10330. (taicpu(p).oper[0]^.typ = top_reg) and
  10331. (
  10332. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  10333. ) and
  10334. (taicpu(hp1).oper[0]^.typ = top_const) and
  10335. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10336. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10337. { Minimum shift value allowed is the bit difference between the sizes }
  10338. (taicpu(hp1).oper[0]^.val >=
  10339. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10340. 8 * (
  10341. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10342. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10343. )
  10344. ) then
  10345. begin
  10346. { For:
  10347. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10348. shl/sal ##, %reg1
  10349. Remove the movsx/movzx instruction if the shift overwrites the
  10350. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10351. }
  10352. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10353. RemoveCurrentP(p, hp1);
  10354. Result := True;
  10355. Exit;
  10356. end
  10357. else if reg_and_hp1_is_instr and
  10358. (taicpu(p).oper[0]^.typ = top_reg) and
  10359. (
  10360. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10361. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10362. ) and
  10363. (taicpu(hp1).oper[0]^.typ = top_const) and
  10364. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10365. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10366. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10367. (taicpu(hp1).oper[0]^.val <
  10368. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10369. 8 * (
  10370. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10371. )
  10372. ) then
  10373. begin
  10374. { For:
  10375. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10376. sar ##, %reg1 shr ##, %reg1
  10377. Move the shift to before the movx instruction if the shift value
  10378. is not too large.
  10379. }
  10380. asml.Remove(hp1);
  10381. asml.InsertBefore(hp1, p);
  10382. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10383. case taicpu(p).opsize of
  10384. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  10385. taicpu(hp1).opsize := S_B;
  10386. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  10387. taicpu(hp1).opsize := S_W;
  10388. {$ifdef x86_64}
  10389. S_LQ:
  10390. taicpu(hp1).opsize := S_L;
  10391. {$endif}
  10392. else
  10393. InternalError(2020112401);
  10394. end;
  10395. if (taicpu(hp1).opcode = A_SHR) then
  10396. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  10397. else
  10398. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  10399. Result := True;
  10400. end;
  10401. if reg_and_hp1_is_instr and
  10402. (taicpu(p).oper[0]^.typ = top_reg) and
  10403. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10404. (
  10405. (taicpu(hp1).opcode = taicpu(p).opcode)
  10406. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  10407. {$ifdef x86_64}
  10408. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  10409. {$endif x86_64}
  10410. ) then
  10411. begin
  10412. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10413. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  10414. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10415. begin
  10416. {
  10417. For example:
  10418. movzbw %al,%ax
  10419. movzwl %ax,%eax
  10420. Compress into:
  10421. movzbl %al,%eax
  10422. }
  10423. RegUsed := False;
  10424. case taicpu(p).opsize of
  10425. S_BW:
  10426. case taicpu(hp1).opsize of
  10427. S_WL:
  10428. begin
  10429. taicpu(p).opsize := S_BL;
  10430. RegUsed := True;
  10431. end;
  10432. {$ifdef x86_64}
  10433. S_WQ:
  10434. begin
  10435. if taicpu(p).opcode = A_MOVZX then
  10436. begin
  10437. taicpu(p).opsize := S_BL;
  10438. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10439. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10440. end
  10441. else
  10442. taicpu(p).opsize := S_BQ;
  10443. RegUsed := True;
  10444. end;
  10445. {$endif x86_64}
  10446. else
  10447. ;
  10448. end;
  10449. {$ifdef x86_64}
  10450. S_BL:
  10451. case taicpu(hp1).opsize of
  10452. S_LQ:
  10453. begin
  10454. if taicpu(p).opcode = A_MOVZX then
  10455. begin
  10456. taicpu(p).opsize := S_BL;
  10457. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10458. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10459. end
  10460. else
  10461. taicpu(p).opsize := S_BQ;
  10462. RegUsed := True;
  10463. end;
  10464. else
  10465. ;
  10466. end;
  10467. S_WL:
  10468. case taicpu(hp1).opsize of
  10469. S_LQ:
  10470. begin
  10471. if taicpu(p).opcode = A_MOVZX then
  10472. begin
  10473. taicpu(p).opsize := S_WL;
  10474. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10475. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10476. end
  10477. else
  10478. taicpu(p).opsize := S_WQ;
  10479. RegUsed := True;
  10480. end;
  10481. else
  10482. ;
  10483. end;
  10484. {$endif x86_64}
  10485. else
  10486. ;
  10487. end;
  10488. if RegUsed then
  10489. begin
  10490. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  10491. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10492. RemoveInstruction(hp1);
  10493. Result := True;
  10494. Exit;
  10495. end;
  10496. end;
  10497. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  10498. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  10499. GetNextInstruction(hp1, hp2) and
  10500. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  10501. (
  10502. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  10503. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  10504. {$ifdef x86_64}
  10505. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  10506. {$endif x86_64}
  10507. ) and
  10508. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  10509. (
  10510. (
  10511. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10512. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10513. ) or
  10514. (
  10515. { Only allow the operands in reverse order for TEST instructions }
  10516. (taicpu(hp2).opcode = A_TEST) and
  10517. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10518. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  10519. )
  10520. ) then
  10521. begin
  10522. {
  10523. For example:
  10524. movzbl %al,%eax
  10525. movzbl (ref),%edx
  10526. andl %edx,%eax
  10527. (%edx deallocated)
  10528. Change to:
  10529. andb (ref),%al
  10530. movzbl %al,%eax
  10531. Rules are:
  10532. - First two instructions have the same opcode and opsize
  10533. - First instruction's operands are the same super-register
  10534. - Second instruction operates on a different register
  10535. - Third instruction is AND, OR, XOR or TEST
  10536. - Third instruction's operands are the destination registers of the first two instructions
  10537. - Third instruction writes to the destination register of the first instruction (except with TEST)
  10538. - Second instruction's destination register is deallocated afterwards
  10539. }
  10540. TransferUsedRegs(TmpUsedRegs);
  10541. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10542. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10543. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  10544. begin
  10545. case taicpu(p).opsize of
  10546. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10547. NewSize := S_B;
  10548. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10549. NewSize := S_W;
  10550. {$ifdef x86_64}
  10551. S_LQ:
  10552. NewSize := S_L;
  10553. {$endif x86_64}
  10554. else
  10555. InternalError(2021120301);
  10556. end;
  10557. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  10558. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  10559. taicpu(hp2).opsize := NewSize;
  10560. RemoveInstruction(hp1);
  10561. { With TEST, it's best to keep the MOVX instruction at the top }
  10562. if (taicpu(hp2).opcode <> A_TEST) then
  10563. begin
  10564. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  10565. asml.Remove(p);
  10566. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  10567. asml.InsertAfter(p, hp2);
  10568. p := hp2;
  10569. end
  10570. else
  10571. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  10572. Result := True;
  10573. Exit;
  10574. end;
  10575. end;
  10576. end;
  10577. if taicpu(p).opcode=A_MOVZX then
  10578. begin
  10579. { removes superfluous And's after movzx's }
  10580. if reg_and_hp1_is_instr and
  10581. (taicpu(hp1).opcode = A_AND) and
  10582. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10583. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10584. {$ifdef x86_64}
  10585. { check for implicit extension to 64 bit }
  10586. or
  10587. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10588. (taicpu(hp1).opsize=S_Q) and
  10589. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  10590. )
  10591. {$endif x86_64}
  10592. )
  10593. then
  10594. begin
  10595. case taicpu(p).opsize Of
  10596. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10597. if (taicpu(hp1).oper[0]^.val = $ff) then
  10598. begin
  10599. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  10600. RemoveInstruction(hp1);
  10601. Result:=true;
  10602. exit;
  10603. end;
  10604. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10605. if (taicpu(hp1).oper[0]^.val = $ffff) then
  10606. begin
  10607. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  10608. RemoveInstruction(hp1);
  10609. Result:=true;
  10610. exit;
  10611. end;
  10612. {$ifdef x86_64}
  10613. S_LQ:
  10614. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  10615. begin
  10616. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  10617. RemoveInstruction(hp1);
  10618. Result:=true;
  10619. exit;
  10620. end;
  10621. {$endif x86_64}
  10622. else
  10623. ;
  10624. end;
  10625. { we cannot get rid of the and, but can we get rid of the movz ?}
  10626. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  10627. begin
  10628. case taicpu(p).opsize Of
  10629. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10630. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  10631. begin
  10632. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  10633. RemoveCurrentP(p,hp1);
  10634. Result:=true;
  10635. exit;
  10636. end;
  10637. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10638. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  10639. begin
  10640. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  10641. RemoveCurrentP(p,hp1);
  10642. Result:=true;
  10643. exit;
  10644. end;
  10645. {$ifdef x86_64}
  10646. S_LQ:
  10647. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  10648. begin
  10649. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  10650. RemoveCurrentP(p,hp1);
  10651. Result:=true;
  10652. exit;
  10653. end;
  10654. {$endif x86_64}
  10655. else
  10656. ;
  10657. end;
  10658. end;
  10659. end;
  10660. { changes some movzx constructs to faster synonyms (all examples
  10661. are given with eax/ax, but are also valid for other registers)}
  10662. if MatchOpType(taicpu(p),top_reg,top_reg) then
  10663. begin
  10664. case taicpu(p).opsize of
  10665. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  10666. (the machine code is equivalent to movzbl %al,%eax), but the
  10667. code generator still generates that assembler instruction and
  10668. it is silently converted. This should probably be checked.
  10669. [Kit] }
  10670. S_BW:
  10671. begin
  10672. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10673. (
  10674. not IsMOVZXAcceptable
  10675. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  10676. or (
  10677. (cs_opt_size in current_settings.optimizerswitches) and
  10678. (taicpu(p).oper[1]^.reg = NR_AX)
  10679. )
  10680. ) then
  10681. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  10682. begin
  10683. DebugMsg(SPeepholeOptimization + 'var7',p);
  10684. taicpu(p).opcode := A_AND;
  10685. taicpu(p).changeopsize(S_W);
  10686. taicpu(p).loadConst(0,$ff);
  10687. Result := True;
  10688. end
  10689. else if not IsMOVZXAcceptable and
  10690. GetNextInstruction(p, hp1) and
  10691. (tai(hp1).typ = ait_instruction) and
  10692. (taicpu(hp1).opcode = A_AND) and
  10693. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10694. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10695. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  10696. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  10697. begin
  10698. DebugMsg(SPeepholeOptimization + 'var8',p);
  10699. taicpu(p).opcode := A_MOV;
  10700. taicpu(p).changeopsize(S_W);
  10701. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10702. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10703. Result := True;
  10704. end;
  10705. end;
  10706. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10707. S_BL:
  10708. begin
  10709. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10710. (
  10711. not IsMOVZXAcceptable
  10712. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10713. or (
  10714. (cs_opt_size in current_settings.optimizerswitches) and
  10715. (taicpu(p).oper[1]^.reg = NR_EAX)
  10716. )
  10717. ) then
  10718. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10719. begin
  10720. DebugMsg(SPeepholeOptimization + 'var9',p);
  10721. taicpu(p).opcode := A_AND;
  10722. taicpu(p).changeopsize(S_L);
  10723. taicpu(p).loadConst(0,$ff);
  10724. Result := True;
  10725. end
  10726. else if not IsMOVZXAcceptable and
  10727. GetNextInstruction(p, hp1) and
  10728. (tai(hp1).typ = ait_instruction) and
  10729. (taicpu(hp1).opcode = A_AND) and
  10730. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10731. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10732. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10733. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10734. begin
  10735. DebugMsg(SPeepholeOptimization + 'var10',p);
  10736. taicpu(p).opcode := A_MOV;
  10737. taicpu(p).changeopsize(S_L);
  10738. { do not use R_SUBWHOLE
  10739. as movl %rdx,%eax
  10740. is invalid in assembler PM }
  10741. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10742. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10743. Result := True;
  10744. end;
  10745. end;
  10746. {$endif i8086}
  10747. S_WL:
  10748. if not IsMOVZXAcceptable then
  10749. begin
  10750. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10751. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10752. begin
  10753. DebugMsg(SPeepholeOptimization + 'var11',p);
  10754. taicpu(p).opcode := A_AND;
  10755. taicpu(p).changeopsize(S_L);
  10756. taicpu(p).loadConst(0,$ffff);
  10757. Result := True;
  10758. end
  10759. else if GetNextInstruction(p, hp1) and
  10760. (tai(hp1).typ = ait_instruction) and
  10761. (taicpu(hp1).opcode = A_AND) and
  10762. (taicpu(hp1).oper[0]^.typ = top_const) and
  10763. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10764. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10765. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10766. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10767. begin
  10768. DebugMsg(SPeepholeOptimization + 'var12',p);
  10769. taicpu(p).opcode := A_MOV;
  10770. taicpu(p).changeopsize(S_L);
  10771. { do not use R_SUBWHOLE
  10772. as movl %rdx,%eax
  10773. is invalid in assembler PM }
  10774. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10775. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10776. Result := True;
  10777. end;
  10778. end;
  10779. else
  10780. InternalError(2017050705);
  10781. end;
  10782. end
  10783. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10784. begin
  10785. if GetNextInstruction(p, hp1) and
  10786. (tai(hp1).typ = ait_instruction) and
  10787. (taicpu(hp1).opcode = A_AND) and
  10788. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10789. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10790. begin
  10791. //taicpu(p).opcode := A_MOV;
  10792. case taicpu(p).opsize Of
  10793. S_BL:
  10794. begin
  10795. DebugMsg(SPeepholeOptimization + 'var13',p);
  10796. taicpu(hp1).changeopsize(S_L);
  10797. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10798. end;
  10799. S_WL:
  10800. begin
  10801. DebugMsg(SPeepholeOptimization + 'var14',p);
  10802. taicpu(hp1).changeopsize(S_L);
  10803. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10804. end;
  10805. S_BW:
  10806. begin
  10807. DebugMsg(SPeepholeOptimization + 'var15',p);
  10808. taicpu(hp1).changeopsize(S_W);
  10809. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10810. end;
  10811. else
  10812. Internalerror(2017050704)
  10813. end;
  10814. Result := True;
  10815. end;
  10816. end;
  10817. end;
  10818. end;
  10819. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10820. var
  10821. hp1, hp2 : tai;
  10822. MaskLength : Cardinal;
  10823. MaskedBits : TCgInt;
  10824. ActiveReg : TRegister;
  10825. begin
  10826. Result:=false;
  10827. { There are no optimisations for reference targets }
  10828. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10829. Exit;
  10830. while GetNextInstruction(p, hp1) and
  10831. (hp1.typ = ait_instruction) do
  10832. begin
  10833. if (taicpu(p).oper[0]^.typ = top_const) then
  10834. begin
  10835. case taicpu(hp1).opcode of
  10836. A_AND:
  10837. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10838. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10839. { the second register must contain the first one, so compare their subreg types }
  10840. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10841. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10842. { change
  10843. and const1, reg
  10844. and const2, reg
  10845. to
  10846. and (const1 and const2), reg
  10847. }
  10848. begin
  10849. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10850. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10851. RemoveCurrentP(p, hp1);
  10852. Result:=true;
  10853. exit;
  10854. end;
  10855. A_CMP:
  10856. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10857. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10858. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10859. { Just check that the condition on the next instruction is compatible }
  10860. GetNextInstruction(hp1, hp2) and
  10861. (hp2.typ = ait_instruction) and
  10862. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10863. then
  10864. { change
  10865. and 2^n, reg
  10866. cmp 2^n, reg
  10867. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10868. to
  10869. and 2^n, reg
  10870. test reg, reg
  10871. j(~c) / set(~c) / cmov(~c)
  10872. }
  10873. begin
  10874. { Keep TEST instruction in, rather than remove it, because
  10875. it may trigger other optimisations such as MovAndTest2Test }
  10876. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10877. taicpu(hp1).opcode := A_TEST;
  10878. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10879. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10880. Result := True;
  10881. Exit;
  10882. end;
  10883. A_MOVZX:
  10884. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10885. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10886. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10887. (
  10888. (
  10889. (taicpu(p).opsize=S_W) and
  10890. (taicpu(hp1).opsize=S_BW)
  10891. ) or
  10892. (
  10893. (taicpu(p).opsize=S_L) and
  10894. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10895. )
  10896. {$ifdef x86_64}
  10897. or
  10898. (
  10899. (taicpu(p).opsize=S_Q) and
  10900. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10901. )
  10902. {$endif x86_64}
  10903. ) then
  10904. begin
  10905. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10906. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10907. ) or
  10908. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10909. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10910. then
  10911. begin
  10912. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10913. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10914. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10915. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10916. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10917. }
  10918. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10919. RemoveInstruction(hp1);
  10920. { See if there are other optimisations possible }
  10921. Continue;
  10922. end;
  10923. end;
  10924. A_SHL:
  10925. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10926. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10927. begin
  10928. {$ifopt R+}
  10929. {$define RANGE_WAS_ON}
  10930. {$R-}
  10931. {$endif}
  10932. { get length of potential and mask }
  10933. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10934. { really a mask? }
  10935. {$ifdef RANGE_WAS_ON}
  10936. {$R+}
  10937. {$endif}
  10938. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10939. { unmasked part shifted out? }
  10940. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10941. begin
  10942. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10943. RemoveCurrentP(p, hp1);
  10944. Result:=true;
  10945. exit;
  10946. end;
  10947. end;
  10948. A_SHR:
  10949. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10950. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10951. (taicpu(hp1).oper[0]^.val <= 63) then
  10952. begin
  10953. { Does SHR combined with the AND cover all the bits?
  10954. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10955. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10956. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10957. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10958. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10959. begin
  10960. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10961. RemoveCurrentP(p, hp1);
  10962. Result := True;
  10963. Exit;
  10964. end;
  10965. end;
  10966. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10967. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10968. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10969. begin
  10970. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10971. (
  10972. (
  10973. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10974. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10975. ) or (
  10976. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10977. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10978. {$ifdef x86_64}
  10979. ) or (
  10980. (taicpu(hp1).opsize = S_LQ) and
  10981. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10982. {$endif x86_64}
  10983. )
  10984. ) then
  10985. begin
  10986. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10987. begin
  10988. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10989. RemoveInstruction(hp1);
  10990. { See if there are other optimisations possible }
  10991. Continue;
  10992. end;
  10993. { The super-registers are the same though.
  10994. Note that this change by itself doesn't improve
  10995. code speed, but it opens up other optimisations. }
  10996. {$ifdef x86_64}
  10997. { Convert 64-bit register to 32-bit }
  10998. case taicpu(hp1).opsize of
  10999. S_BQ:
  11000. begin
  11001. taicpu(hp1).opsize := S_BL;
  11002. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  11003. end;
  11004. S_WQ:
  11005. begin
  11006. taicpu(hp1).opsize := S_WL;
  11007. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  11008. end
  11009. else
  11010. ;
  11011. end;
  11012. {$endif x86_64}
  11013. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  11014. taicpu(hp1).opcode := A_MOVZX;
  11015. { See if there are other optimisations possible }
  11016. Continue;
  11017. end;
  11018. end;
  11019. else
  11020. ;
  11021. end;
  11022. end
  11023. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  11024. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  11025. begin
  11026. {$ifdef x86_64}
  11027. if (taicpu(p).opsize = S_Q) then
  11028. begin
  11029. { Never necessary }
  11030. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  11031. RemoveCurrentP(p, hp1);
  11032. Result := True;
  11033. Exit;
  11034. end;
  11035. {$endif x86_64}
  11036. { Forward check to determine necessity of and %reg,%reg }
  11037. TransferUsedRegs(TmpUsedRegs);
  11038. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11039. { Saves on a bunch of dereferences }
  11040. ActiveReg := taicpu(p).oper[1]^.reg;
  11041. case taicpu(hp1).opcode of
  11042. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11043. if (
  11044. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11045. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11046. ) and
  11047. (
  11048. (taicpu(hp1).opcode <> A_MOV) or
  11049. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  11050. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  11051. ) and
  11052. not (
  11053. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  11054. (taicpu(hp1).opcode = A_MOV) and
  11055. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  11056. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  11057. ) and
  11058. (
  11059. (
  11060. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11061. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  11062. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  11063. ) or
  11064. (
  11065. {$ifdef x86_64}
  11066. (
  11067. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  11068. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  11069. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  11070. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  11071. ) and
  11072. {$endif x86_64}
  11073. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  11074. )
  11075. ) then
  11076. begin
  11077. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  11078. RemoveCurrentP(p, hp1);
  11079. Result := True;
  11080. Exit;
  11081. end;
  11082. A_ADD,
  11083. A_AND,
  11084. A_BSF,
  11085. A_BSR,
  11086. A_BTC,
  11087. A_BTR,
  11088. A_BTS,
  11089. A_OR,
  11090. A_SUB,
  11091. A_XOR:
  11092. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  11093. if (
  11094. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11095. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11096. ) and
  11097. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  11098. begin
  11099. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  11100. RemoveCurrentP(p, hp1);
  11101. Result := True;
  11102. Exit;
  11103. end;
  11104. A_CMP,
  11105. A_TEST:
  11106. if (
  11107. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11108. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11109. ) and
  11110. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  11111. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  11112. begin
  11113. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  11114. RemoveCurrentP(p, hp1);
  11115. Result := True;
  11116. Exit;
  11117. end;
  11118. A_BSWAP,
  11119. A_NEG,
  11120. A_NOT:
  11121. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  11122. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  11123. begin
  11124. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  11125. RemoveCurrentP(p, hp1);
  11126. Result := True;
  11127. Exit;
  11128. end;
  11129. else
  11130. ;
  11131. end;
  11132. end;
  11133. if (taicpu(hp1).is_jmp) and
  11134. (taicpu(hp1).opcode<>A_JMP) and
  11135. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  11136. begin
  11137. { change
  11138. and x, reg
  11139. jxx
  11140. to
  11141. test x, reg
  11142. jxx
  11143. if reg is deallocated before the
  11144. jump, but only if it's a conditional jump (PFV)
  11145. }
  11146. taicpu(p).opcode := A_TEST;
  11147. Exit;
  11148. end;
  11149. Break;
  11150. end;
  11151. { Lone AND tests }
  11152. if (taicpu(p).oper[0]^.typ = top_const) then
  11153. begin
  11154. {
  11155. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  11156. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  11157. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  11158. }
  11159. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  11160. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  11161. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  11162. begin
  11163. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  11164. if taicpu(p).opsize = S_L then
  11165. begin
  11166. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  11167. Result := True;
  11168. end;
  11169. end;
  11170. end;
  11171. { Backward check to determine necessity of and %reg,%reg }
  11172. if (taicpu(p).oper[0]^.typ = top_reg) and
  11173. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11174. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11175. GetLastInstruction(p, hp2) and
  11176. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  11177. { Check size of adjacent instruction to determine if the AND is
  11178. effectively a null operation }
  11179. (
  11180. (taicpu(p).opsize = taicpu(hp2).opsize) or
  11181. { Note: Don't include S_Q }
  11182. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  11183. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  11184. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  11185. ) then
  11186. begin
  11187. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  11188. { If GetNextInstruction returned False, hp1 will be nil }
  11189. RemoveCurrentP(p, hp1);
  11190. Result := True;
  11191. Exit;
  11192. end;
  11193. end;
  11194. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  11195. var
  11196. hp1: tai; NewRef: TReference;
  11197. { This entire nested function is used in an if-statement below, but we
  11198. want to avoid all the used reg transfers and GetNextInstruction calls
  11199. until we really have to check }
  11200. function MemRegisterNotUsedLater: Boolean; inline;
  11201. var
  11202. hp2: tai;
  11203. begin
  11204. TransferUsedRegs(TmpUsedRegs);
  11205. hp2 := p;
  11206. repeat
  11207. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11208. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11209. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  11210. end;
  11211. begin
  11212. Result := False;
  11213. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  11214. Exit;
  11215. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  11216. begin
  11217. { Change:
  11218. add %reg2,%reg1
  11219. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  11220. To:
  11221. mov/s/z #(%reg1,%reg2),%reg1
  11222. }
  11223. if MatchOpType(taicpu(p), top_reg, top_reg) and
  11224. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  11225. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  11226. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  11227. (
  11228. (
  11229. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  11230. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  11231. { r/esp cannot be an index }
  11232. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  11233. ) or (
  11234. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  11235. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  11236. )
  11237. ) and (
  11238. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  11239. (
  11240. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  11241. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11242. MemRegisterNotUsedLater
  11243. )
  11244. ) then
  11245. begin
  11246. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11247. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11248. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  11249. RemoveCurrentp(p, hp1);
  11250. Result := True;
  11251. Exit;
  11252. end;
  11253. { Change:
  11254. addl/q $x,%reg1
  11255. movl/q %reg1,%reg2
  11256. To:
  11257. leal/q $x(%reg1),%reg2
  11258. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11259. Breaks the dependency chain.
  11260. }
  11261. if MatchOpType(taicpu(p),top_const,top_reg) and
  11262. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11263. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11264. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11265. (
  11266. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  11267. not (cs_opt_size in current_settings.optimizerswitches) or
  11268. (
  11269. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11270. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11271. )
  11272. ) then
  11273. begin
  11274. { Change the MOV instruction to a LEA instruction, and update the
  11275. first operand }
  11276. reference_reset(NewRef, 1, []);
  11277. NewRef.base := taicpu(p).oper[1]^.reg;
  11278. NewRef.scalefactor := 1;
  11279. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  11280. taicpu(hp1).opcode := A_LEA;
  11281. taicpu(hp1).loadref(0, NewRef);
  11282. TransferUsedRegs(TmpUsedRegs);
  11283. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11284. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11285. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11286. begin
  11287. { Move what is now the LEA instruction to before the SUB instruction }
  11288. Asml.Remove(hp1);
  11289. Asml.InsertBefore(hp1, p);
  11290. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11291. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  11292. p := hp1;
  11293. end
  11294. else
  11295. begin
  11296. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11297. RemoveCurrentP(p, hp1);
  11298. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  11299. end;
  11300. Result := True;
  11301. end;
  11302. end;
  11303. end;
  11304. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  11305. var
  11306. SubReg: TSubRegister;
  11307. begin
  11308. Result:=false;
  11309. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  11310. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11311. with taicpu(p).oper[0]^.ref^ do
  11312. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  11313. begin
  11314. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  11315. begin
  11316. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  11317. taicpu(p).opcode := A_ADD;
  11318. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  11319. Result := True;
  11320. end
  11321. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  11322. begin
  11323. if (base <> NR_NO) then
  11324. begin
  11325. if (scalefactor <= 1) then
  11326. begin
  11327. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  11328. taicpu(p).opcode := A_ADD;
  11329. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  11330. Result := True;
  11331. end;
  11332. end
  11333. else
  11334. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  11335. if (scalefactor in [2, 4, 8]) then
  11336. begin
  11337. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  11338. taicpu(p).loadconst(0, BsrByte(scalefactor));
  11339. taicpu(p).opcode := A_SHL;
  11340. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  11341. Result := True;
  11342. end;
  11343. end;
  11344. end;
  11345. end;
  11346. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  11347. var
  11348. hp1: tai; NewRef: TReference;
  11349. begin
  11350. { Change:
  11351. subl/q $x,%reg1
  11352. movl/q %reg1,%reg2
  11353. To:
  11354. leal/q $-x(%reg1),%reg2
  11355. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11356. Breaks the dependency chain and potentially permits the removal of
  11357. a CMP instruction if one follows.
  11358. }
  11359. Result := False;
  11360. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  11361. MatchOpType(taicpu(p),top_const,top_reg) and
  11362. GetNextInstruction(p, hp1) and
  11363. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11364. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11365. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11366. (
  11367. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  11368. not (cs_opt_size in current_settings.optimizerswitches) or
  11369. (
  11370. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11371. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11372. )
  11373. ) then
  11374. begin
  11375. { Change the MOV instruction to a LEA instruction, and update the
  11376. first operand }
  11377. reference_reset(NewRef, 1, []);
  11378. NewRef.base := taicpu(p).oper[1]^.reg;
  11379. NewRef.scalefactor := 1;
  11380. NewRef.offset := -taicpu(p).oper[0]^.val;
  11381. taicpu(hp1).opcode := A_LEA;
  11382. taicpu(hp1).loadref(0, NewRef);
  11383. TransferUsedRegs(TmpUsedRegs);
  11384. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11385. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11386. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11387. begin
  11388. { Move what is now the LEA instruction to before the SUB instruction }
  11389. Asml.Remove(hp1);
  11390. Asml.InsertBefore(hp1, p);
  11391. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11392. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  11393. p := hp1;
  11394. end
  11395. else
  11396. begin
  11397. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11398. RemoveCurrentP(p, hp1);
  11399. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  11400. end;
  11401. Result := True;
  11402. end;
  11403. end;
  11404. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  11405. begin
  11406. { we can skip all instructions not messing with the stack pointer }
  11407. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  11408. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  11409. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  11410. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  11411. ({(taicpu(hp1).ops=0) or }
  11412. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  11413. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  11414. ) and }
  11415. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  11416. )
  11417. ) do
  11418. GetNextInstruction(hp1,hp1);
  11419. Result:=assigned(hp1);
  11420. end;
  11421. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  11422. var
  11423. hp1, hp2, hp3, hp4, hp5: tai;
  11424. begin
  11425. Result:=false;
  11426. hp5:=nil;
  11427. { replace
  11428. leal(q) x(<stackpointer>),<stackpointer>
  11429. call procname
  11430. leal(q) -x(<stackpointer>),<stackpointer>
  11431. ret
  11432. by
  11433. jmp procname
  11434. but do it only on level 4 because it destroys stack back traces
  11435. }
  11436. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11437. MatchOpType(taicpu(p),top_ref,top_reg) and
  11438. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11439. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  11440. { the -8 or -24 are not required, but bail out early if possible,
  11441. higher values are unlikely }
  11442. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  11443. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  11444. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  11445. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  11446. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11447. GetNextInstruction(p, hp1) and
  11448. { Take a copy of hp1 }
  11449. SetAndTest(hp1, hp4) and
  11450. { trick to skip label }
  11451. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11452. SkipSimpleInstructions(hp1) and
  11453. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11454. GetNextInstruction(hp1, hp2) and
  11455. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  11456. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  11457. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  11458. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11459. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  11460. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  11461. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  11462. { Segment register will be NR_NO }
  11463. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11464. GetNextInstruction(hp2, hp3) and
  11465. { trick to skip label }
  11466. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11467. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11468. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11469. SetAndTest(hp3,hp5) and
  11470. GetNextInstruction(hp3,hp3) and
  11471. MatchInstruction(hp3,A_RET,[S_NO])
  11472. )
  11473. ) and
  11474. (taicpu(hp3).ops=0) then
  11475. begin
  11476. taicpu(hp1).opcode := A_JMP;
  11477. taicpu(hp1).is_jmp := true;
  11478. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  11479. RemoveCurrentP(p, hp4);
  11480. RemoveInstruction(hp2);
  11481. RemoveInstruction(hp3);
  11482. if Assigned(hp5) then
  11483. begin
  11484. AsmL.Remove(hp5);
  11485. ASmL.InsertBefore(hp5,hp1)
  11486. end;
  11487. Result:=true;
  11488. end;
  11489. end;
  11490. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  11491. {$ifdef x86_64}
  11492. var
  11493. hp1, hp2, hp3, hp4, hp5: tai;
  11494. {$endif x86_64}
  11495. begin
  11496. Result:=false;
  11497. {$ifdef x86_64}
  11498. hp5:=nil;
  11499. { replace
  11500. push %rax
  11501. call procname
  11502. pop %rcx
  11503. ret
  11504. by
  11505. jmp procname
  11506. but do it only on level 4 because it destroys stack back traces
  11507. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  11508. for all supported calling conventions
  11509. }
  11510. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11511. MatchOpType(taicpu(p),top_reg) and
  11512. (taicpu(p).oper[0]^.reg=NR_RAX) and
  11513. GetNextInstruction(p, hp1) and
  11514. { Take a copy of hp1 }
  11515. SetAndTest(hp1, hp4) and
  11516. { trick to skip label }
  11517. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11518. SkipSimpleInstructions(hp1) and
  11519. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11520. GetNextInstruction(hp1, hp2) and
  11521. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  11522. MatchOpType(taicpu(hp2),top_reg) and
  11523. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  11524. GetNextInstruction(hp2, hp3) and
  11525. { trick to skip label }
  11526. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11527. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11528. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11529. SetAndTest(hp3,hp5) and
  11530. GetNextInstruction(hp3,hp3) and
  11531. MatchInstruction(hp3,A_RET,[S_NO])
  11532. )
  11533. ) and
  11534. (taicpu(hp3).ops=0) then
  11535. begin
  11536. taicpu(hp1).opcode := A_JMP;
  11537. taicpu(hp1).is_jmp := true;
  11538. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  11539. RemoveCurrentP(p, hp4);
  11540. RemoveInstruction(hp2);
  11541. RemoveInstruction(hp3);
  11542. if Assigned(hp5) then
  11543. begin
  11544. AsmL.Remove(hp5);
  11545. ASmL.InsertBefore(hp5,hp1)
  11546. end;
  11547. Result:=true;
  11548. end;
  11549. {$endif x86_64}
  11550. end;
  11551. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  11552. var
  11553. Value, RegName: string;
  11554. begin
  11555. Result:=false;
  11556. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  11557. begin
  11558. case taicpu(p).oper[0]^.val of
  11559. 0:
  11560. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  11561. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11562. begin
  11563. { change "mov $0,%reg" into "xor %reg,%reg" }
  11564. taicpu(p).opcode := A_XOR;
  11565. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  11566. Result := True;
  11567. {$ifdef x86_64}
  11568. end
  11569. else if (taicpu(p).opsize = S_Q) then
  11570. begin
  11571. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11572. { The actual optimization }
  11573. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11574. taicpu(p).changeopsize(S_L);
  11575. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11576. Result := True;
  11577. end;
  11578. $1..$FFFFFFFF:
  11579. begin
  11580. { Code size reduction by J. Gareth "Kit" Moreton }
  11581. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  11582. case taicpu(p).opsize of
  11583. S_Q:
  11584. begin
  11585. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11586. Value := debug_tostr(taicpu(p).oper[0]^.val);
  11587. { The actual optimization }
  11588. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11589. taicpu(p).changeopsize(S_L);
  11590. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11591. Result := True;
  11592. end;
  11593. else
  11594. { Do nothing };
  11595. end;
  11596. {$endif x86_64}
  11597. end;
  11598. -1:
  11599. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  11600. if (cs_opt_size in current_settings.optimizerswitches) and
  11601. (taicpu(p).opsize <> S_B) and
  11602. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11603. begin
  11604. { change "mov $-1,%reg" into "or $-1,%reg" }
  11605. { NOTES:
  11606. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  11607. - This operation creates a false dependency on the register, so only do it when optimising for size
  11608. - 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
  11609. }
  11610. taicpu(p).opcode := A_OR;
  11611. Result := True;
  11612. end;
  11613. else
  11614. { Do nothing };
  11615. end;
  11616. end;
  11617. end;
  11618. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  11619. var
  11620. hp1: tai;
  11621. begin
  11622. { Detect:
  11623. andw x, %ax (0 <= x < $8000)
  11624. ...
  11625. movzwl %ax,%eax
  11626. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11627. }
  11628. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  11629. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11630. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  11631. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11632. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11633. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11634. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11635. begin
  11636. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  11637. taicpu(hp1).opcode := A_CWDE;
  11638. taicpu(hp1).clearop(0);
  11639. taicpu(hp1).clearop(1);
  11640. taicpu(hp1).ops := 0;
  11641. { A change was made, but not with p, so move forward 1 }
  11642. p := tai(p.Next);
  11643. Result := True;
  11644. end;
  11645. end;
  11646. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  11647. begin
  11648. Result := False;
  11649. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  11650. Exit;
  11651. { Convert:
  11652. movswl %ax,%eax -> cwtl
  11653. movslq %eax,%rax -> cdqe
  11654. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  11655. refer to the same opcode and depends only on the assembler's
  11656. current operand-size attribute. [Kit]
  11657. }
  11658. with taicpu(p) do
  11659. case opsize of
  11660. S_WL:
  11661. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  11662. begin
  11663. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  11664. opcode := A_CWDE;
  11665. clearop(0);
  11666. clearop(1);
  11667. ops := 0;
  11668. Result := True;
  11669. end;
  11670. {$ifdef x86_64}
  11671. S_LQ:
  11672. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  11673. begin
  11674. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  11675. opcode := A_CDQE;
  11676. clearop(0);
  11677. clearop(1);
  11678. ops := 0;
  11679. Result := True;
  11680. end;
  11681. {$endif x86_64}
  11682. else
  11683. ;
  11684. end;
  11685. end;
  11686. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  11687. var
  11688. hp1: tai;
  11689. begin
  11690. { Detect:
  11691. shr x, %ax (x > 0)
  11692. ...
  11693. movzwl %ax,%eax
  11694. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11695. }
  11696. Result := False;
  11697. if MatchOpType(taicpu(p), top_const, top_reg) and
  11698. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11699. (taicpu(p).oper[0]^.val > 0) and
  11700. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11701. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11702. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11703. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11704. begin
  11705. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11706. taicpu(hp1).opcode := A_CWDE;
  11707. taicpu(hp1).clearop(0);
  11708. taicpu(hp1).clearop(1);
  11709. taicpu(hp1).ops := 0;
  11710. { A change was made, but not with p, so move forward 1 }
  11711. p := tai(p.Next);
  11712. Result := True;
  11713. end;
  11714. end;
  11715. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11716. var
  11717. hp1, hp2: tai;
  11718. Opposite, SecondOpposite: TAsmOp;
  11719. NewCond: TAsmCond;
  11720. begin
  11721. Result := False;
  11722. { Change:
  11723. add/sub 128,(dest)
  11724. To:
  11725. sub/add -128,(dest)
  11726. This generaally takes fewer bytes to encode because -128 can be stored
  11727. in a signed byte, whereas +128 cannot.
  11728. }
  11729. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11730. begin
  11731. if taicpu(p).opcode = A_ADD then
  11732. Opposite := A_SUB
  11733. else
  11734. Opposite := A_ADD;
  11735. { Be careful if the flags are in use, because the CF flag inverts
  11736. when changing from ADD to SUB and vice versa }
  11737. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11738. GetNextInstruction(p, hp1) then
  11739. begin
  11740. TransferUsedRegs(TmpUsedRegs);
  11741. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11742. hp2 := hp1;
  11743. { Scan ahead to check if everything's safe }
  11744. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11745. begin
  11746. if (hp1.typ <> ait_instruction) then
  11747. { Probably unsafe since the flags are still in use }
  11748. Exit;
  11749. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11750. { Stop searching at an unconditional jump }
  11751. Break;
  11752. if not
  11753. (
  11754. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11755. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11756. ) and
  11757. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11758. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11759. Exit;
  11760. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11761. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11762. { Move to the next instruction }
  11763. GetNextInstruction(hp1, hp1);
  11764. end;
  11765. while Assigned(hp2) and (hp2 <> hp1) do
  11766. begin
  11767. NewCond := C_None;
  11768. case taicpu(hp2).condition of
  11769. C_A, C_NBE:
  11770. NewCond := C_BE;
  11771. C_B, C_C, C_NAE:
  11772. NewCond := C_AE;
  11773. C_AE, C_NB, C_NC:
  11774. NewCond := C_B;
  11775. C_BE, C_NA:
  11776. NewCond := C_A;
  11777. else
  11778. { No change needed };
  11779. end;
  11780. if NewCond <> C_None then
  11781. begin
  11782. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11783. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11784. taicpu(hp2).condition := NewCond;
  11785. end
  11786. else
  11787. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11788. begin
  11789. { Because of the flipping of the carry bit, to ensure
  11790. the operation remains equivalent, ADC becomes SBB
  11791. and vice versa, and the constant is not-inverted.
  11792. If multiple ADCs or SBBs appear in a row, each one
  11793. changed causes the carry bit to invert, so they all
  11794. need to be flipped }
  11795. if taicpu(hp2).opcode = A_ADC then
  11796. SecondOpposite := A_SBB
  11797. else
  11798. SecondOpposite := A_ADC;
  11799. if taicpu(hp2).oper[0]^.typ <> top_const then
  11800. { Should have broken out of this optimisation already }
  11801. InternalError(2021112901);
  11802. 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]^) + ' -> ' +
  11803. 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);
  11804. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11805. taicpu(hp2).opcode := SecondOpposite;
  11806. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11807. end;
  11808. { Move to the next instruction }
  11809. GetNextInstruction(hp2, hp2);
  11810. end;
  11811. if (hp2 <> hp1) then
  11812. InternalError(2021111501);
  11813. end;
  11814. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11815. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11816. taicpu(p).opcode := Opposite;
  11817. taicpu(p).oper[0]^.val := -128;
  11818. { No further optimisations can be made on this instruction, so move
  11819. onto the next one to save time }
  11820. p := tai(p.Next);
  11821. UpdateUsedRegs(p);
  11822. Result := True;
  11823. Exit;
  11824. end;
  11825. { Detect:
  11826. add/sub %reg2,(dest)
  11827. add/sub x, (dest)
  11828. (dest can be a register or a reference)
  11829. Swap the instructions to minimise a pipeline stall. This reverses the
  11830. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11831. optimisations could be made.
  11832. }
  11833. if (taicpu(p).oper[0]^.typ = top_reg) and
  11834. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11835. (
  11836. (
  11837. (taicpu(p).oper[1]^.typ = top_reg) and
  11838. { We can try searching further ahead if we're writing to a register }
  11839. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11840. ) or
  11841. (
  11842. (taicpu(p).oper[1]^.typ = top_ref) and
  11843. GetNextInstruction(p, hp1)
  11844. )
  11845. ) and
  11846. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11847. (taicpu(hp1).oper[0]^.typ = top_const) and
  11848. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11849. begin
  11850. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11851. TransferUsedRegs(TmpUsedRegs);
  11852. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11853. hp2 := p;
  11854. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11855. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11856. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11857. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11858. begin
  11859. asml.remove(hp1);
  11860. asml.InsertBefore(hp1, p);
  11861. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11862. Result := True;
  11863. end;
  11864. end;
  11865. end;
  11866. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11867. begin
  11868. Result:=false;
  11869. { change "cmp $0, %reg" to "test %reg, %reg" }
  11870. if MatchOpType(taicpu(p),top_const,top_reg) and
  11871. (taicpu(p).oper[0]^.val = 0) then
  11872. begin
  11873. taicpu(p).opcode := A_TEST;
  11874. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11875. Result:=true;
  11876. end;
  11877. end;
  11878. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11879. var
  11880. IsTestConstX : Boolean;
  11881. hp1,hp2 : tai;
  11882. begin
  11883. Result:=false;
  11884. { removes the line marked with (x) from the sequence
  11885. and/or/xor/add/sub/... $x, %y
  11886. test/or %y, %y | test $-1, %y (x)
  11887. j(n)z _Label
  11888. as the first instruction already adjusts the ZF
  11889. %y operand may also be a reference }
  11890. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11891. MatchOperand(taicpu(p).oper[0]^,-1);
  11892. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11893. GetLastInstruction(p, hp1) and
  11894. (tai(hp1).typ = ait_instruction) and
  11895. GetNextInstruction(p,hp2) and
  11896. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11897. case taicpu(hp1).opcode Of
  11898. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  11899. { These two instructions set the zero flag if the result is zero }
  11900. A_POPCNT, A_LZCNT:
  11901. begin
  11902. if (
  11903. { With POPCNT, an input of zero will set the zero flag
  11904. because the population count of zero is zero }
  11905. (taicpu(hp1).opcode = A_POPCNT) and
  11906. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  11907. (
  11908. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  11909. { Faster than going through the second half of the 'or'
  11910. condition below }
  11911. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  11912. )
  11913. ) or (
  11914. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  11915. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11916. { and in case of carry for A(E)/B(E)/C/NC }
  11917. (
  11918. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11919. (
  11920. (taicpu(hp1).opcode <> A_ADD) and
  11921. (taicpu(hp1).opcode <> A_SUB) and
  11922. (taicpu(hp1).opcode <> A_LZCNT)
  11923. )
  11924. )
  11925. ) then
  11926. begin
  11927. RemoveCurrentP(p, hp2);
  11928. Result:=true;
  11929. Exit;
  11930. end;
  11931. end;
  11932. A_SHL, A_SAL, A_SHR, A_SAR:
  11933. begin
  11934. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11935. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11936. { therefore, it's only safe to do this optimization for }
  11937. { shifts by a (nonzero) constant }
  11938. (taicpu(hp1).oper[0]^.typ = top_const) and
  11939. (taicpu(hp1).oper[0]^.val <> 0) and
  11940. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11941. { and in case of carry for A(E)/B(E)/C/NC }
  11942. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11943. begin
  11944. RemoveCurrentP(p, hp2);
  11945. Result:=true;
  11946. Exit;
  11947. end;
  11948. end;
  11949. A_DEC, A_INC, A_NEG:
  11950. begin
  11951. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11952. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11953. { and in case of carry for A(E)/B(E)/C/NC }
  11954. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11955. begin
  11956. RemoveCurrentP(p, hp2);
  11957. Result:=true;
  11958. Exit;
  11959. end;
  11960. end
  11961. else
  11962. ;
  11963. end; { case }
  11964. { change "test $-1,%reg" into "test %reg,%reg" }
  11965. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11966. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11967. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11968. if MatchInstruction(p, A_OR, []) and
  11969. { Can only match if they're both registers }
  11970. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11971. begin
  11972. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11973. taicpu(p).opcode := A_TEST;
  11974. { No need to set Result to True, as we've done all the optimisations we can }
  11975. end;
  11976. end;
  11977. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11978. var
  11979. hp1,hp3 : tai;
  11980. {$ifndef x86_64}
  11981. hp2 : taicpu;
  11982. {$endif x86_64}
  11983. begin
  11984. Result:=false;
  11985. hp3:=nil;
  11986. {$ifndef x86_64}
  11987. { don't do this on modern CPUs, this really hurts them due to
  11988. broken call/ret pairing }
  11989. if (current_settings.optimizecputype < cpu_Pentium2) and
  11990. not(cs_create_pic in current_settings.moduleswitches) and
  11991. GetNextInstruction(p, hp1) and
  11992. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11993. MatchOpType(taicpu(hp1),top_ref) and
  11994. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11995. begin
  11996. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  11997. InsertLLItem(p.previous, p, hp2);
  11998. taicpu(p).opcode := A_JMP;
  11999. taicpu(p).is_jmp := true;
  12000. RemoveInstruction(hp1);
  12001. Result:=true;
  12002. end
  12003. else
  12004. {$endif x86_64}
  12005. { replace
  12006. call procname
  12007. ret
  12008. by
  12009. jmp procname
  12010. but do it only on level 4 because it destroys stack back traces
  12011. else if the subroutine is marked as no return, remove the ret
  12012. }
  12013. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  12014. (po_noreturn in current_procinfo.procdef.procoptions)) and
  12015. GetNextInstruction(p, hp1) and
  12016. (MatchInstruction(hp1,A_RET,[S_NO]) or
  12017. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  12018. SetAndTest(hp1,hp3) and
  12019. GetNextInstruction(hp1,hp1) and
  12020. MatchInstruction(hp1,A_RET,[S_NO])
  12021. )
  12022. ) and
  12023. (taicpu(hp1).ops=0) then
  12024. begin
  12025. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12026. { we might destroy stack alignment here if we do not do a call }
  12027. (target_info.stackalign<=sizeof(SizeUInt)) then
  12028. begin
  12029. taicpu(p).opcode := A_JMP;
  12030. taicpu(p).is_jmp := true;
  12031. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  12032. end
  12033. else
  12034. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  12035. RemoveInstruction(hp1);
  12036. if Assigned(hp3) then
  12037. begin
  12038. AsmL.Remove(hp3);
  12039. AsmL.InsertBefore(hp3,p)
  12040. end;
  12041. Result:=true;
  12042. end;
  12043. end;
  12044. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  12045. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  12046. begin
  12047. case OpSize of
  12048. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12049. Result := (Val <= $FF) and (Val >= -128);
  12050. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12051. Result := (Val <= $FFFF) and (Val >= -32768);
  12052. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  12053. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  12054. else
  12055. Result := True;
  12056. end;
  12057. end;
  12058. var
  12059. hp1, hp2 : tai;
  12060. SizeChange: Boolean;
  12061. PreMessage: string;
  12062. begin
  12063. Result := False;
  12064. if (taicpu(p).oper[0]^.typ = top_reg) and
  12065. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12066. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  12067. begin
  12068. { Change (using movzbl %al,%eax as an example):
  12069. movzbl %al, %eax movzbl %al, %eax
  12070. cmpl x, %eax testl %eax,%eax
  12071. To:
  12072. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  12073. movzbl %al, %eax movzbl %al, %eax
  12074. Smaller instruction and minimises pipeline stall as the CPU
  12075. doesn't have to wait for the register to get zero-extended. [Kit]
  12076. Also allow if the smaller of the two registers is being checked,
  12077. as this still removes the false dependency.
  12078. }
  12079. if
  12080. (
  12081. (
  12082. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  12083. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  12084. ) or (
  12085. { If MatchOperand returns True, they must both be registers }
  12086. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  12087. )
  12088. ) and
  12089. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  12090. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  12091. begin
  12092. 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);
  12093. asml.Remove(hp1);
  12094. asml.InsertBefore(hp1, p);
  12095. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  12096. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  12097. begin
  12098. taicpu(hp1).opcode := A_TEST;
  12099. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  12100. end;
  12101. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12102. case taicpu(p).opsize of
  12103. S_BW, S_BL:
  12104. begin
  12105. SizeChange := taicpu(hp1).opsize <> S_B;
  12106. taicpu(hp1).changeopsize(S_B);
  12107. end;
  12108. S_WL:
  12109. begin
  12110. SizeChange := taicpu(hp1).opsize <> S_W;
  12111. taicpu(hp1).changeopsize(S_W);
  12112. end
  12113. else
  12114. InternalError(2020112701);
  12115. end;
  12116. UpdateUsedRegs(tai(p.Next));
  12117. { Check if the register is used aferwards - if not, we can
  12118. remove the movzx instruction completely }
  12119. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  12120. begin
  12121. { Hp1 is a better position than p for debugging purposes }
  12122. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  12123. RemoveCurrentp(p, hp1);
  12124. Result := True;
  12125. end;
  12126. if SizeChange then
  12127. DebugMsg(SPeepholeOptimization + PreMessage +
  12128. 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)
  12129. else
  12130. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  12131. Exit;
  12132. end;
  12133. { Change (using movzwl %ax,%eax as an example):
  12134. movzwl %ax, %eax
  12135. movb %al, (dest) (Register is smaller than read register in movz)
  12136. To:
  12137. movb %al, (dest) (Move one back to avoid a false dependency)
  12138. movzwl %ax, %eax
  12139. }
  12140. if (taicpu(hp1).opcode = A_MOV) and
  12141. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12142. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  12143. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  12144. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  12145. begin
  12146. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  12147. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  12148. asml.Remove(hp1);
  12149. asml.InsertBefore(hp1, p);
  12150. if taicpu(hp1).oper[1]^.typ = top_reg then
  12151. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12152. { Check if the register is used aferwards - if not, we can
  12153. remove the movzx instruction completely }
  12154. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  12155. begin
  12156. { Hp1 is a better position than p for debugging purposes }
  12157. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  12158. RemoveCurrentp(p, hp1);
  12159. Result := True;
  12160. end;
  12161. Exit;
  12162. end;
  12163. end;
  12164. end;
  12165. {$ifdef x86_64}
  12166. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  12167. var
  12168. PreMessage, RegName: string;
  12169. begin
  12170. { Code size reduction by J. Gareth "Kit" Moreton }
  12171. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  12172. as this removes the REX prefix }
  12173. Result := False;
  12174. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  12175. Exit;
  12176. if taicpu(p).oper[0]^.typ <> top_reg then
  12177. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  12178. InternalError(2018011500);
  12179. case taicpu(p).opsize of
  12180. S_Q:
  12181. begin
  12182. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  12183. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  12184. { The actual optimization }
  12185. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12186. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12187. taicpu(p).changeopsize(S_L);
  12188. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  12189. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  12190. end;
  12191. else
  12192. ;
  12193. end;
  12194. end;
  12195. {$endif}
  12196. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  12197. var
  12198. XReg: TRegister;
  12199. begin
  12200. Result := False;
  12201. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  12202. Smaller encoding and slightly faster on some platforms (also works for
  12203. ZMM-sized registers) }
  12204. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  12205. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  12206. begin
  12207. XReg := taicpu(p).oper[0]^.reg;
  12208. if (taicpu(p).oper[1]^.reg = XReg) then
  12209. begin
  12210. taicpu(p).changeopsize(S_XMM);
  12211. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  12212. if (cs_opt_size in current_settings.optimizerswitches) then
  12213. begin
  12214. { Change input registers to %xmm0 to reduce size. Note that
  12215. there's a risk of a false dependency doing this, so only
  12216. optimise for size here }
  12217. XReg := NR_XMM0;
  12218. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  12219. end
  12220. else
  12221. begin
  12222. setsubreg(XReg, R_SUBMMX);
  12223. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  12224. end;
  12225. taicpu(p).oper[0]^.reg := XReg;
  12226. taicpu(p).oper[1]^.reg := XReg;
  12227. Result := True;
  12228. end;
  12229. end;
  12230. end;
  12231. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  12232. var
  12233. OperIdx: Integer;
  12234. begin
  12235. for OperIdx := 0 to p.ops - 1 do
  12236. if p.oper[OperIdx]^.typ = top_ref then
  12237. optimize_ref(p.oper[OperIdx]^.ref^, False);
  12238. end;
  12239. end.