aoptx86.pas 544 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742
  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,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3
  33. );
  34. TX86AsmOptimizer = class(TAsmOptimizer)
  35. { some optimizations are very expensive to check, so the
  36. pre opt pass can be used to set some flags, depending on the found
  37. instructions if it is worth to check a certain optimization }
  38. OptsToCheck : set of TOptsToCheck;
  39. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  40. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  41. function RegReadByInstruction(reg : TRegister; hp : tai) : boolean;
  42. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  43. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  44. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  45. potentially allowing further optimisation (although it might need to know if
  46. it crossed a conditional jump. }
  47. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  48. {
  49. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  50. the use of a register by allocs/dealloc, so it can ignore calls.
  51. In the following example, GetNextInstructionUsingReg will return the second movq,
  52. GetNextInstructionUsingRegTrackingUse won't.
  53. movq %rdi,%rax
  54. # Register rdi released
  55. # Register rdi allocated
  56. movq %rax,%rdi
  57. While in this example:
  58. movq %rdi,%rax
  59. call proc
  60. movq %rdi,%rax
  61. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  62. won't.
  63. }
  64. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  65. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  66. private
  67. function SkipSimpleInstructions(var hp1: tai): Boolean;
  68. protected
  69. class function IsMOVZXAcceptable: Boolean; static; inline;
  70. { Attempts to allocate a volatile integer register for use between p and hp,
  71. using AUsedRegs for the current register usage information. Returns NR_NO
  72. if no free register could be found }
  73. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  74. { Attempts to allocate a volatile MM register for use between p and hp,
  75. using AUsedRegs for the current register usage information. Returns NR_NO
  76. if no free register could be found }
  77. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  78. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  79. function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  80. { checks whether reading the value in reg1 depends on the value of reg2. This
  81. is very similar to SuperRegisterEquals, except it takes into account that
  82. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  83. depend on the value in AH). }
  84. function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  85. { Replaces all references to AOldReg in a memory reference to ANewReg }
  86. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  87. { Replaces all references to AOldReg in an operand to ANewReg }
  88. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  89. { Replaces all references to AOldReg in an instruction to ANewReg,
  90. except where the register is being written }
  91. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  93. or writes to a global symbol }
  94. class function IsRefSafe(const ref: PReference): Boolean; static;
  95. { Returns true if the given MOV instruction can be safely converted to CMOV }
  96. class function CanBeCMOV(p : tai) : boolean; static;
  97. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  98. conversion was successful }
  99. function ConvertLEA(const p : taicpu): Boolean;
  100. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  101. procedure DebugMsg(const s : string; p : tai);inline;
  102. class function IsExitCode(p : tai) : boolean; static;
  103. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  104. procedure RemoveLastDeallocForFuncRes(p : tai);
  105. function DoSubAddOpt(var p : tai) : Boolean;
  106. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  107. function PrePeepholeOptSxx(var p : tai) : boolean;
  108. function PrePeepholeOptIMUL(var p : tai) : boolean;
  109. function PrePeepholeOptAND(var p : tai) : boolean;
  110. function OptPass1Test(var p: tai): boolean;
  111. function OptPass1Add(var p: tai): boolean;
  112. function OptPass1AND(var p : tai) : boolean;
  113. function OptPass1_V_MOVAP(var p : tai) : boolean;
  114. function OptPass1VOP(var p : tai) : boolean;
  115. function OptPass1MOV(var p : tai) : boolean;
  116. function OptPass1Movx(var p : tai) : boolean;
  117. function OptPass1MOVXX(var p : tai) : boolean;
  118. function OptPass1OP(var p : tai) : boolean;
  119. function OptPass1LEA(var p : tai) : boolean;
  120. function OptPass1Sub(var p : tai) : boolean;
  121. function OptPass1SHLSAL(var p : tai) : boolean;
  122. function OptPass1FSTP(var p : tai) : boolean;
  123. function OptPass1FLD(var p : tai) : boolean;
  124. function OptPass1Cmp(var p : tai) : boolean;
  125. function OptPass1PXor(var p : tai) : boolean;
  126. function OptPass1VPXor(var p: tai): boolean;
  127. function OptPass1Imul(var p : tai) : boolean;
  128. function OptPass1Jcc(var p : tai) : boolean;
  129. function OptPass1SHXX(var p: tai): boolean;
  130. function OptPass1VMOVDQ(var p: tai): Boolean;
  131. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  132. function OptPass2Movx(var p : tai): Boolean;
  133. function OptPass2MOV(var p : tai) : boolean;
  134. function OptPass2Imul(var p : tai) : boolean;
  135. function OptPass2Jmp(var p : tai) : boolean;
  136. function OptPass2Jcc(var p : tai) : boolean;
  137. function OptPass2Lea(var p: tai): Boolean;
  138. function OptPass2SUB(var p: tai): Boolean;
  139. function OptPass2ADD(var p : tai): Boolean;
  140. function OptPass2SETcc(var p : tai) : boolean;
  141. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  142. function PostPeepholeOptMov(var p : tai) : Boolean;
  143. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  144. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  145. function PostPeepholeOptXor(var p : tai) : Boolean;
  146. {$endif x86_64}
  147. function PostPeepholeOptAnd(var p : tai) : boolean;
  148. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  149. function PostPeepholeOptCmp(var p : tai) : Boolean;
  150. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  151. function PostPeepholeOptCall(var p : tai) : Boolean;
  152. function PostPeepholeOptLea(var p : tai) : Boolean;
  153. function PostPeepholeOptPush(var p: tai): Boolean;
  154. function PostPeepholeOptShr(var p : tai) : boolean;
  155. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  156. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  157. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  158. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  159. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  160. { Processor-dependent reference optimisation }
  161. class procedure OptimizeRefs(var p: taicpu); static;
  162. end;
  163. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  164. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  165. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  166. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  167. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  168. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  169. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  170. {$if max_operands>2}
  171. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  172. {$endif max_operands>2}
  173. function RefsEqual(const r1, r2: treference): boolean;
  174. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  175. { returns true, if ref is a reference using only the registers passed as base and index
  176. and having an offset }
  177. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  178. implementation
  179. uses
  180. cutils,verbose,
  181. systems,
  182. globals,
  183. cpuinfo,
  184. procinfo,
  185. paramgr,
  186. aasmbase,
  187. aoptbase,aoptutils,
  188. symconst,symsym,
  189. cgx86,
  190. itcpugas;
  191. {$ifdef DEBUG_AOPTCPU}
  192. const
  193. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  194. {$else DEBUG_AOPTCPU}
  195. { Empty strings help the optimizer to remove string concatenations that won't
  196. ever appear to the user on release builds. [Kit] }
  197. const
  198. SPeepholeOptimization = '';
  199. {$endif DEBUG_AOPTCPU}
  200. LIST_STEP_SIZE = 4;
  201. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  202. begin
  203. result :=
  204. (instr.typ = ait_instruction) and
  205. (taicpu(instr).opcode = op) and
  206. ((opsize = []) or (taicpu(instr).opsize in opsize));
  207. end;
  208. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  209. begin
  210. result :=
  211. (instr.typ = ait_instruction) and
  212. ((taicpu(instr).opcode = op1) or
  213. (taicpu(instr).opcode = op2)
  214. ) and
  215. ((opsize = []) or (taicpu(instr).opsize in opsize));
  216. end;
  217. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  218. begin
  219. result :=
  220. (instr.typ = ait_instruction) and
  221. ((taicpu(instr).opcode = op1) or
  222. (taicpu(instr).opcode = op2) or
  223. (taicpu(instr).opcode = op3)
  224. ) and
  225. ((opsize = []) or (taicpu(instr).opsize in opsize));
  226. end;
  227. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  228. const opsize : topsizes) : boolean;
  229. var
  230. op : TAsmOp;
  231. begin
  232. result:=false;
  233. if (instr.typ <> ait_instruction) or
  234. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  235. exit;
  236. for op in ops do
  237. begin
  238. if taicpu(instr).opcode = op then
  239. begin
  240. result:=true;
  241. exit;
  242. end;
  243. end;
  244. end;
  245. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  246. begin
  247. result := (oper.typ = top_reg) and (oper.reg = reg);
  248. end;
  249. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  250. begin
  251. result := (oper.typ = top_const) and (oper.val = a);
  252. end;
  253. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  254. begin
  255. result := oper1.typ = oper2.typ;
  256. if result then
  257. case oper1.typ of
  258. top_const:
  259. Result:=oper1.val = oper2.val;
  260. top_reg:
  261. Result:=oper1.reg = oper2.reg;
  262. top_ref:
  263. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  264. else
  265. internalerror(2013102801);
  266. end
  267. end;
  268. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  269. begin
  270. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  271. if result then
  272. case oper1.typ of
  273. top_const:
  274. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  275. top_reg:
  276. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  277. top_ref:
  278. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  279. else
  280. internalerror(2020052401);
  281. end
  282. end;
  283. function RefsEqual(const r1, r2: treference): boolean;
  284. begin
  285. RefsEqual :=
  286. (r1.offset = r2.offset) and
  287. (r1.segment = r2.segment) and (r1.base = r2.base) and
  288. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  289. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  290. (r1.relsymbol = r2.relsymbol) and
  291. (r1.volatility=[]) and
  292. (r2.volatility=[]);
  293. end;
  294. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  295. begin
  296. Result:=(ref.offset=0) and
  297. (ref.scalefactor in [0,1]) and
  298. (ref.segment=NR_NO) and
  299. (ref.symbol=nil) and
  300. (ref.relsymbol=nil) and
  301. ((base=NR_INVALID) or
  302. (ref.base=base)) and
  303. ((index=NR_INVALID) or
  304. (ref.index=index)) and
  305. (ref.volatility=[]);
  306. end;
  307. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  308. begin
  309. Result:=(ref.scalefactor in [0,1]) and
  310. (ref.segment=NR_NO) and
  311. (ref.symbol=nil) and
  312. (ref.relsymbol=nil) and
  313. ((base=NR_INVALID) or
  314. (ref.base=base)) and
  315. ((index=NR_INVALID) or
  316. (ref.index=index)) and
  317. (ref.volatility=[]);
  318. end;
  319. function InstrReadsFlags(p: tai): boolean;
  320. begin
  321. InstrReadsFlags := true;
  322. case p.typ of
  323. ait_instruction:
  324. if InsProp[taicpu(p).opcode].Ch*
  325. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  326. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  327. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  328. exit;
  329. ait_label:
  330. exit;
  331. else
  332. ;
  333. end;
  334. InstrReadsFlags := false;
  335. end;
  336. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  337. begin
  338. Next:=Current;
  339. repeat
  340. Result:=GetNextInstruction(Next,Next);
  341. until not (Result) or
  342. not(cs_opt_level3 in current_settings.optimizerswitches) or
  343. (Next.typ<>ait_instruction) or
  344. RegInInstruction(reg,Next) or
  345. is_calljmp(taicpu(Next).opcode);
  346. end;
  347. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  348. begin
  349. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  350. Next := Current;
  351. repeat
  352. Result := GetNextInstruction(Next,Next);
  353. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  354. if is_calljmpuncondret(taicpu(Next).opcode) then
  355. begin
  356. Result := False;
  357. Exit;
  358. end
  359. else
  360. CrossJump := True;
  361. until not Result or
  362. not (cs_opt_level3 in current_settings.optimizerswitches) or
  363. (Next.typ <> ait_instruction) or
  364. RegInInstruction(reg,Next);
  365. end;
  366. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  367. begin
  368. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  369. begin
  370. Result:=GetNextInstruction(Current,Next);
  371. exit;
  372. end;
  373. Next:=tai(Current.Next);
  374. Result:=false;
  375. while assigned(Next) do
  376. begin
  377. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  378. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  379. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  380. exit
  381. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  382. begin
  383. Result:=true;
  384. exit;
  385. end;
  386. Next:=tai(Next.Next);
  387. end;
  388. end;
  389. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  390. begin
  391. Result:=RegReadByInstruction(reg,hp);
  392. end;
  393. function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  394. var
  395. p: taicpu;
  396. opcount: longint;
  397. begin
  398. RegReadByInstruction := false;
  399. if hp.typ <> ait_instruction then
  400. exit;
  401. p := taicpu(hp);
  402. case p.opcode of
  403. A_CALL:
  404. regreadbyinstruction := true;
  405. A_IMUL:
  406. case p.ops of
  407. 1:
  408. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  409. (
  410. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  411. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  412. );
  413. 2,3:
  414. regReadByInstruction :=
  415. reginop(reg,p.oper[0]^) or
  416. reginop(reg,p.oper[1]^);
  417. else
  418. InternalError(2019112801);
  419. end;
  420. A_MUL:
  421. begin
  422. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  423. (
  424. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  425. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  426. );
  427. end;
  428. A_IDIV,A_DIV:
  429. begin
  430. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  431. (
  432. (getregtype(reg)=R_INTREGISTER) and
  433. (
  434. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  435. )
  436. );
  437. end;
  438. else
  439. begin
  440. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  441. begin
  442. RegReadByInstruction := false;
  443. exit;
  444. end;
  445. for opcount := 0 to p.ops-1 do
  446. if (p.oper[opCount]^.typ = top_ref) and
  447. RegInRef(reg,p.oper[opcount]^.ref^) then
  448. begin
  449. RegReadByInstruction := true;
  450. exit
  451. end;
  452. { special handling for SSE MOVSD }
  453. if (p.opcode=A_MOVSD) and (p.ops>0) then
  454. begin
  455. if p.ops<>2 then
  456. internalerror(2017042702);
  457. regReadByInstruction := reginop(reg,p.oper[0]^) or
  458. (
  459. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  460. );
  461. exit;
  462. end;
  463. with insprop[p.opcode] do
  464. begin
  465. case getregtype(reg) of
  466. R_INTREGISTER:
  467. begin
  468. case getsupreg(reg) of
  469. RS_EAX:
  470. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  471. begin
  472. RegReadByInstruction := true;
  473. exit
  474. end;
  475. RS_ECX:
  476. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  477. begin
  478. RegReadByInstruction := true;
  479. exit
  480. end;
  481. RS_EDX:
  482. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  483. begin
  484. RegReadByInstruction := true;
  485. exit
  486. end;
  487. RS_EBX:
  488. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  489. begin
  490. RegReadByInstruction := true;
  491. exit
  492. end;
  493. RS_ESP:
  494. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  495. begin
  496. RegReadByInstruction := true;
  497. exit
  498. end;
  499. RS_EBP:
  500. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  501. begin
  502. RegReadByInstruction := true;
  503. exit
  504. end;
  505. RS_ESI:
  506. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  507. begin
  508. RegReadByInstruction := true;
  509. exit
  510. end;
  511. RS_EDI:
  512. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  513. begin
  514. RegReadByInstruction := true;
  515. exit
  516. end;
  517. end;
  518. end;
  519. R_MMREGISTER:
  520. begin
  521. case getsupreg(reg) of
  522. RS_XMM0:
  523. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  524. begin
  525. RegReadByInstruction := true;
  526. exit
  527. end;
  528. end;
  529. end;
  530. else
  531. ;
  532. end;
  533. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  534. begin
  535. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  536. begin
  537. case p.condition of
  538. C_A,C_NBE, { CF=0 and ZF=0 }
  539. C_BE,C_NA: { CF=1 or ZF=1 }
  540. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  541. C_AE,C_NB,C_NC, { CF=0 }
  542. C_B,C_NAE,C_C: { CF=1 }
  543. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  544. C_NE,C_NZ, { ZF=0 }
  545. C_E,C_Z: { ZF=1 }
  546. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  547. C_G,C_NLE, { ZF=0 and SF=OF }
  548. C_LE,C_NG: { ZF=1 or SF<>OF }
  549. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  550. C_GE,C_NL, { SF=OF }
  551. C_L,C_NGE: { SF<>OF }
  552. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  553. C_NO, { OF=0 }
  554. C_O: { OF=1 }
  555. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  556. C_NP,C_PO, { PF=0 }
  557. C_P,C_PE: { PF=1 }
  558. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  559. C_NS, { SF=0 }
  560. C_S: { SF=1 }
  561. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  562. else
  563. internalerror(2017042701);
  564. end;
  565. if RegReadByInstruction then
  566. exit;
  567. end;
  568. case getsubreg(reg) of
  569. R_SUBW,R_SUBD,R_SUBQ:
  570. RegReadByInstruction :=
  571. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  572. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  573. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  574. R_SUBFLAGCARRY:
  575. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  576. R_SUBFLAGPARITY:
  577. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  578. R_SUBFLAGAUXILIARY:
  579. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  580. R_SUBFLAGZERO:
  581. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  582. R_SUBFLAGSIGN:
  583. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  584. R_SUBFLAGOVERFLOW:
  585. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  586. R_SUBFLAGINTERRUPT:
  587. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  588. R_SUBFLAGDIRECTION:
  589. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  590. else
  591. internalerror(2017042601);
  592. end;
  593. exit;
  594. end;
  595. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  596. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  597. (p.oper[0]^.reg=p.oper[1]^.reg) then
  598. exit;
  599. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  600. begin
  601. RegReadByInstruction := true;
  602. exit
  603. end;
  604. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  605. begin
  606. RegReadByInstruction := true;
  607. exit
  608. end;
  609. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  610. begin
  611. RegReadByInstruction := true;
  612. exit
  613. end;
  614. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  615. begin
  616. RegReadByInstruction := true;
  617. exit
  618. end;
  619. end;
  620. end;
  621. end;
  622. end;
  623. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  624. begin
  625. result:=false;
  626. if p1.typ<>ait_instruction then
  627. exit;
  628. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  629. exit(true);
  630. if (getregtype(reg)=R_INTREGISTER) and
  631. { change information for xmm movsd are not correct }
  632. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  633. begin
  634. case getsupreg(reg) of
  635. { RS_EAX = RS_RAX on x86-64 }
  636. RS_EAX:
  637. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  638. RS_ECX:
  639. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  640. RS_EDX:
  641. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  642. RS_EBX:
  643. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  644. RS_ESP:
  645. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  646. RS_EBP:
  647. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  648. RS_ESI:
  649. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  650. RS_EDI:
  651. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  652. else
  653. ;
  654. end;
  655. if result then
  656. exit;
  657. end
  658. else if getregtype(reg)=R_MMREGISTER then
  659. begin
  660. case getsupreg(reg) of
  661. RS_XMM0:
  662. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  663. else
  664. ;
  665. end;
  666. if result then
  667. exit;
  668. end
  669. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  670. begin
  671. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  672. exit(true);
  673. case getsubreg(reg) of
  674. R_SUBFLAGCARRY:
  675. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  676. R_SUBFLAGPARITY:
  677. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  678. R_SUBFLAGAUXILIARY:
  679. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  680. R_SUBFLAGZERO:
  681. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  682. R_SUBFLAGSIGN:
  683. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  684. R_SUBFLAGOVERFLOW:
  685. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  686. R_SUBFLAGINTERRUPT:
  687. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  688. R_SUBFLAGDIRECTION:
  689. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  690. R_SUBW,R_SUBD,R_SUBQ:
  691. { Everything except the direction bits }
  692. Result:=
  693. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  694. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  695. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  696. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  697. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  698. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  699. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  700. else
  701. ;
  702. end;
  703. if result then
  704. exit;
  705. end
  706. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  707. exit(true);
  708. Result:=inherited RegInInstruction(Reg, p1);
  709. end;
  710. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  711. const
  712. WriteOps: array[0..3] of set of TInsChange =
  713. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  714. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  715. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  716. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  717. var
  718. OperIdx: Integer;
  719. begin
  720. Result := False;
  721. if p1.typ <> ait_instruction then
  722. exit;
  723. with insprop[taicpu(p1).opcode] do
  724. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  725. begin
  726. case getsubreg(reg) of
  727. R_SUBW,R_SUBD,R_SUBQ:
  728. Result :=
  729. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  730. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  731. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  732. R_SUBFLAGCARRY:
  733. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  734. R_SUBFLAGPARITY:
  735. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  736. R_SUBFLAGAUXILIARY:
  737. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  738. R_SUBFLAGZERO:
  739. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  740. R_SUBFLAGSIGN:
  741. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  742. R_SUBFLAGOVERFLOW:
  743. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  744. R_SUBFLAGINTERRUPT:
  745. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  746. R_SUBFLAGDIRECTION:
  747. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  748. else
  749. internalerror(2017042602);
  750. end;
  751. exit;
  752. end;
  753. case taicpu(p1).opcode of
  754. A_CALL:
  755. { We could potentially set Result to False if the register in
  756. question is non-volatile for the subroutine's calling convention,
  757. but this would require detecting the calling convention in use and
  758. also assuming that the routine doesn't contain malformed assembly
  759. language, for example... so it could only be done under -O4 as it
  760. would be considered a side-effect. [Kit] }
  761. Result := True;
  762. A_MOVSD:
  763. { special handling for SSE MOVSD }
  764. if (taicpu(p1).ops>0) then
  765. begin
  766. if taicpu(p1).ops<>2 then
  767. internalerror(2017042703);
  768. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  769. end;
  770. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  771. so fix it here (FK)
  772. }
  773. A_VMOVSS,
  774. A_VMOVSD:
  775. begin
  776. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  777. exit;
  778. end;
  779. A_IMUL:
  780. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  781. else
  782. ;
  783. end;
  784. if Result then
  785. exit;
  786. with insprop[taicpu(p1).opcode] do
  787. begin
  788. if getregtype(reg)=R_INTREGISTER then
  789. begin
  790. case getsupreg(reg) of
  791. RS_EAX:
  792. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  793. begin
  794. Result := True;
  795. exit
  796. end;
  797. RS_ECX:
  798. if [Ch_WECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  799. begin
  800. Result := True;
  801. exit
  802. end;
  803. RS_EDX:
  804. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  805. begin
  806. Result := True;
  807. exit
  808. end;
  809. RS_EBX:
  810. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  811. begin
  812. Result := True;
  813. exit
  814. end;
  815. RS_ESP:
  816. if [Ch_WESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  817. begin
  818. Result := True;
  819. exit
  820. end;
  821. RS_EBP:
  822. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  823. begin
  824. Result := True;
  825. exit
  826. end;
  827. RS_ESI:
  828. if [Ch_WESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  829. begin
  830. Result := True;
  831. exit
  832. end;
  833. RS_EDI:
  834. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  835. begin
  836. Result := True;
  837. exit
  838. end;
  839. end;
  840. end;
  841. for OperIdx := 0 to taicpu(p1).ops - 1 do
  842. if (WriteOps[OperIdx]*Ch<>[]) and
  843. { The register doesn't get modified inside a reference }
  844. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  845. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  846. begin
  847. Result := true;
  848. exit
  849. end;
  850. end;
  851. end;
  852. {$ifdef DEBUG_AOPTCPU}
  853. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  854. begin
  855. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  856. end;
  857. function debug_tostr(i: tcgint): string; inline;
  858. begin
  859. Result := tostr(i);
  860. end;
  861. function debug_regname(r: TRegister): string; inline;
  862. begin
  863. Result := '%' + std_regname(r);
  864. end;
  865. { Debug output function - creates a string representation of an operator }
  866. function debug_operstr(oper: TOper): string;
  867. begin
  868. case oper.typ of
  869. top_const:
  870. Result := '$' + debug_tostr(oper.val);
  871. top_reg:
  872. Result := debug_regname(oper.reg);
  873. top_ref:
  874. begin
  875. if oper.ref^.offset <> 0 then
  876. Result := debug_tostr(oper.ref^.offset) + '('
  877. else
  878. Result := '(';
  879. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  880. begin
  881. Result := Result + debug_regname(oper.ref^.base);
  882. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  883. Result := Result + ',' + debug_regname(oper.ref^.index);
  884. end
  885. else
  886. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  887. Result := Result + debug_regname(oper.ref^.index);
  888. if (oper.ref^.scalefactor > 1) then
  889. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  890. else
  891. Result := Result + ')';
  892. end;
  893. else
  894. Result := '[UNKNOWN]';
  895. end;
  896. end;
  897. function debug_op2str(opcode: tasmop): string; inline;
  898. begin
  899. Result := std_op2str[opcode];
  900. end;
  901. function debug_opsize2str(opsize: topsize): string; inline;
  902. begin
  903. Result := gas_opsize2str[opsize];
  904. end;
  905. {$else DEBUG_AOPTCPU}
  906. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  907. begin
  908. end;
  909. function debug_tostr(i: tcgint): string; inline;
  910. begin
  911. Result := '';
  912. end;
  913. function debug_regname(r: TRegister): string; inline;
  914. begin
  915. Result := '';
  916. end;
  917. function debug_operstr(oper: TOper): string; inline;
  918. begin
  919. Result := '';
  920. end;
  921. function debug_op2str(opcode: tasmop): string; inline;
  922. begin
  923. Result := '';
  924. end;
  925. function debug_opsize2str(opsize: topsize): string; inline;
  926. begin
  927. Result := '';
  928. end;
  929. {$endif DEBUG_AOPTCPU}
  930. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  931. begin
  932. {$ifdef x86_64}
  933. { Always fine on x86-64 }
  934. Result := True;
  935. {$else x86_64}
  936. Result :=
  937. {$ifdef i8086}
  938. (current_settings.cputype >= cpu_386) and
  939. {$endif i8086}
  940. (
  941. { Always accept if optimising for size }
  942. (cs_opt_size in current_settings.optimizerswitches) or
  943. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  944. (current_settings.optimizecputype >= cpu_Pentium2)
  945. );
  946. {$endif x86_64}
  947. end;
  948. { Attempts to allocate a volatile integer register for use between p and hp,
  949. using AUsedRegs for the current register usage information. Returns NR_NO
  950. if no free register could be found }
  951. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  952. var
  953. RegSet: TCPURegisterSet;
  954. CurrentSuperReg: Integer;
  955. CurrentReg: TRegister;
  956. Currentp: tai;
  957. Breakout: Boolean;
  958. begin
  959. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  960. Result := NR_NO;
  961. RegSet :=
  962. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  963. current_procinfo.saved_regs_int;
  964. for CurrentSuperReg in RegSet do
  965. begin
  966. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  967. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  968. {$if defined(i386) or defined(i8086)}
  969. { If the target size is 8-bit, make sure we can actually encode it }
  970. and (
  971. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  972. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  973. )
  974. {$endif i386 or i8086}
  975. then
  976. begin
  977. Currentp := p;
  978. Breakout := False;
  979. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  980. begin
  981. case Currentp.typ of
  982. ait_instruction:
  983. begin
  984. if RegInInstruction(CurrentReg, Currentp) then
  985. begin
  986. Breakout := True;
  987. Break;
  988. end;
  989. { Cannot allocate across an unconditional jump }
  990. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  991. Exit;
  992. end;
  993. ait_marker:
  994. { Don't try anything more if a marker is hit }
  995. Exit;
  996. ait_regalloc:
  997. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  998. begin
  999. Breakout := True;
  1000. Break;
  1001. end;
  1002. else
  1003. ;
  1004. end;
  1005. end;
  1006. if Breakout then
  1007. { Try the next register }
  1008. Continue;
  1009. { We have a free register available }
  1010. Result := CurrentReg;
  1011. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1012. Exit;
  1013. end;
  1014. end;
  1015. end;
  1016. { Attempts to allocate a volatile MM register for use between p and hp,
  1017. using AUsedRegs for the current register usage information. Returns NR_NO
  1018. if no free register could be found }
  1019. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1020. var
  1021. RegSet: TCPURegisterSet;
  1022. CurrentSuperReg: Integer;
  1023. CurrentReg: TRegister;
  1024. Currentp: tai;
  1025. Breakout: Boolean;
  1026. begin
  1027. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  1028. Result := NR_NO;
  1029. RegSet :=
  1030. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1031. current_procinfo.saved_regs_mm;
  1032. for CurrentSuperReg in RegSet do
  1033. begin
  1034. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1035. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1036. begin
  1037. Currentp := p;
  1038. Breakout := False;
  1039. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1040. begin
  1041. case Currentp.typ of
  1042. ait_instruction:
  1043. begin
  1044. if RegInInstruction(CurrentReg, Currentp) then
  1045. begin
  1046. Breakout := True;
  1047. Break;
  1048. end;
  1049. { Cannot allocate across an unconditional jump }
  1050. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1051. Exit;
  1052. end;
  1053. ait_marker:
  1054. { Don't try anything more if a marker is hit }
  1055. Exit;
  1056. ait_regalloc:
  1057. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1058. begin
  1059. Breakout := True;
  1060. Break;
  1061. end;
  1062. else
  1063. ;
  1064. end;
  1065. end;
  1066. if Breakout then
  1067. { Try the next register }
  1068. Continue;
  1069. { We have a free register available }
  1070. Result := CurrentReg;
  1071. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1072. Exit;
  1073. end;
  1074. end;
  1075. end;
  1076. function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1077. begin
  1078. if not SuperRegistersEqual(reg1,reg2) then
  1079. exit(false);
  1080. if getregtype(reg1)<>R_INTREGISTER then
  1081. exit(true); {because SuperRegisterEqual is true}
  1082. case getsubreg(reg1) of
  1083. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1084. higher, it preserves the high bits, so the new value depends on
  1085. reg2's previous value. In other words, it is equivalent to doing:
  1086. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1087. R_SUBL:
  1088. exit(getsubreg(reg2)=R_SUBL);
  1089. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1090. higher, it actually does a:
  1091. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1092. R_SUBH:
  1093. exit(getsubreg(reg2)=R_SUBH);
  1094. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1095. bits of reg2:
  1096. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1097. R_SUBW:
  1098. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1099. { a write to R_SUBD always overwrites every other subregister,
  1100. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1101. R_SUBD,
  1102. R_SUBQ:
  1103. exit(true);
  1104. else
  1105. internalerror(2017042801);
  1106. end;
  1107. end;
  1108. function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1109. begin
  1110. if not SuperRegistersEqual(reg1,reg2) then
  1111. exit(false);
  1112. if getregtype(reg1)<>R_INTREGISTER then
  1113. exit(true); {because SuperRegisterEqual is true}
  1114. case getsubreg(reg1) of
  1115. R_SUBL:
  1116. exit(getsubreg(reg2)<>R_SUBH);
  1117. R_SUBH:
  1118. exit(getsubreg(reg2)<>R_SUBL);
  1119. R_SUBW,
  1120. R_SUBD,
  1121. R_SUBQ:
  1122. exit(true);
  1123. else
  1124. internalerror(2017042802);
  1125. end;
  1126. end;
  1127. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1128. var
  1129. hp1 : tai;
  1130. l : TCGInt;
  1131. begin
  1132. result:=false;
  1133. { changes the code sequence
  1134. shr/sar const1, x
  1135. shl const2, x
  1136. to
  1137. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1138. if GetNextInstruction(p, hp1) and
  1139. MatchInstruction(hp1,A_SHL,[]) and
  1140. (taicpu(p).oper[0]^.typ = top_const) and
  1141. (taicpu(hp1).oper[0]^.typ = top_const) and
  1142. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1143. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1144. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1145. begin
  1146. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1147. not(cs_opt_size in current_settings.optimizerswitches) then
  1148. begin
  1149. { shr/sar const1, %reg
  1150. shl const2, %reg
  1151. with const1 > const2 }
  1152. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1153. taicpu(hp1).opcode := A_AND;
  1154. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1155. case taicpu(p).opsize Of
  1156. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1157. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1158. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1159. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1160. else
  1161. Internalerror(2017050703)
  1162. end;
  1163. end
  1164. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1165. not(cs_opt_size in current_settings.optimizerswitches) then
  1166. begin
  1167. { shr/sar const1, %reg
  1168. shl const2, %reg
  1169. with const1 < const2 }
  1170. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1171. taicpu(p).opcode := A_AND;
  1172. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1173. case taicpu(p).opsize Of
  1174. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1175. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1176. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1177. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1178. else
  1179. Internalerror(2017050702)
  1180. end;
  1181. end
  1182. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1183. begin
  1184. { shr/sar const1, %reg
  1185. shl const2, %reg
  1186. with const1 = const2 }
  1187. taicpu(p).opcode := A_AND;
  1188. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1189. case taicpu(p).opsize Of
  1190. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1191. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1192. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1193. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1194. else
  1195. Internalerror(2017050701)
  1196. end;
  1197. RemoveInstruction(hp1);
  1198. end;
  1199. end;
  1200. end;
  1201. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1202. var
  1203. opsize : topsize;
  1204. hp1 : tai;
  1205. tmpref : treference;
  1206. ShiftValue : Cardinal;
  1207. BaseValue : TCGInt;
  1208. begin
  1209. result:=false;
  1210. opsize:=taicpu(p).opsize;
  1211. { changes certain "imul const, %reg"'s to lea sequences }
  1212. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1213. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1214. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1215. if (taicpu(p).oper[0]^.val = 1) then
  1216. if (taicpu(p).ops = 2) then
  1217. { remove "imul $1, reg" }
  1218. begin
  1219. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1220. Result := RemoveCurrentP(p);
  1221. end
  1222. else
  1223. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1224. begin
  1225. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1226. InsertLLItem(p.previous, p.next, hp1);
  1227. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1228. p.free;
  1229. p := hp1;
  1230. end
  1231. else if ((taicpu(p).ops <= 2) or
  1232. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1233. not(cs_opt_size in current_settings.optimizerswitches) and
  1234. (not(GetNextInstruction(p, hp1)) or
  1235. not((tai(hp1).typ = ait_instruction) and
  1236. ((taicpu(hp1).opcode=A_Jcc) and
  1237. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1238. begin
  1239. {
  1240. imul X, reg1, reg2 to
  1241. lea (reg1,reg1,Y), reg2
  1242. shl ZZ,reg2
  1243. imul XX, reg1 to
  1244. lea (reg1,reg1,YY), reg1
  1245. shl ZZ,reg2
  1246. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1247. it does not exist as a separate optimization target in FPC though.
  1248. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1249. at most two zeros
  1250. }
  1251. reference_reset(tmpref,1,[]);
  1252. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1253. begin
  1254. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1255. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1256. TmpRef.base := taicpu(p).oper[1]^.reg;
  1257. TmpRef.index := taicpu(p).oper[1]^.reg;
  1258. if not(BaseValue in [3,5,9]) then
  1259. Internalerror(2018110101);
  1260. TmpRef.ScaleFactor := BaseValue-1;
  1261. if (taicpu(p).ops = 2) then
  1262. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1263. else
  1264. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1265. AsmL.InsertAfter(hp1,p);
  1266. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1267. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1268. RemoveCurrentP(p, hp1);
  1269. if ShiftValue>0 then
  1270. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1271. end;
  1272. end;
  1273. end;
  1274. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1275. begin
  1276. Result := False;
  1277. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1278. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1279. begin
  1280. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1281. taicpu(p).opcode := A_MOV;
  1282. Result := True;
  1283. end;
  1284. end;
  1285. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1286. var
  1287. p: taicpu absolute hp;
  1288. i: Integer;
  1289. begin
  1290. Result := False;
  1291. if not assigned(hp) or
  1292. (hp.typ <> ait_instruction) then
  1293. Exit;
  1294. // p := taicpu(hp);
  1295. Prefetch(insprop[p.opcode]);
  1296. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1297. with insprop[p.opcode] do
  1298. begin
  1299. case getsubreg(reg) of
  1300. R_SUBW,R_SUBD,R_SUBQ:
  1301. Result:=
  1302. RegLoadedWithNewValue(NR_CARRYFLAG,hp) and
  1303. RegLoadedWithNewValue(NR_PARITYFLAG,hp) and
  1304. RegLoadedWithNewValue(NR_AUXILIARYFLAG,hp) and
  1305. RegLoadedWithNewValue(NR_ZEROFLAG,hp) and
  1306. RegLoadedWithNewValue(NR_SIGNFLAG,hp) and
  1307. RegLoadedWithNewValue(NR_OVERFLOWFLAG,hp);
  1308. R_SUBFLAGCARRY:
  1309. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1310. R_SUBFLAGPARITY:
  1311. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1312. R_SUBFLAGAUXILIARY:
  1313. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1314. R_SUBFLAGZERO:
  1315. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1316. R_SUBFLAGSIGN:
  1317. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1318. R_SUBFLAGOVERFLOW:
  1319. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1320. R_SUBFLAGINTERRUPT:
  1321. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1322. R_SUBFLAGDIRECTION:
  1323. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1324. else
  1325. begin
  1326. writeln(getsubreg(reg));
  1327. internalerror(2017050501);
  1328. end;
  1329. end;
  1330. exit;
  1331. end;
  1332. { Handle special cases first }
  1333. case p.opcode of
  1334. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1335. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1336. begin
  1337. Result :=
  1338. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1339. (p.oper[1]^.typ = top_reg) and
  1340. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1341. (
  1342. (p.oper[0]^.typ = top_const) or
  1343. (
  1344. (p.oper[0]^.typ = top_reg) and
  1345. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1346. ) or (
  1347. (p.oper[0]^.typ = top_ref) and
  1348. not RegInRef(reg,p.oper[0]^.ref^)
  1349. )
  1350. );
  1351. end;
  1352. A_MUL, A_IMUL:
  1353. Result :=
  1354. (
  1355. (p.ops=3) and { IMUL only }
  1356. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1357. (
  1358. (
  1359. (p.oper[1]^.typ=top_reg) and
  1360. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1361. ) or (
  1362. (p.oper[1]^.typ=top_ref) and
  1363. not RegInRef(reg,p.oper[1]^.ref^)
  1364. )
  1365. )
  1366. ) or (
  1367. (
  1368. (p.ops=1) and
  1369. (
  1370. (
  1371. (
  1372. (p.oper[0]^.typ=top_reg) and
  1373. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1374. )
  1375. ) or (
  1376. (p.oper[0]^.typ=top_ref) and
  1377. not RegInRef(reg,p.oper[0]^.ref^)
  1378. )
  1379. ) and (
  1380. (
  1381. (p.opsize=S_B) and
  1382. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1383. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1384. ) or (
  1385. (p.opsize=S_W) and
  1386. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1387. ) or (
  1388. (p.opsize=S_L) and
  1389. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1390. {$ifdef x86_64}
  1391. ) or (
  1392. (p.opsize=S_Q) and
  1393. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1394. {$endif x86_64}
  1395. )
  1396. )
  1397. )
  1398. );
  1399. A_CBW:
  1400. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1401. {$ifndef x86_64}
  1402. A_LDS:
  1403. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1404. A_LES:
  1405. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1406. {$endif not x86_64}
  1407. A_LFS:
  1408. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1409. A_LGS:
  1410. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1411. A_LSS:
  1412. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1413. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1414. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1415. A_LODSB:
  1416. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1417. A_LODSW:
  1418. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1419. {$ifdef x86_64}
  1420. A_LODSQ:
  1421. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1422. {$endif x86_64}
  1423. A_LODSD:
  1424. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1425. A_FSTSW, A_FNSTSW:
  1426. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1427. else
  1428. begin
  1429. with insprop[p.opcode] do
  1430. begin
  1431. if (
  1432. { xor %reg,%reg etc. is classed as a new value }
  1433. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1434. MatchOpType(p, top_reg, top_reg) and
  1435. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1436. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1437. ) then
  1438. begin
  1439. Result := True;
  1440. Exit;
  1441. end;
  1442. { Make sure the entire register is overwritten }
  1443. if (getregtype(reg) = R_INTREGISTER) then
  1444. begin
  1445. if (p.ops > 0) then
  1446. begin
  1447. if RegInOp(reg, p.oper[0]^) then
  1448. begin
  1449. if (p.oper[0]^.typ = top_ref) then
  1450. begin
  1451. if RegInRef(reg, p.oper[0]^.ref^) then
  1452. begin
  1453. Result := False;
  1454. Exit;
  1455. end;
  1456. end
  1457. else if (p.oper[0]^.typ = top_reg) then
  1458. begin
  1459. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1460. begin
  1461. Result := False;
  1462. Exit;
  1463. end
  1464. else if ([Ch_WOp1]*Ch<>[]) then
  1465. begin
  1466. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1467. Result := True
  1468. else
  1469. begin
  1470. Result := False;
  1471. Exit;
  1472. end;
  1473. end;
  1474. end;
  1475. end;
  1476. if (p.ops > 1) then
  1477. begin
  1478. if RegInOp(reg, p.oper[1]^) then
  1479. begin
  1480. if (p.oper[1]^.typ = top_ref) then
  1481. begin
  1482. if RegInRef(reg, p.oper[1]^.ref^) then
  1483. begin
  1484. Result := False;
  1485. Exit;
  1486. end;
  1487. end
  1488. else if (p.oper[1]^.typ = top_reg) then
  1489. begin
  1490. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1491. begin
  1492. Result := False;
  1493. Exit;
  1494. end
  1495. else if ([Ch_WOp2]*Ch<>[]) then
  1496. begin
  1497. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1498. Result := True
  1499. else
  1500. begin
  1501. Result := False;
  1502. Exit;
  1503. end;
  1504. end;
  1505. end;
  1506. end;
  1507. if (p.ops > 2) then
  1508. begin
  1509. if RegInOp(reg, p.oper[2]^) then
  1510. begin
  1511. if (p.oper[2]^.typ = top_ref) then
  1512. begin
  1513. if RegInRef(reg, p.oper[2]^.ref^) then
  1514. begin
  1515. Result := False;
  1516. Exit;
  1517. end;
  1518. end
  1519. else if (p.oper[2]^.typ = top_reg) then
  1520. begin
  1521. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1522. begin
  1523. Result := False;
  1524. Exit;
  1525. end
  1526. else if ([Ch_WOp3]*Ch<>[]) then
  1527. begin
  1528. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1529. Result := True
  1530. else
  1531. begin
  1532. Result := False;
  1533. Exit;
  1534. end;
  1535. end;
  1536. end;
  1537. end;
  1538. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1539. begin
  1540. if (p.oper[3]^.typ = top_ref) then
  1541. begin
  1542. if RegInRef(reg, p.oper[3]^.ref^) then
  1543. begin
  1544. Result := False;
  1545. Exit;
  1546. end;
  1547. end
  1548. else if (p.oper[3]^.typ = top_reg) then
  1549. begin
  1550. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1551. begin
  1552. Result := False;
  1553. Exit;
  1554. end
  1555. else if ([Ch_WOp4]*Ch<>[]) then
  1556. begin
  1557. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1558. Result := True
  1559. else
  1560. begin
  1561. Result := False;
  1562. Exit;
  1563. end;
  1564. end;
  1565. end;
  1566. end;
  1567. end;
  1568. end;
  1569. end;
  1570. { Don't do these ones first in case an input operand is equal to an explicit output registers }
  1571. case getsupreg(reg) of
  1572. RS_EAX:
  1573. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1574. begin
  1575. Result := True;
  1576. Exit;
  1577. end;
  1578. RS_ECX:
  1579. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1580. begin
  1581. Result := True;
  1582. Exit;
  1583. end;
  1584. RS_EDX:
  1585. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1586. begin
  1587. Result := True;
  1588. Exit;
  1589. end;
  1590. RS_EBX:
  1591. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1592. begin
  1593. Result := True;
  1594. Exit;
  1595. end;
  1596. RS_ESP:
  1597. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1598. begin
  1599. Result := True;
  1600. Exit;
  1601. end;
  1602. RS_EBP:
  1603. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1604. begin
  1605. Result := True;
  1606. Exit;
  1607. end;
  1608. RS_ESI:
  1609. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1610. begin
  1611. Result := True;
  1612. Exit;
  1613. end;
  1614. RS_EDI:
  1615. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1616. begin
  1617. Result := True;
  1618. Exit;
  1619. end;
  1620. else
  1621. ;
  1622. end;
  1623. end;
  1624. end;
  1625. end;
  1626. end;
  1627. end;
  1628. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1629. var
  1630. hp2,hp3 : tai;
  1631. begin
  1632. { some x86-64 issue a NOP before the real exit code }
  1633. if MatchInstruction(p,A_NOP,[]) then
  1634. GetNextInstruction(p,p);
  1635. result:=assigned(p) and (p.typ=ait_instruction) and
  1636. ((taicpu(p).opcode = A_RET) or
  1637. ((taicpu(p).opcode=A_LEAVE) and
  1638. GetNextInstruction(p,hp2) and
  1639. MatchInstruction(hp2,A_RET,[S_NO])
  1640. ) or
  1641. (((taicpu(p).opcode=A_LEA) and
  1642. MatchOpType(taicpu(p),top_ref,top_reg) and
  1643. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1644. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1645. ) and
  1646. GetNextInstruction(p,hp2) and
  1647. MatchInstruction(hp2,A_RET,[S_NO])
  1648. ) or
  1649. ((((taicpu(p).opcode=A_MOV) and
  1650. MatchOpType(taicpu(p),top_reg,top_reg) and
  1651. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1652. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1653. ((taicpu(p).opcode=A_LEA) and
  1654. MatchOpType(taicpu(p),top_ref,top_reg) and
  1655. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1656. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1657. )
  1658. ) and
  1659. GetNextInstruction(p,hp2) and
  1660. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1661. MatchOpType(taicpu(hp2),top_reg) and
  1662. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1663. GetNextInstruction(hp2,hp3) and
  1664. MatchInstruction(hp3,A_RET,[S_NO])
  1665. )
  1666. );
  1667. end;
  1668. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1669. begin
  1670. isFoldableArithOp := False;
  1671. case hp1.opcode of
  1672. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1673. isFoldableArithOp :=
  1674. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1675. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1676. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1677. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1678. (taicpu(hp1).oper[1]^.reg = reg);
  1679. A_INC,A_DEC,A_NEG,A_NOT:
  1680. isFoldableArithOp :=
  1681. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1682. (taicpu(hp1).oper[0]^.reg = reg);
  1683. else
  1684. ;
  1685. end;
  1686. end;
  1687. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1688. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1689. var
  1690. hp2: tai;
  1691. begin
  1692. hp2 := p;
  1693. repeat
  1694. hp2 := tai(hp2.previous);
  1695. if assigned(hp2) and
  1696. (hp2.typ = ait_regalloc) and
  1697. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1698. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1699. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1700. begin
  1701. RemoveInstruction(hp2);
  1702. break;
  1703. end;
  1704. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1705. end;
  1706. begin
  1707. case current_procinfo.procdef.returndef.typ of
  1708. arraydef,recorddef,pointerdef,
  1709. stringdef,enumdef,procdef,objectdef,errordef,
  1710. filedef,setdef,procvardef,
  1711. classrefdef,forwarddef:
  1712. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1713. orddef:
  1714. if current_procinfo.procdef.returndef.size <> 0 then
  1715. begin
  1716. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1717. { for int64/qword }
  1718. if current_procinfo.procdef.returndef.size = 8 then
  1719. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1720. end;
  1721. else
  1722. ;
  1723. end;
  1724. end;
  1725. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1726. var
  1727. hp1,hp2 : tai;
  1728. begin
  1729. result:=false;
  1730. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1731. begin
  1732. { vmova* reg1,reg1
  1733. =>
  1734. <nop> }
  1735. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1736. begin
  1737. RemoveCurrentP(p);
  1738. result:=true;
  1739. exit;
  1740. end
  1741. else if GetNextInstruction(p,hp1) then
  1742. begin
  1743. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1744. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1745. begin
  1746. { vmova* reg1,reg2
  1747. vmova* reg2,reg3
  1748. dealloc reg2
  1749. =>
  1750. vmova* reg1,reg3 }
  1751. TransferUsedRegs(TmpUsedRegs);
  1752. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1753. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1754. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1755. begin
  1756. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1757. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1758. RemoveInstruction(hp1);
  1759. result:=true;
  1760. exit;
  1761. end
  1762. { special case:
  1763. vmova* reg1,<op>
  1764. vmova* <op>,reg1
  1765. =>
  1766. vmova* reg1,<op> }
  1767. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1768. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1769. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1770. ) then
  1771. begin
  1772. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1773. RemoveInstruction(hp1);
  1774. result:=true;
  1775. exit;
  1776. end
  1777. end
  1778. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1779. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1780. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1781. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1782. ) and
  1783. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1784. begin
  1785. { vmova* reg1,reg2
  1786. vmovs* reg2,<op>
  1787. dealloc reg2
  1788. =>
  1789. vmovs* reg1,reg3 }
  1790. TransferUsedRegs(TmpUsedRegs);
  1791. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1792. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1793. begin
  1794. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1795. taicpu(p).opcode:=taicpu(hp1).opcode;
  1796. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1797. RemoveInstruction(hp1);
  1798. result:=true;
  1799. exit;
  1800. end
  1801. end;
  1802. end;
  1803. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1804. begin
  1805. if MatchInstruction(hp1,[A_VFMADDPD,
  1806. A_VFMADD132PD,
  1807. A_VFMADD132PS,
  1808. A_VFMADD132SD,
  1809. A_VFMADD132SS,
  1810. A_VFMADD213PD,
  1811. A_VFMADD213PS,
  1812. A_VFMADD213SD,
  1813. A_VFMADD213SS,
  1814. A_VFMADD231PD,
  1815. A_VFMADD231PS,
  1816. A_VFMADD231SD,
  1817. A_VFMADD231SS,
  1818. A_VFMADDSUB132PD,
  1819. A_VFMADDSUB132PS,
  1820. A_VFMADDSUB213PD,
  1821. A_VFMADDSUB213PS,
  1822. A_VFMADDSUB231PD,
  1823. A_VFMADDSUB231PS,
  1824. A_VFMSUB132PD,
  1825. A_VFMSUB132PS,
  1826. A_VFMSUB132SD,
  1827. A_VFMSUB132SS,
  1828. A_VFMSUB213PD,
  1829. A_VFMSUB213PS,
  1830. A_VFMSUB213SD,
  1831. A_VFMSUB213SS,
  1832. A_VFMSUB231PD,
  1833. A_VFMSUB231PS,
  1834. A_VFMSUB231SD,
  1835. A_VFMSUB231SS,
  1836. A_VFMSUBADD132PD,
  1837. A_VFMSUBADD132PS,
  1838. A_VFMSUBADD213PD,
  1839. A_VFMSUBADD213PS,
  1840. A_VFMSUBADD231PD,
  1841. A_VFMSUBADD231PS,
  1842. A_VFNMADD132PD,
  1843. A_VFNMADD132PS,
  1844. A_VFNMADD132SD,
  1845. A_VFNMADD132SS,
  1846. A_VFNMADD213PD,
  1847. A_VFNMADD213PS,
  1848. A_VFNMADD213SD,
  1849. A_VFNMADD213SS,
  1850. A_VFNMADD231PD,
  1851. A_VFNMADD231PS,
  1852. A_VFNMADD231SD,
  1853. A_VFNMADD231SS,
  1854. A_VFNMSUB132PD,
  1855. A_VFNMSUB132PS,
  1856. A_VFNMSUB132SD,
  1857. A_VFNMSUB132SS,
  1858. A_VFNMSUB213PD,
  1859. A_VFNMSUB213PS,
  1860. A_VFNMSUB213SD,
  1861. A_VFNMSUB213SS,
  1862. A_VFNMSUB231PD,
  1863. A_VFNMSUB231PS,
  1864. A_VFNMSUB231SD,
  1865. A_VFNMSUB231SS],[S_NO]) and
  1866. { we mix single and double opperations here because we assume that the compiler
  1867. generates vmovapd only after double operations and vmovaps only after single operations }
  1868. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1869. GetNextInstruction(hp1,hp2) and
  1870. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1871. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1872. begin
  1873. TransferUsedRegs(TmpUsedRegs);
  1874. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1875. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1876. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1877. begin
  1878. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1879. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1880. RemoveInstruction(hp2);
  1881. end;
  1882. end
  1883. else if (hp1.typ = ait_instruction) and
  1884. GetNextInstruction(hp1, hp2) and
  1885. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1886. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1887. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1888. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1889. (((taicpu(p).opcode=A_MOVAPS) and
  1890. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1891. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1892. ((taicpu(p).opcode=A_MOVAPD) and
  1893. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1894. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1895. ) then
  1896. { change
  1897. movapX reg,reg2
  1898. addsX/subsX/... reg3, reg2
  1899. movapX reg2,reg
  1900. to
  1901. addsX/subsX/... reg3,reg
  1902. }
  1903. begin
  1904. TransferUsedRegs(TmpUsedRegs);
  1905. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1906. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1907. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1908. begin
  1909. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1910. debug_op2str(taicpu(p).opcode)+' '+
  1911. debug_op2str(taicpu(hp1).opcode)+' '+
  1912. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1913. { we cannot eliminate the first move if
  1914. the operations uses the same register for source and dest }
  1915. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1916. RemoveCurrentP(p, nil);
  1917. p:=hp1;
  1918. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1919. RemoveInstruction(hp2);
  1920. result:=true;
  1921. end;
  1922. end;
  1923. end;
  1924. end;
  1925. end;
  1926. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1927. var
  1928. hp1 : tai;
  1929. begin
  1930. result:=false;
  1931. { replace
  1932. V<Op>X %mreg1,%mreg2,%mreg3
  1933. VMovX %mreg3,%mreg4
  1934. dealloc %mreg3
  1935. by
  1936. V<Op>X %mreg1,%mreg2,%mreg4
  1937. ?
  1938. }
  1939. if GetNextInstruction(p,hp1) and
  1940. { we mix single and double operations here because we assume that the compiler
  1941. generates vmovapd only after double operations and vmovaps only after single operations }
  1942. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1943. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1944. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1945. begin
  1946. TransferUsedRegs(TmpUsedRegs);
  1947. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1948. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1949. begin
  1950. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1951. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1952. RemoveInstruction(hp1);
  1953. result:=true;
  1954. end;
  1955. end;
  1956. end;
  1957. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1958. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1959. begin
  1960. Result := False;
  1961. { For safety reasons, only check for exact register matches }
  1962. { Check base register }
  1963. if (ref.base = AOldReg) then
  1964. begin
  1965. ref.base := ANewReg;
  1966. Result := True;
  1967. end;
  1968. { Check index register }
  1969. if (ref.index = AOldReg) then
  1970. begin
  1971. ref.index := ANewReg;
  1972. Result := True;
  1973. end;
  1974. end;
  1975. { Replaces all references to AOldReg in an operand to ANewReg }
  1976. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  1977. var
  1978. OldSupReg, NewSupReg: TSuperRegister;
  1979. OldSubReg, NewSubReg: TSubRegister;
  1980. OldRegType: TRegisterType;
  1981. ThisOper: POper;
  1982. begin
  1983. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  1984. Result := False;
  1985. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  1986. InternalError(2020011801);
  1987. OldSupReg := getsupreg(AOldReg);
  1988. OldSubReg := getsubreg(AOldReg);
  1989. OldRegType := getregtype(AOldReg);
  1990. NewSupReg := getsupreg(ANewReg);
  1991. NewSubReg := getsubreg(ANewReg);
  1992. if OldRegType <> getregtype(ANewReg) then
  1993. InternalError(2020011802);
  1994. if OldSubReg <> NewSubReg then
  1995. InternalError(2020011803);
  1996. case ThisOper^.typ of
  1997. top_reg:
  1998. if (
  1999. (ThisOper^.reg = AOldReg) or
  2000. (
  2001. (OldRegType = R_INTREGISTER) and
  2002. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2003. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2004. (
  2005. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2006. {$ifndef x86_64}
  2007. and (
  2008. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2009. don't have an 8-bit representation }
  2010. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2011. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2012. )
  2013. {$endif x86_64}
  2014. )
  2015. )
  2016. ) then
  2017. begin
  2018. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2019. Result := True;
  2020. end;
  2021. top_ref:
  2022. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2023. Result := True;
  2024. else
  2025. ;
  2026. end;
  2027. end;
  2028. { Replaces all references to AOldReg in an instruction to ANewReg }
  2029. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2030. const
  2031. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2032. var
  2033. OperIdx: Integer;
  2034. begin
  2035. Result := False;
  2036. for OperIdx := 0 to p.ops - 1 do
  2037. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2038. begin
  2039. { The shift and rotate instructions can only use CL }
  2040. if not (
  2041. (OperIdx = 0) and
  2042. { This second condition just helps to avoid unnecessarily
  2043. calling MatchInstruction for 10 different opcodes }
  2044. (p.oper[0]^.reg = NR_CL) and
  2045. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2046. ) then
  2047. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2048. end
  2049. else if p.oper[OperIdx]^.typ = top_ref then
  2050. { It's okay to replace registers in references that get written to }
  2051. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2052. end;
  2053. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2054. begin
  2055. with ref^ do
  2056. Result :=
  2057. (index = NR_NO) and
  2058. (
  2059. {$ifdef x86_64}
  2060. (
  2061. (base = NR_RIP) and
  2062. (refaddr in [addr_pic, addr_pic_no_got])
  2063. ) or
  2064. {$endif x86_64}
  2065. (base = NR_STACK_POINTER_REG) or
  2066. (base = current_procinfo.framepointer)
  2067. );
  2068. end;
  2069. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2070. var
  2071. l: asizeint;
  2072. begin
  2073. Result := False;
  2074. { Should have been checked previously }
  2075. if p.opcode <> A_LEA then
  2076. InternalError(2020072501);
  2077. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2078. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2079. not(cs_opt_size in current_settings.optimizerswitches) then
  2080. exit;
  2081. with p.oper[0]^.ref^ do
  2082. begin
  2083. if (base <> p.oper[1]^.reg) or
  2084. (index <> NR_NO) or
  2085. assigned(symbol) then
  2086. exit;
  2087. l:=offset;
  2088. if (l=1) and UseIncDec then
  2089. begin
  2090. p.opcode:=A_INC;
  2091. p.loadreg(0,p.oper[1]^.reg);
  2092. p.ops:=1;
  2093. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2094. end
  2095. else if (l=-1) and UseIncDec then
  2096. begin
  2097. p.opcode:=A_DEC;
  2098. p.loadreg(0,p.oper[1]^.reg);
  2099. p.ops:=1;
  2100. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2101. end
  2102. else
  2103. begin
  2104. if (l<0) and (l<>-2147483648) then
  2105. begin
  2106. p.opcode:=A_SUB;
  2107. p.loadConst(0,-l);
  2108. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2109. end
  2110. else
  2111. begin
  2112. p.opcode:=A_ADD;
  2113. p.loadConst(0,l);
  2114. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2115. end;
  2116. end;
  2117. end;
  2118. Result := True;
  2119. end;
  2120. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2121. var
  2122. CurrentReg, ReplaceReg: TRegister;
  2123. begin
  2124. Result := False;
  2125. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2126. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2127. case hp.opcode of
  2128. A_FSTSW, A_FNSTSW,
  2129. A_IN, A_INS, A_OUT, A_OUTS,
  2130. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2131. { These routines have explicit operands, but they are restricted in
  2132. what they can be (e.g. IN and OUT can only read from AL, AX or
  2133. EAX. }
  2134. Exit;
  2135. A_IMUL:
  2136. begin
  2137. { The 1-operand version writes to implicit registers
  2138. The 2-operand version reads from the first operator, and reads
  2139. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2140. the 3-operand version reads from a register that it doesn't write to
  2141. }
  2142. case hp.ops of
  2143. 1:
  2144. if (
  2145. (
  2146. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2147. ) or
  2148. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2149. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2150. begin
  2151. Result := True;
  2152. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2153. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2154. end;
  2155. 2:
  2156. { Only modify the first parameter }
  2157. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2158. begin
  2159. Result := True;
  2160. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2161. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2162. end;
  2163. 3:
  2164. { Only modify the second parameter }
  2165. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2166. begin
  2167. Result := True;
  2168. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2169. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2170. end;
  2171. else
  2172. InternalError(2020012901);
  2173. end;
  2174. end;
  2175. else
  2176. if (hp.ops > 0) and
  2177. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2178. begin
  2179. Result := True;
  2180. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2181. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2182. end;
  2183. end;
  2184. end;
  2185. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2186. var
  2187. hp1, hp2, hp3: tai;
  2188. DoOptimisation, TempBool: Boolean;
  2189. {$ifdef x86_64}
  2190. NewConst: TCGInt;
  2191. {$endif x86_64}
  2192. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2193. begin
  2194. if taicpu(hp1).opcode = signed_movop then
  2195. begin
  2196. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2197. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2198. end
  2199. else
  2200. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2201. end;
  2202. function TryConstMerge(var p1, p2: tai): Boolean;
  2203. var
  2204. ThisRef: TReference;
  2205. begin
  2206. Result := False;
  2207. ThisRef := taicpu(p2).oper[1]^.ref^;
  2208. { Only permit writes to the stack, since we can guarantee alignment with that }
  2209. if (ThisRef.index = NR_NO) and
  2210. (
  2211. (ThisRef.base = NR_STACK_POINTER_REG) or
  2212. (ThisRef.base = current_procinfo.framepointer)
  2213. ) then
  2214. begin
  2215. case taicpu(p).opsize of
  2216. S_B:
  2217. begin
  2218. { Word writes must be on a 2-byte boundary }
  2219. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2220. begin
  2221. { Reduce offset of second reference to see if it is sequential with the first }
  2222. Dec(ThisRef.offset, 1);
  2223. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2224. begin
  2225. { Make sure the constants aren't represented as a
  2226. negative number, as these won't merge properly }
  2227. taicpu(p1).opsize := S_W;
  2228. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2229. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2230. RemoveInstruction(p2);
  2231. Result := True;
  2232. end;
  2233. end;
  2234. end;
  2235. S_W:
  2236. begin
  2237. { Longword writes must be on a 4-byte boundary }
  2238. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2239. begin
  2240. { Reduce offset of second reference to see if it is sequential with the first }
  2241. Dec(ThisRef.offset, 2);
  2242. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2243. begin
  2244. { Make sure the constants aren't represented as a
  2245. negative number, as these won't merge properly }
  2246. taicpu(p1).opsize := S_L;
  2247. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2248. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2249. RemoveInstruction(p2);
  2250. Result := True;
  2251. end;
  2252. end;
  2253. end;
  2254. {$ifdef x86_64}
  2255. S_L:
  2256. begin
  2257. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2258. see if the constants can be encoded this way. }
  2259. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2260. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2261. { Quadword writes must be on an 8-byte boundary }
  2262. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2263. begin
  2264. { Reduce offset of second reference to see if it is sequential with the first }
  2265. Dec(ThisRef.offset, 4);
  2266. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2267. begin
  2268. { Make sure the constants aren't represented as a
  2269. negative number, as these won't merge properly }
  2270. taicpu(p1).opsize := S_Q;
  2271. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2272. taicpu(p1).oper[0]^.val := NewConst;
  2273. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2274. RemoveInstruction(p2);
  2275. Result := True;
  2276. end;
  2277. end;
  2278. end;
  2279. {$endif x86_64}
  2280. else
  2281. ;
  2282. end;
  2283. end;
  2284. end;
  2285. var
  2286. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2287. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2288. NewSize: topsize;
  2289. CurrentReg, ActiveReg: TRegister;
  2290. SourceRef, TargetRef: TReference;
  2291. MovAligned, MovUnaligned: TAsmOp;
  2292. begin
  2293. Result:=false;
  2294. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2295. { remove mov reg1,reg1? }
  2296. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2297. then
  2298. begin
  2299. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2300. { take care of the register (de)allocs following p }
  2301. RemoveCurrentP(p, hp1);
  2302. Result:=true;
  2303. exit;
  2304. end;
  2305. { All the next optimisations require a next instruction }
  2306. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2307. Exit;
  2308. { Look for:
  2309. mov %reg1,%reg2
  2310. ??? %reg2,r/m
  2311. Change to:
  2312. mov %reg1,%reg2
  2313. ??? %reg1,r/m
  2314. }
  2315. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2316. begin
  2317. CurrentReg := taicpu(p).oper[1]^.reg;
  2318. if RegReadByInstruction(CurrentReg, hp1) and
  2319. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2320. begin
  2321. { A change has occurred, just not in p }
  2322. Result := True;
  2323. TransferUsedRegs(TmpUsedRegs);
  2324. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2325. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2326. { Just in case something didn't get modified (e.g. an
  2327. implicit register) }
  2328. not RegReadByInstruction(CurrentReg, hp1) then
  2329. begin
  2330. { We can remove the original MOV }
  2331. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2332. RemoveCurrentp(p, hp1);
  2333. { UsedRegs got updated by RemoveCurrentp }
  2334. Result := True;
  2335. Exit;
  2336. end;
  2337. { If we know a MOV instruction has become a null operation, we might as well
  2338. get rid of it now to save time. }
  2339. if (taicpu(hp1).opcode = A_MOV) and
  2340. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2341. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2342. { Just being a register is enough to confirm it's a null operation }
  2343. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2344. begin
  2345. Result := True;
  2346. { Speed-up to reduce a pipeline stall... if we had something like...
  2347. movl %eax,%edx
  2348. movw %dx,%ax
  2349. ... the second instruction would change to movw %ax,%ax, but
  2350. given that it is now %ax that's active rather than %eax,
  2351. penalties might occur due to a partial register write, so instead,
  2352. change it to a MOVZX instruction when optimising for speed.
  2353. }
  2354. if not (cs_opt_size in current_settings.optimizerswitches) and
  2355. IsMOVZXAcceptable and
  2356. (taicpu(hp1).opsize < taicpu(p).opsize)
  2357. {$ifdef x86_64}
  2358. { operations already implicitly set the upper 64 bits to zero }
  2359. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2360. {$endif x86_64}
  2361. then
  2362. begin
  2363. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2364. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2365. case taicpu(p).opsize of
  2366. S_W:
  2367. if taicpu(hp1).opsize = S_B then
  2368. taicpu(hp1).opsize := S_BL
  2369. else
  2370. InternalError(2020012911);
  2371. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2372. case taicpu(hp1).opsize of
  2373. S_B:
  2374. taicpu(hp1).opsize := S_BL;
  2375. S_W:
  2376. taicpu(hp1).opsize := S_WL;
  2377. else
  2378. InternalError(2020012912);
  2379. end;
  2380. else
  2381. InternalError(2020012910);
  2382. end;
  2383. taicpu(hp1).opcode := A_MOVZX;
  2384. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2385. end
  2386. else
  2387. begin
  2388. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2389. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2390. RemoveInstruction(hp1);
  2391. { The instruction after what was hp1 is now the immediate next instruction,
  2392. so we can continue to make optimisations if it's present }
  2393. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2394. Exit;
  2395. hp1 := hp2;
  2396. end;
  2397. end;
  2398. end;
  2399. end;
  2400. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2401. overwrites the original destination register. e.g.
  2402. movl ###,%reg2d
  2403. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2404. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2405. }
  2406. if (taicpu(p).oper[1]^.typ = top_reg) and
  2407. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2408. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2409. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2410. begin
  2411. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2412. begin
  2413. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2414. case taicpu(p).oper[0]^.typ of
  2415. top_const:
  2416. { We have something like:
  2417. movb $x, %regb
  2418. movzbl %regb,%regd
  2419. Change to:
  2420. movl $x, %regd
  2421. }
  2422. begin
  2423. case taicpu(hp1).opsize of
  2424. S_BW:
  2425. begin
  2426. convert_mov_value(A_MOVSX, $FF);
  2427. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2428. taicpu(p).opsize := S_W;
  2429. end;
  2430. S_BL:
  2431. begin
  2432. convert_mov_value(A_MOVSX, $FF);
  2433. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2434. taicpu(p).opsize := S_L;
  2435. end;
  2436. S_WL:
  2437. begin
  2438. convert_mov_value(A_MOVSX, $FFFF);
  2439. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2440. taicpu(p).opsize := S_L;
  2441. end;
  2442. {$ifdef x86_64}
  2443. S_BQ:
  2444. begin
  2445. convert_mov_value(A_MOVSX, $FF);
  2446. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2447. taicpu(p).opsize := S_Q;
  2448. end;
  2449. S_WQ:
  2450. begin
  2451. convert_mov_value(A_MOVSX, $FFFF);
  2452. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2453. taicpu(p).opsize := S_Q;
  2454. end;
  2455. S_LQ:
  2456. begin
  2457. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2458. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2459. taicpu(p).opsize := S_Q;
  2460. end;
  2461. {$endif x86_64}
  2462. else
  2463. { If hp1 was a MOV instruction, it should have been
  2464. optimised already }
  2465. InternalError(2020021001);
  2466. end;
  2467. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2468. RemoveInstruction(hp1);
  2469. Result := True;
  2470. Exit;
  2471. end;
  2472. top_ref:
  2473. { We have something like:
  2474. movb mem, %regb
  2475. movzbl %regb,%regd
  2476. Change to:
  2477. movzbl mem, %regd
  2478. }
  2479. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2480. begin
  2481. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2482. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  2483. RemoveCurrentP(p, hp1);
  2484. Result:=True;
  2485. Exit;
  2486. end;
  2487. else
  2488. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2489. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2490. Exit;
  2491. end;
  2492. end
  2493. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2494. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2495. optimised }
  2496. else
  2497. begin
  2498. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2499. RemoveCurrentP(p, hp1);
  2500. Result := True;
  2501. Exit;
  2502. end;
  2503. end;
  2504. if (taicpu(hp1).opcode = A_AND) and
  2505. (taicpu(p).oper[1]^.typ = top_reg) and
  2506. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2507. begin
  2508. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2509. begin
  2510. case taicpu(p).opsize of
  2511. S_L:
  2512. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2513. begin
  2514. { Optimize out:
  2515. mov x, %reg
  2516. and ffffffffh, %reg
  2517. }
  2518. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2519. RemoveInstruction(hp1);
  2520. Result:=true;
  2521. exit;
  2522. end;
  2523. S_Q: { TODO: Confirm if this is even possible }
  2524. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2525. begin
  2526. { Optimize out:
  2527. mov x, %reg
  2528. and ffffffffffffffffh, %reg
  2529. }
  2530. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2531. RemoveInstruction(hp1);
  2532. Result:=true;
  2533. exit;
  2534. end;
  2535. else
  2536. ;
  2537. end;
  2538. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2539. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2540. GetNextInstruction(hp1,hp2) and
  2541. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2542. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2543. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2544. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2545. GetNextInstruction(hp2,hp3) and
  2546. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2547. (taicpu(hp3).condition in [C_E,C_NE]) then
  2548. begin
  2549. TransferUsedRegs(TmpUsedRegs);
  2550. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2551. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2552. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2553. begin
  2554. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2555. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2556. taicpu(hp1).opcode:=A_TEST;
  2557. RemoveInstruction(hp2);
  2558. RemoveCurrentP(p, hp1);
  2559. Result:=true;
  2560. exit;
  2561. end;
  2562. end;
  2563. end
  2564. else if IsMOVZXAcceptable and
  2565. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2566. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2567. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2568. then
  2569. begin
  2570. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2571. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2572. case taicpu(p).opsize of
  2573. S_B:
  2574. if (taicpu(hp1).oper[0]^.val = $ff) then
  2575. begin
  2576. { Convert:
  2577. movb x, %regl movb x, %regl
  2578. andw ffh, %regw andl ffh, %regd
  2579. To:
  2580. movzbw x, %regd movzbl x, %regd
  2581. (Identical registers, just different sizes)
  2582. }
  2583. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2584. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2585. case taicpu(hp1).opsize of
  2586. S_W: NewSize := S_BW;
  2587. S_L: NewSize := S_BL;
  2588. {$ifdef x86_64}
  2589. S_Q: NewSize := S_BQ;
  2590. {$endif x86_64}
  2591. else
  2592. InternalError(2018011510);
  2593. end;
  2594. end
  2595. else
  2596. NewSize := S_NO;
  2597. S_W:
  2598. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2599. begin
  2600. { Convert:
  2601. movw x, %regw
  2602. andl ffffh, %regd
  2603. To:
  2604. movzwl x, %regd
  2605. (Identical registers, just different sizes)
  2606. }
  2607. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2608. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2609. case taicpu(hp1).opsize of
  2610. S_L: NewSize := S_WL;
  2611. {$ifdef x86_64}
  2612. S_Q: NewSize := S_WQ;
  2613. {$endif x86_64}
  2614. else
  2615. InternalError(2018011511);
  2616. end;
  2617. end
  2618. else
  2619. NewSize := S_NO;
  2620. else
  2621. NewSize := S_NO;
  2622. end;
  2623. if NewSize <> S_NO then
  2624. begin
  2625. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2626. { The actual optimization }
  2627. taicpu(p).opcode := A_MOVZX;
  2628. taicpu(p).changeopsize(NewSize);
  2629. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2630. { Safeguard if "and" is followed by a conditional command }
  2631. TransferUsedRegs(TmpUsedRegs);
  2632. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2633. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2634. begin
  2635. { At this point, the "and" command is effectively equivalent to
  2636. "test %reg,%reg". This will be handled separately by the
  2637. Peephole Optimizer. [Kit] }
  2638. DebugMsg(SPeepholeOptimization + PreMessage +
  2639. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2640. end
  2641. else
  2642. begin
  2643. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2644. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2645. RemoveInstruction(hp1);
  2646. end;
  2647. Result := True;
  2648. Exit;
  2649. end;
  2650. end;
  2651. end;
  2652. if (taicpu(hp1).opcode = A_OR) and
  2653. (taicpu(p).oper[1]^.typ = top_reg) and
  2654. MatchOperand(taicpu(p).oper[0]^, 0) and
  2655. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2656. begin
  2657. { mov 0, %reg
  2658. or ###,%reg
  2659. Change to (only if the flags are not used):
  2660. mov ###,%reg
  2661. }
  2662. TransferUsedRegs(TmpUsedRegs);
  2663. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2664. DoOptimisation := True;
  2665. { Even if the flags are used, we might be able to do the optimisation
  2666. if the conditions are predictable }
  2667. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2668. begin
  2669. { Only perform if ### = %reg (the same register) or equal to 0,
  2670. so %reg is guaranteed to still have a value of zero }
  2671. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2672. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2673. begin
  2674. hp2 := hp1;
  2675. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2676. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2677. GetNextInstruction(hp2, hp3) do
  2678. begin
  2679. { Don't continue modifying if the flags state is getting changed }
  2680. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2681. Break;
  2682. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2683. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2684. begin
  2685. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2686. begin
  2687. { Condition is always true }
  2688. case taicpu(hp3).opcode of
  2689. A_Jcc:
  2690. begin
  2691. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2692. { Check for jump shortcuts before we destroy the condition }
  2693. DoJumpOptimizations(hp3, TempBool);
  2694. MakeUnconditional(taicpu(hp3));
  2695. Result := True;
  2696. end;
  2697. A_CMOVcc:
  2698. begin
  2699. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2700. taicpu(hp3).opcode := A_MOV;
  2701. taicpu(hp3).condition := C_None;
  2702. Result := True;
  2703. end;
  2704. A_SETcc:
  2705. begin
  2706. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2707. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2708. taicpu(hp3).opcode := A_MOV;
  2709. taicpu(hp3).ops := 2;
  2710. taicpu(hp3).condition := C_None;
  2711. taicpu(hp3).opsize := S_B;
  2712. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2713. taicpu(hp3).loadconst(0, 1);
  2714. Result := True;
  2715. end;
  2716. else
  2717. InternalError(2021090701);
  2718. end;
  2719. end
  2720. 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
  2721. begin
  2722. { Condition is always false }
  2723. case taicpu(hp3).opcode of
  2724. A_Jcc:
  2725. begin
  2726. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2727. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2728. RemoveInstruction(hp3);
  2729. Result := True;
  2730. { Since hp3 was deleted, hp2 must not be updated }
  2731. Continue;
  2732. end;
  2733. A_CMOVcc:
  2734. begin
  2735. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2736. RemoveInstruction(hp3);
  2737. Result := True;
  2738. { Since hp3 was deleted, hp2 must not be updated }
  2739. Continue;
  2740. end;
  2741. A_SETcc:
  2742. begin
  2743. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2744. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2745. taicpu(hp3).opcode := A_MOV;
  2746. taicpu(hp3).ops := 2;
  2747. taicpu(hp3).condition := C_None;
  2748. taicpu(hp3).opsize := S_B;
  2749. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2750. taicpu(hp3).loadconst(0, 0);
  2751. Result := True;
  2752. end;
  2753. else
  2754. InternalError(2021090702);
  2755. end;
  2756. end
  2757. else
  2758. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2759. DoOptimisation := False;
  2760. end;
  2761. hp2 := hp3;
  2762. end;
  2763. { Flags are still in use - don't optimise }
  2764. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2765. DoOptimisation := False;
  2766. end
  2767. else
  2768. DoOptimisation := False;
  2769. end;
  2770. if DoOptimisation then
  2771. begin
  2772. {$ifdef x86_64}
  2773. { OR only supports 32-bit sign-extended constants for 64-bit
  2774. instructions, so compensate for this if the constant is
  2775. encoded as a value greater than or equal to 2^31 }
  2776. if (taicpu(hp1).opsize = S_Q) and
  2777. (taicpu(hp1).oper[0]^.typ = top_const) and
  2778. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2779. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2780. {$endif x86_64}
  2781. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2782. taicpu(hp1).opcode := A_MOV;
  2783. RemoveCurrentP(p, hp1);
  2784. Result := True;
  2785. Exit;
  2786. end;
  2787. end;
  2788. { Next instruction is also a MOV ? }
  2789. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2790. begin
  2791. if MatchOpType(taicpu(p), top_const, top_ref) and
  2792. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2793. TryConstMerge(p, hp1) then
  2794. begin
  2795. Result := True;
  2796. { In case we have four byte writes in a row, check for 2 more
  2797. right now so we don't have to wait for another iteration of
  2798. pass 1
  2799. }
  2800. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  2801. case taicpu(p).opsize of
  2802. S_W:
  2803. begin
  2804. if GetNextInstruction(p, hp1) and
  2805. MatchInstruction(hp1, A_MOV, [S_B]) and
  2806. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2807. GetNextInstruction(hp1, hp2) and
  2808. MatchInstruction(hp2, A_MOV, [S_B]) and
  2809. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2810. { Try to merge the two bytes }
  2811. TryConstMerge(hp1, hp2) then
  2812. { Now try to merge the two words (hp2 will get deleted) }
  2813. TryConstMerge(p, hp1);
  2814. end;
  2815. S_L:
  2816. begin
  2817. { Though this only really benefits x86_64 and not i386, it
  2818. gets a potential optimisation done faster and hence
  2819. reduces the number of times OptPass1MOV is entered }
  2820. if GetNextInstruction(p, hp1) and
  2821. MatchInstruction(hp1, A_MOV, [S_W]) and
  2822. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2823. GetNextInstruction(hp1, hp2) and
  2824. MatchInstruction(hp2, A_MOV, [S_W]) and
  2825. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2826. { Try to merge the two words }
  2827. TryConstMerge(hp1, hp2) then
  2828. { This will always fail on i386, so don't bother
  2829. calling it unless we're doing x86_64 }
  2830. {$ifdef x86_64}
  2831. { Now try to merge the two longwords (hp2 will get deleted) }
  2832. TryConstMerge(p, hp1)
  2833. {$endif x86_64}
  2834. ;
  2835. end;
  2836. else
  2837. ;
  2838. end;
  2839. Exit;
  2840. end;
  2841. if (taicpu(p).oper[1]^.typ = top_reg) and
  2842. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2843. begin
  2844. CurrentReg := taicpu(p).oper[1]^.reg;
  2845. TransferUsedRegs(TmpUsedRegs);
  2846. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2847. { we have
  2848. mov x, %treg
  2849. mov %treg, y
  2850. }
  2851. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2852. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2853. { we've got
  2854. mov x, %treg
  2855. mov %treg, y
  2856. with %treg is not used after }
  2857. case taicpu(p).oper[0]^.typ Of
  2858. { top_reg is covered by DeepMOVOpt }
  2859. top_const:
  2860. begin
  2861. { change
  2862. mov const, %treg
  2863. mov %treg, y
  2864. to
  2865. mov const, y
  2866. }
  2867. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2868. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2869. begin
  2870. if taicpu(hp1).oper[1]^.typ=top_reg then
  2871. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2872. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2873. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2874. RemoveInstruction(hp1);
  2875. Result:=true;
  2876. Exit;
  2877. end;
  2878. end;
  2879. top_ref:
  2880. case taicpu(hp1).oper[1]^.typ of
  2881. top_reg:
  2882. begin
  2883. { change
  2884. mov mem, %treg
  2885. mov %treg, %reg
  2886. to
  2887. mov mem, %reg"
  2888. }
  2889. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2890. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2891. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2892. RemoveInstruction(hp1);
  2893. Result:=true;
  2894. Exit;
  2895. end;
  2896. top_ref:
  2897. begin
  2898. {$ifdef x86_64}
  2899. { Look for the following to simplify:
  2900. mov x(mem1), %reg
  2901. mov %reg, y(mem2)
  2902. mov x+8(mem1), %reg
  2903. mov %reg, y+8(mem2)
  2904. Change to:
  2905. movdqu x(mem1), %xmmreg
  2906. movdqu %xmmreg, y(mem2)
  2907. }
  2908. SourceRef := taicpu(p).oper[0]^.ref^;
  2909. TargetRef := taicpu(hp1).oper[1]^.ref^;
  2910. if (taicpu(p).opsize = S_Q) and
  2911. GetNextInstruction(hp1, hp2) and
  2912. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  2913. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  2914. begin
  2915. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  2916. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2917. Inc(SourceRef.offset, 8);
  2918. if UseAVX then
  2919. begin
  2920. MovAligned := A_VMOVDQA;
  2921. MovUnaligned := A_VMOVDQU;
  2922. end
  2923. else
  2924. begin
  2925. MovAligned := A_MOVDQA;
  2926. MovUnaligned := A_MOVDQU;
  2927. end;
  2928. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2929. begin
  2930. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2931. Inc(TargetRef.offset, 8);
  2932. if GetNextInstruction(hp2, hp3) and
  2933. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2934. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2935. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2936. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2937. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2938. begin
  2939. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2940. if CurrentReg <> NR_NO then
  2941. begin
  2942. { Remember that the offsets are 8 ahead }
  2943. if ((SourceRef.offset mod 16) = 8) and
  2944. (
  2945. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2946. (SourceRef.base = current_procinfo.framepointer) or
  2947. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2948. ) then
  2949. taicpu(p).opcode := MovAligned
  2950. else
  2951. taicpu(p).opcode := MovUnaligned;
  2952. taicpu(p).opsize := S_XMM;
  2953. taicpu(p).oper[1]^.reg := CurrentReg;
  2954. if ((TargetRef.offset mod 16) = 8) and
  2955. (
  2956. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2957. (TargetRef.base = current_procinfo.framepointer) or
  2958. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2959. ) then
  2960. taicpu(hp1).opcode := MovAligned
  2961. else
  2962. taicpu(hp1).opcode := MovUnaligned;
  2963. taicpu(hp1).opsize := S_XMM;
  2964. taicpu(hp1).oper[0]^.reg := CurrentReg;
  2965. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  2966. RemoveInstruction(hp2);
  2967. RemoveInstruction(hp3);
  2968. Result := True;
  2969. Exit;
  2970. end;
  2971. end;
  2972. end
  2973. else
  2974. begin
  2975. { See if the next references are 8 less rather than 8 greater }
  2976. Dec(SourceRef.offset, 16); { -8 the other way }
  2977. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2978. begin
  2979. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2980. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  2981. if GetNextInstruction(hp2, hp3) and
  2982. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2983. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2984. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2985. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2986. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2987. begin
  2988. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2989. if CurrentReg <> NR_NO then
  2990. begin
  2991. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  2992. if ((SourceRef.offset mod 16) = 0) and
  2993. (
  2994. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2995. (SourceRef.base = current_procinfo.framepointer) or
  2996. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2997. ) then
  2998. taicpu(hp2).opcode := MovAligned
  2999. else
  3000. taicpu(hp2).opcode := MovUnaligned;
  3001. taicpu(hp2).opsize := S_XMM;
  3002. taicpu(hp2).oper[1]^.reg := CurrentReg;
  3003. if ((TargetRef.offset mod 16) = 0) and
  3004. (
  3005. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3006. (TargetRef.base = current_procinfo.framepointer) or
  3007. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3008. ) then
  3009. taicpu(hp3).opcode := MovAligned
  3010. else
  3011. taicpu(hp3).opcode := MovUnaligned;
  3012. taicpu(hp3).opsize := S_XMM;
  3013. taicpu(hp3).oper[0]^.reg := CurrentReg;
  3014. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3015. RemoveInstruction(hp1);
  3016. RemoveCurrentP(p, hp2);
  3017. Result := True;
  3018. Exit;
  3019. end;
  3020. end;
  3021. end;
  3022. end;
  3023. end;
  3024. {$endif x86_64}
  3025. end;
  3026. else
  3027. { The write target should be a reg or a ref }
  3028. InternalError(2021091601);
  3029. end;
  3030. else
  3031. ;
  3032. end
  3033. else
  3034. { %treg is used afterwards, but all eventualities
  3035. other than the first MOV instruction being a constant
  3036. are covered by DeepMOVOpt, so only check for that }
  3037. if (taicpu(p).oper[0]^.typ = top_const) and
  3038. (
  3039. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3040. not (cs_opt_size in current_settings.optimizerswitches) or
  3041. (taicpu(hp1).opsize = S_B)
  3042. ) and
  3043. (
  3044. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3045. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3046. ) then
  3047. begin
  3048. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3049. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3050. end;
  3051. end;
  3052. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3053. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3054. { mov reg1, mem1 or mov mem1, reg1
  3055. mov mem2, reg2 mov reg2, mem2}
  3056. begin
  3057. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3058. { mov reg1, mem1 or mov mem1, reg1
  3059. mov mem2, reg1 mov reg2, mem1}
  3060. begin
  3061. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3062. { Removes the second statement from
  3063. mov reg1, mem1/reg2
  3064. mov mem1/reg2, reg1 }
  3065. begin
  3066. if taicpu(p).oper[0]^.typ=top_reg then
  3067. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3068. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3069. RemoveInstruction(hp1);
  3070. Result:=true;
  3071. exit;
  3072. end
  3073. else
  3074. begin
  3075. TransferUsedRegs(TmpUsedRegs);
  3076. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3077. if (taicpu(p).oper[1]^.typ = top_ref) and
  3078. { mov reg1, mem1
  3079. mov mem2, reg1 }
  3080. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3081. GetNextInstruction(hp1, hp2) and
  3082. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3083. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3084. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3085. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3086. { change to
  3087. mov reg1, mem1 mov reg1, mem1
  3088. mov mem2, reg1 cmp reg1, mem2
  3089. cmp mem1, reg1
  3090. }
  3091. begin
  3092. RemoveInstruction(hp2);
  3093. taicpu(hp1).opcode := A_CMP;
  3094. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3095. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3096. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3097. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3098. end;
  3099. end;
  3100. end
  3101. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3102. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3103. begin
  3104. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3105. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3106. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3107. end
  3108. else
  3109. begin
  3110. TransferUsedRegs(TmpUsedRegs);
  3111. if GetNextInstruction(hp1, hp2) and
  3112. MatchOpType(taicpu(p),top_ref,top_reg) and
  3113. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3114. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3115. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3116. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3117. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3118. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3119. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3120. { mov mem1, %reg1
  3121. mov %reg1, mem2
  3122. mov mem2, reg2
  3123. to:
  3124. mov mem1, reg2
  3125. mov reg2, mem2}
  3126. begin
  3127. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3128. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3129. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3130. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3131. RemoveInstruction(hp2);
  3132. Result := True;
  3133. end
  3134. {$ifdef i386}
  3135. { this is enabled for i386 only, as the rules to create the reg sets below
  3136. are too complicated for x86-64, so this makes this code too error prone
  3137. on x86-64
  3138. }
  3139. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3140. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3141. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3142. { mov mem1, reg1 mov mem1, reg1
  3143. mov reg1, mem2 mov reg1, mem2
  3144. mov mem2, reg2 mov mem2, reg1
  3145. to: to:
  3146. mov mem1, reg1 mov mem1, reg1
  3147. mov mem1, reg2 mov reg1, mem2
  3148. mov reg1, mem2
  3149. or (if mem1 depends on reg1
  3150. and/or if mem2 depends on reg2)
  3151. to:
  3152. mov mem1, reg1
  3153. mov reg1, mem2
  3154. mov reg1, reg2
  3155. }
  3156. begin
  3157. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3158. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3159. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3160. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3161. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3162. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3163. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3164. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3165. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3166. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3167. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3168. end
  3169. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3170. begin
  3171. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3172. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3173. end
  3174. else
  3175. begin
  3176. RemoveInstruction(hp2);
  3177. end
  3178. {$endif i386}
  3179. ;
  3180. end;
  3181. end
  3182. { movl [mem1],reg1
  3183. movl [mem1],reg2
  3184. to
  3185. movl [mem1],reg1
  3186. movl reg1,reg2
  3187. }
  3188. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3189. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3190. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3191. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3192. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3193. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3194. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3195. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3196. begin
  3197. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3198. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3199. end;
  3200. { movl const1,[mem1]
  3201. movl [mem1],reg1
  3202. to
  3203. movl const1,reg1
  3204. movl reg1,[mem1]
  3205. }
  3206. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3207. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3208. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3209. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3210. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3211. begin
  3212. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3213. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3214. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3215. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3216. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3217. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3218. Result:=true;
  3219. exit;
  3220. end;
  3221. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3222. end;
  3223. { search further than the next instruction for a mov (as long as it's not a jump) }
  3224. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3225. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3226. (taicpu(p).oper[1]^.typ = top_reg) and
  3227. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3228. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3229. begin
  3230. { we work with hp2 here, so hp1 can be still used later on when
  3231. checking for GetNextInstruction_p }
  3232. hp3 := hp1;
  3233. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3234. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3235. { Saves on a large number of dereferences }
  3236. ActiveReg := taicpu(p).oper[1]^.reg;
  3237. TransferUsedRegs(TmpUsedRegs);
  3238. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3239. while GetNextInstructionUsingRegCond(hp3,hp2,ActiveReg,CrossJump) and
  3240. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3241. (hp2.typ=ait_instruction) do
  3242. begin
  3243. case taicpu(hp2).opcode of
  3244. A_POP:
  3245. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) then
  3246. begin
  3247. if not CrossJump and
  3248. not RegUsedBetween(ActiveReg, p, hp2) then
  3249. begin
  3250. { We can remove the original MOV since the register
  3251. wasn't used between it and its popping from the stack }
  3252. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3253. RemoveCurrentp(p, hp1);
  3254. Result := True;
  3255. Exit;
  3256. end;
  3257. { Can't go any further }
  3258. Break;
  3259. end;
  3260. A_MOV:
  3261. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) and
  3262. ((taicpu(p).oper[0]^.typ=top_const) or
  3263. ((taicpu(p).oper[0]^.typ=top_reg) and
  3264. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3265. )
  3266. ) then
  3267. begin
  3268. { we have
  3269. mov x, %treg
  3270. mov %treg, y
  3271. }
  3272. { We don't need to call UpdateUsedRegs for every instruction between
  3273. p and hp2 because the register we're concerned about will not
  3274. become deallocated (otherwise GetNextInstructionUsingReg would
  3275. have stopped at an earlier instruction). [Kit] }
  3276. TempRegUsed :=
  3277. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3278. RegReadByInstruction(ActiveReg, hp3) or
  3279. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs);
  3280. case taicpu(p).oper[0]^.typ Of
  3281. top_reg:
  3282. begin
  3283. { change
  3284. mov %reg, %treg
  3285. mov %treg, y
  3286. to
  3287. mov %reg, y
  3288. }
  3289. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3290. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3291. if MatchOperand(taicpu(hp2).oper[1]^, CurrentReg) then
  3292. begin
  3293. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3294. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3295. if TempRegUsed then
  3296. begin
  3297. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3298. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3299. { Set the start of the next GetNextInstructionUsingRegCond search
  3300. to start at the entry right before hp2 (which is about to be removed) }
  3301. hp3 := tai(hp2.Previous);
  3302. RemoveInstruction(hp2);
  3303. { See if there's more we can optimise }
  3304. Continue;
  3305. end
  3306. else
  3307. begin
  3308. RemoveInstruction(hp2);
  3309. { We can remove the original MOV too }
  3310. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3311. RemoveCurrentP(p, hp1);
  3312. Result:=true;
  3313. Exit;
  3314. end;
  3315. end
  3316. else
  3317. begin
  3318. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3319. taicpu(hp2).loadReg(0, CurrentReg);
  3320. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3321. { Check to see if the register also appears in the reference }
  3322. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3323. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, ActiveReg, CurrentReg);
  3324. { Don't remove the first instruction if the temporary register is in use }
  3325. if not TempRegUsed and
  3326. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3327. not RegInOp(ActiveReg, taicpu(hp2).oper[1]^) then
  3328. begin
  3329. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3330. RemoveCurrentP(p, hp1);
  3331. Result:=true;
  3332. Exit;
  3333. end;
  3334. { No need to set Result to True here. If there's another instruction later
  3335. on that can be optimised, it will be detected when the main Pass 1 loop
  3336. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3337. end;
  3338. end;
  3339. top_const:
  3340. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3341. begin
  3342. { change
  3343. mov const, %treg
  3344. mov %treg, y
  3345. to
  3346. mov const, y
  3347. }
  3348. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3349. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3350. begin
  3351. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3352. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3353. if TempRegUsed then
  3354. begin
  3355. { Don't remove the first instruction if the temporary register is in use }
  3356. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3357. { No need to set Result to True. If there's another instruction later on
  3358. that can be optimised, it will be detected when the main Pass 1 loop
  3359. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3360. end
  3361. else
  3362. begin
  3363. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3364. RemoveCurrentP(p, hp1);
  3365. Result:=true;
  3366. Exit;
  3367. end;
  3368. end;
  3369. end;
  3370. else
  3371. Internalerror(2019103001);
  3372. end;
  3373. end
  3374. else
  3375. if MatchOperand(taicpu(hp2).oper[1]^, ActiveReg) then
  3376. begin
  3377. if not CrossJump and
  3378. not RegUsedBetween(ActiveReg, p, hp2) and
  3379. not RegReadByInstruction(ActiveReg, hp2) then
  3380. begin
  3381. { Register is not used before it is overwritten }
  3382. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3383. RemoveCurrentp(p, hp1);
  3384. Result := True;
  3385. Exit;
  3386. end;
  3387. if (taicpu(p).oper[0]^.typ = top_const) and
  3388. (taicpu(hp2).oper[0]^.typ = top_const) then
  3389. begin
  3390. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3391. begin
  3392. { Same value - register hasn't changed }
  3393. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3394. RemoveInstruction(hp2);
  3395. Result := True;
  3396. { See if there's more we can optimise }
  3397. Continue;
  3398. end;
  3399. end;
  3400. end;
  3401. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3402. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3403. MatchOperand(taicpu(hp2).oper[0]^, ActiveReg) and
  3404. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, ActiveReg) then
  3405. begin
  3406. {
  3407. Change from:
  3408. mov ###, %reg
  3409. ...
  3410. movs/z %reg,%reg (Same register, just different sizes)
  3411. To:
  3412. movs/z ###, %reg (Longer version)
  3413. ...
  3414. (remove)
  3415. }
  3416. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3417. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3418. { Keep the first instruction as mov if ### is a constant }
  3419. if taicpu(p).oper[0]^.typ = top_const then
  3420. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3421. else
  3422. begin
  3423. taicpu(p).opcode := taicpu(hp2).opcode;
  3424. taicpu(p).opsize := taicpu(hp2).opsize;
  3425. end;
  3426. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3427. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3428. RemoveInstruction(hp2);
  3429. Result := True;
  3430. Exit;
  3431. end;
  3432. else
  3433. { Move down to the MatchOpType if-block below };
  3434. end;
  3435. { Also catches MOV/S/Z instructions that aren't modified }
  3436. if taicpu(p).oper[0]^.typ = top_reg then
  3437. begin
  3438. CurrentReg := taicpu(p).oper[0]^.reg;
  3439. if
  3440. not RegModifiedByInstruction(CurrentReg, hp3) and
  3441. not RegModifiedBetween(CurrentReg, hp3, hp2) and
  3442. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3443. begin
  3444. Result := True;
  3445. { Just in case something didn't get modified (e.g. an
  3446. implicit register). Also, if it does read from this
  3447. register, then there's no longer an advantage to
  3448. changing the register on subsequent instructions.}
  3449. if not RegReadByInstruction(ActiveReg, hp2) then
  3450. begin
  3451. { If a conditional jump was crossed, do not delete
  3452. the original MOV no matter what }
  3453. if not CrossJump and
  3454. { RegEndOfLife returns True if the register is
  3455. deallocated before the next instruction or has
  3456. been loaded with a new value }
  3457. RegEndOfLife(ActiveReg, taicpu(hp2)) then
  3458. begin
  3459. { We can remove the original MOV }
  3460. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3461. RemoveCurrentp(p, hp1);
  3462. Exit;
  3463. end;
  3464. if not RegModifiedByInstruction(ActiveReg, hp2) then
  3465. begin
  3466. { See if there's more we can optimise }
  3467. hp3 := hp2;
  3468. Continue;
  3469. end;
  3470. end;
  3471. end;
  3472. end;
  3473. { Break out of the while loop under normal circumstances }
  3474. Break;
  3475. end;
  3476. end;
  3477. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3478. (taicpu(p).oper[1]^.typ = top_reg) and
  3479. (taicpu(p).opsize = S_L) and
  3480. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3481. (taicpu(hp2).opcode = A_AND) and
  3482. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3483. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3484. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3485. ) then
  3486. begin
  3487. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3488. begin
  3489. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3490. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3491. begin
  3492. { Optimize out:
  3493. mov x, %reg
  3494. and ffffffffh, %reg
  3495. }
  3496. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3497. RemoveInstruction(hp2);
  3498. Result:=true;
  3499. exit;
  3500. end;
  3501. end;
  3502. end;
  3503. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3504. x >= RetOffset) as it doesn't do anything (it writes either to a
  3505. parameter or to the temporary storage room for the function
  3506. result)
  3507. }
  3508. if IsExitCode(hp1) and
  3509. (taicpu(p).oper[1]^.typ = top_ref) and
  3510. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3511. (
  3512. (
  3513. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3514. not (
  3515. assigned(current_procinfo.procdef.funcretsym) and
  3516. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3517. )
  3518. ) or
  3519. { Also discard writes to the stack that are below the base pointer,
  3520. as this is temporary storage rather than a function result on the
  3521. stack, say. }
  3522. (
  3523. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3524. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3525. )
  3526. ) then
  3527. begin
  3528. RemoveCurrentp(p, hp1);
  3529. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3530. RemoveLastDeallocForFuncRes(p);
  3531. Result:=true;
  3532. exit;
  3533. end;
  3534. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3535. begin
  3536. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3537. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3538. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3539. begin
  3540. { change
  3541. mov reg1, mem1
  3542. test/cmp x, mem1
  3543. to
  3544. mov reg1, mem1
  3545. test/cmp x, reg1
  3546. }
  3547. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3548. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3549. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3550. Result := True;
  3551. Exit;
  3552. end;
  3553. if DoMovCmpMemOpt(p, hp1, True) then
  3554. begin
  3555. Result := True;
  3556. Exit;
  3557. end;
  3558. end;
  3559. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3560. { If the flags register is in use, don't change the instruction to an
  3561. ADD otherwise this will scramble the flags. [Kit] }
  3562. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3563. begin
  3564. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3565. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3566. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3567. ) or
  3568. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3569. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3570. )
  3571. ) then
  3572. { mov reg1,ref
  3573. lea reg2,[reg1,reg2]
  3574. to
  3575. add reg2,ref}
  3576. begin
  3577. TransferUsedRegs(TmpUsedRegs);
  3578. { reg1 may not be used afterwards }
  3579. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3580. begin
  3581. Taicpu(hp1).opcode:=A_ADD;
  3582. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3583. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3584. RemoveCurrentp(p, hp1);
  3585. result:=true;
  3586. exit;
  3587. end;
  3588. end;
  3589. { If the LEA instruction can be converted into an arithmetic instruction,
  3590. it may be possible to then fold it in the next optimisation, otherwise
  3591. there's nothing more that can be optimised here. }
  3592. if not ConvertLEA(taicpu(hp1)) then
  3593. Exit;
  3594. end;
  3595. if (taicpu(p).oper[1]^.typ = top_reg) and
  3596. (hp1.typ = ait_instruction) and
  3597. GetNextInstruction(hp1, hp2) and
  3598. MatchInstruction(hp2,A_MOV,[]) and
  3599. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3600. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3601. (
  3602. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3603. {$ifdef x86_64}
  3604. or
  3605. (
  3606. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3607. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3608. )
  3609. {$endif x86_64}
  3610. ) then
  3611. begin
  3612. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3613. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3614. { change movsX/movzX reg/ref, reg2
  3615. add/sub/or/... reg3/$const, reg2
  3616. mov reg2 reg/ref
  3617. dealloc reg2
  3618. to
  3619. add/sub/or/... reg3/$const, reg/ref }
  3620. begin
  3621. TransferUsedRegs(TmpUsedRegs);
  3622. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3623. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3624. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3625. begin
  3626. { by example:
  3627. movswl %si,%eax movswl %si,%eax p
  3628. decl %eax addl %edx,%eax hp1
  3629. movw %ax,%si movw %ax,%si hp2
  3630. ->
  3631. movswl %si,%eax movswl %si,%eax p
  3632. decw %eax addw %edx,%eax hp1
  3633. movw %ax,%si movw %ax,%si hp2
  3634. }
  3635. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3636. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3637. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3638. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3639. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3640. {
  3641. ->
  3642. movswl %si,%eax movswl %si,%eax p
  3643. decw %si addw %dx,%si hp1
  3644. movw %ax,%si movw %ax,%si hp2
  3645. }
  3646. case taicpu(hp1).ops of
  3647. 1:
  3648. begin
  3649. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3650. if taicpu(hp1).oper[0]^.typ=top_reg then
  3651. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3652. end;
  3653. 2:
  3654. begin
  3655. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3656. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3657. (taicpu(hp1).opcode<>A_SHL) and
  3658. (taicpu(hp1).opcode<>A_SHR) and
  3659. (taicpu(hp1).opcode<>A_SAR) then
  3660. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3661. end;
  3662. else
  3663. internalerror(2008042701);
  3664. end;
  3665. {
  3666. ->
  3667. decw %si addw %dx,%si p
  3668. }
  3669. RemoveInstruction(hp2);
  3670. RemoveCurrentP(p, hp1);
  3671. Result:=True;
  3672. Exit;
  3673. end;
  3674. end;
  3675. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3676. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3677. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3678. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3679. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3680. )
  3681. {$ifdef i386}
  3682. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3683. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3684. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3685. {$endif i386}
  3686. then
  3687. { change movsX/movzX reg/ref, reg2
  3688. add/sub/or/... regX/$const, reg2
  3689. mov reg2, reg3
  3690. dealloc reg2
  3691. to
  3692. movsX/movzX reg/ref, reg3
  3693. add/sub/or/... reg3/$const, reg3
  3694. }
  3695. begin
  3696. TransferUsedRegs(TmpUsedRegs);
  3697. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3698. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3699. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3700. begin
  3701. { by example:
  3702. movswl %si,%eax movswl %si,%eax p
  3703. decl %eax addl %edx,%eax hp1
  3704. movw %ax,%si movw %ax,%si hp2
  3705. ->
  3706. movswl %si,%eax movswl %si,%eax p
  3707. decw %eax addw %edx,%eax hp1
  3708. movw %ax,%si movw %ax,%si hp2
  3709. }
  3710. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3711. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3712. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3713. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3714. { limit size of constants as well to avoid assembler errors, but
  3715. check opsize to avoid overflow when left shifting the 1 }
  3716. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3717. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3718. {$ifdef x86_64}
  3719. { Be careful of, for example:
  3720. movl %reg1,%reg2
  3721. addl %reg3,%reg2
  3722. movq %reg2,%reg4
  3723. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3724. }
  3725. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3726. begin
  3727. taicpu(hp2).changeopsize(S_L);
  3728. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3729. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3730. end;
  3731. {$endif x86_64}
  3732. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3733. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3734. if taicpu(p).oper[0]^.typ=top_reg then
  3735. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3736. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3737. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3738. {
  3739. ->
  3740. movswl %si,%eax movswl %si,%eax p
  3741. decw %si addw %dx,%si hp1
  3742. movw %ax,%si movw %ax,%si hp2
  3743. }
  3744. case taicpu(hp1).ops of
  3745. 1:
  3746. begin
  3747. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3748. if taicpu(hp1).oper[0]^.typ=top_reg then
  3749. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3750. end;
  3751. 2:
  3752. begin
  3753. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3754. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3755. (taicpu(hp1).opcode<>A_SHL) and
  3756. (taicpu(hp1).opcode<>A_SHR) and
  3757. (taicpu(hp1).opcode<>A_SAR) then
  3758. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3759. end;
  3760. else
  3761. internalerror(2018111801);
  3762. end;
  3763. {
  3764. ->
  3765. decw %si addw %dx,%si p
  3766. }
  3767. RemoveInstruction(hp2);
  3768. end;
  3769. end;
  3770. end;
  3771. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3772. GetNextInstruction(hp1, hp2) and
  3773. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3774. MatchOperand(Taicpu(p).oper[0]^,0) and
  3775. (Taicpu(p).oper[1]^.typ = top_reg) and
  3776. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3777. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3778. { mov reg1,0
  3779. bts reg1,operand1 --> mov reg1,operand2
  3780. or reg1,operand2 bts reg1,operand1}
  3781. begin
  3782. Taicpu(hp2).opcode:=A_MOV;
  3783. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  3784. asml.remove(hp1);
  3785. insertllitem(hp2,hp2.next,hp1);
  3786. RemoveCurrentp(p, hp1);
  3787. Result:=true;
  3788. exit;
  3789. end;
  3790. {
  3791. mov ref,reg0
  3792. <op> reg0,reg1
  3793. dealloc reg0
  3794. to
  3795. <op> ref,reg1
  3796. }
  3797. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3798. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3799. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3800. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  3801. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  3802. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  3803. begin
  3804. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  3805. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3806. RemoveCurrentp(p, hp1);
  3807. Result:=true;
  3808. exit;
  3809. end;
  3810. {$ifdef x86_64}
  3811. { Convert:
  3812. movq x(ref),%reg64
  3813. shrq y,%reg64
  3814. To:
  3815. movl x+4(ref),%reg32
  3816. shrl y-32,%reg32 (Remove if y = 32)
  3817. }
  3818. if (taicpu(p).opsize = S_Q) and
  3819. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3820. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3821. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3822. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3823. (taicpu(hp1).oper[0]^.val >= 32) and
  3824. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3825. begin
  3826. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3827. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3828. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3829. { Convert to 32-bit }
  3830. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3831. taicpu(p).opsize := S_L;
  3832. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3833. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3834. if (taicpu(hp1).oper[0]^.val = 32) then
  3835. begin
  3836. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3837. RemoveInstruction(hp1);
  3838. end
  3839. else
  3840. begin
  3841. { This will potentially open up more arithmetic operations since
  3842. the peephole optimizer now has a big hint that only the lower
  3843. 32 bits are currently in use (and opcodes are smaller in size) }
  3844. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3845. taicpu(hp1).opsize := S_L;
  3846. Dec(taicpu(hp1).oper[0]^.val, 32);
  3847. DebugMsg(SPeepholeOptimization + PreMessage +
  3848. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3849. end;
  3850. Result := True;
  3851. Exit;
  3852. end;
  3853. {$endif x86_64}
  3854. { Backward optimisation. If we have:
  3855. func. %reg1,%reg2
  3856. mov %reg2,%reg3
  3857. (dealloc %reg2)
  3858. Change to:
  3859. func. %reg1,%reg3 (see comment below for what a valid func. is)
  3860. }
  3861. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3862. begin
  3863. CurrentReg := taicpu(p).oper[0]^.reg;
  3864. ActiveReg := taicpu(p).oper[1]^.reg;
  3865. TransferUsedRegs(TmpUsedRegs);
  3866. if not RegUsedAfterInstruction(CurrentReg, p, TmpUsedRegs) and
  3867. GetLastInstruction(p, hp2) and
  3868. (hp2.typ = ait_instruction) and
  3869. { Have to make sure it's an instruction that only reads from
  3870. operand 1 and only writes (not reads or modifies) from operand 2;
  3871. in essence, a one-operand pure function such as BSR or POPCNT }
  3872. (taicpu(hp2).ops = 2) and
  3873. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  3874. (taicpu(hp2).oper[1]^.typ = top_reg) and
  3875. (taicpu(hp2).oper[1]^.reg = CurrentReg) then
  3876. begin
  3877. case taicpu(hp2).opcode of
  3878. A_FSTSW, A_FNSTSW,
  3879. A_IN, A_INS, A_OUT, A_OUTS,
  3880. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS,
  3881. { These routines have explicit operands, but they are restricted in
  3882. what they can be (e.g. IN and OUT can only read from AL, AX or
  3883. EAX. }
  3884. A_CMOVcc:
  3885. { CMOV is not valid either because then CurrentReg will depend
  3886. on an unknown value if the condition is False and hence is
  3887. not a pure write }
  3888. ;
  3889. else
  3890. begin
  3891. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  3892. taicpu(hp2).oper[1]^.reg := ActiveReg;
  3893. AllocRegBetween(ActiveReg, hp2, p, TmpUsedRegs);
  3894. RemoveCurrentp(p, hp1);
  3895. Result := True;
  3896. Exit;
  3897. end;
  3898. end;
  3899. end;
  3900. end;
  3901. end;
  3902. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  3903. var
  3904. hp1 : tai;
  3905. begin
  3906. Result:=false;
  3907. if taicpu(p).ops <> 2 then
  3908. exit;
  3909. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  3910. GetNextInstruction(p,hp1) then
  3911. begin
  3912. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  3913. (taicpu(hp1).ops = 2) then
  3914. begin
  3915. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3916. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3917. { movXX reg1, mem1 or movXX mem1, reg1
  3918. movXX mem2, reg2 movXX reg2, mem2}
  3919. begin
  3920. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3921. { movXX reg1, mem1 or movXX mem1, reg1
  3922. movXX mem2, reg1 movXX reg2, mem1}
  3923. begin
  3924. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3925. begin
  3926. { Removes the second statement from
  3927. movXX reg1, mem1/reg2
  3928. movXX mem1/reg2, reg1
  3929. }
  3930. if taicpu(p).oper[0]^.typ=top_reg then
  3931. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3932. { Removes the second statement from
  3933. movXX mem1/reg1, reg2
  3934. movXX reg2, mem1/reg1
  3935. }
  3936. if (taicpu(p).oper[1]^.typ=top_reg) and
  3937. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  3938. begin
  3939. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  3940. RemoveInstruction(hp1);
  3941. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  3942. Result:=true;
  3943. exit;
  3944. end
  3945. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  3946. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  3947. begin
  3948. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  3949. RemoveInstruction(hp1);
  3950. Result:=true;
  3951. exit;
  3952. end;
  3953. end
  3954. end;
  3955. end;
  3956. end;
  3957. end;
  3958. end;
  3959. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  3960. var
  3961. hp1 : tai;
  3962. begin
  3963. result:=false;
  3964. { replace
  3965. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  3966. MovX %mreg2,%mreg1
  3967. dealloc %mreg2
  3968. by
  3969. <Op>X %mreg2,%mreg1
  3970. ?
  3971. }
  3972. if GetNextInstruction(p,hp1) and
  3973. { we mix single and double opperations here because we assume that the compiler
  3974. generates vmovapd only after double operations and vmovaps only after single operations }
  3975. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  3976. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3977. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  3978. (taicpu(p).oper[0]^.typ=top_reg) then
  3979. begin
  3980. TransferUsedRegs(TmpUsedRegs);
  3981. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3982. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3983. begin
  3984. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  3985. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3986. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  3987. RemoveInstruction(hp1);
  3988. result:=true;
  3989. end;
  3990. end;
  3991. end;
  3992. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  3993. var
  3994. hp1, p_label, p_dist, hp1_dist: tai;
  3995. JumpLabel, JumpLabel_dist: TAsmLabel;
  3996. FirstValue, SecondValue: TCGInt;
  3997. begin
  3998. Result := False;
  3999. if (taicpu(p).oper[0]^.typ = top_const) and
  4000. (taicpu(p).oper[0]^.val <> -1) then
  4001. begin
  4002. { Convert unsigned maximum constants to -1 to aid optimisation }
  4003. case taicpu(p).opsize of
  4004. S_B:
  4005. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4006. begin
  4007. taicpu(p).oper[0]^.val := -1;
  4008. Result := True;
  4009. Exit;
  4010. end;
  4011. S_W:
  4012. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4013. begin
  4014. taicpu(p).oper[0]^.val := -1;
  4015. Result := True;
  4016. Exit;
  4017. end;
  4018. S_L:
  4019. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4020. begin
  4021. taicpu(p).oper[0]^.val := -1;
  4022. Result := True;
  4023. Exit;
  4024. end;
  4025. {$ifdef x86_64}
  4026. S_Q:
  4027. { Storing anything greater than $7FFFFFFF is not possible so do
  4028. nothing };
  4029. {$endif x86_64}
  4030. else
  4031. InternalError(2021121001);
  4032. end;
  4033. end;
  4034. if GetNextInstruction(p, hp1) and
  4035. TrySwapMovCmp(p, hp1) then
  4036. begin
  4037. Result := True;
  4038. Exit;
  4039. end;
  4040. { Search for:
  4041. test $x,(reg/ref)
  4042. jne @lbl1
  4043. test $y,(reg/ref) (same register or reference)
  4044. jne @lbl1
  4045. Change to:
  4046. test $(x or y),(reg/ref)
  4047. jne @lbl1
  4048. (Note, this doesn't work with je instead of jne)
  4049. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4050. Also search for:
  4051. test $x,(reg/ref)
  4052. je @lbl1
  4053. test $y,(reg/ref)
  4054. je/jne @lbl2
  4055. If (x or y) = x, then the second jump is deterministic
  4056. }
  4057. if (
  4058. (
  4059. (taicpu(p).oper[0]^.typ = top_const) or
  4060. (
  4061. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4062. (taicpu(p).oper[0]^.typ = top_reg) and
  4063. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4064. )
  4065. ) and
  4066. MatchInstruction(hp1, A_JCC, [])
  4067. ) then
  4068. begin
  4069. if (taicpu(p).oper[0]^.typ = top_reg) and
  4070. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4071. FirstValue := -1
  4072. else
  4073. FirstValue := taicpu(p).oper[0]^.val;
  4074. { If we have several test/jne's in a row, it might be the case that
  4075. the second label doesn't go to the same location, but the one
  4076. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4077. so accommodate for this with a while loop.
  4078. }
  4079. hp1_dist := hp1;
  4080. if GetNextInstruction(hp1, p_dist) and
  4081. (p_dist.typ = ait_instruction) and
  4082. (
  4083. (
  4084. (taicpu(p_dist).opcode = A_TEST) and
  4085. (
  4086. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4087. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4088. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4089. )
  4090. ) or
  4091. (
  4092. { cmp 0,%reg = test %reg,%reg }
  4093. (taicpu(p_dist).opcode = A_CMP) and
  4094. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4095. )
  4096. ) and
  4097. { Make sure the destination operands are actually the same }
  4098. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4099. GetNextInstruction(p_dist, hp1_dist) and
  4100. MatchInstruction(hp1_dist, A_JCC, []) then
  4101. begin
  4102. if
  4103. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4104. (
  4105. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4106. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4107. ) then
  4108. SecondValue := -1
  4109. else
  4110. SecondValue := taicpu(p_dist).oper[0]^.val;
  4111. { If both of the TEST constants are identical, delete the second
  4112. TEST that is unnecessary. }
  4113. if (FirstValue = SecondValue) then
  4114. begin
  4115. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4116. RemoveInstruction(p_dist);
  4117. { Don't let the flags register become deallocated and reallocated between the jumps }
  4118. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4119. Result := True;
  4120. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4121. begin
  4122. { Since the second jump's condition is a subset of the first, we
  4123. know it will never branch because the first jump dominates it.
  4124. Get it out of the way now rather than wait for the jump
  4125. optimisations for a speed boost. }
  4126. if IsJumpToLabel(taicpu(hp1_dist)) then
  4127. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4128. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4129. RemoveInstruction(hp1_dist);
  4130. end
  4131. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4132. begin
  4133. { If the inverse of the first condition is a subset of the second,
  4134. the second one will definitely branch if the first one doesn't }
  4135. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4136. MakeUnconditional(taicpu(hp1_dist));
  4137. RemoveDeadCodeAfterJump(hp1_dist);
  4138. end;
  4139. Exit;
  4140. end;
  4141. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4142. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4143. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4144. then the second jump will never branch, so it can also be
  4145. removed regardless of where it goes }
  4146. (
  4147. (FirstValue = -1) or
  4148. (SecondValue = -1) or
  4149. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4150. ) then
  4151. begin
  4152. { Same jump location... can be a register since nothing's changed }
  4153. { If any of the entries are equivalent to test %reg,%reg, then the
  4154. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4155. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4156. if IsJumpToLabel(taicpu(hp1_dist)) then
  4157. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4158. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4159. RemoveInstruction(hp1_dist);
  4160. { Only remove the second test if no jumps or other conditional instructions follow }
  4161. TransferUsedRegs(TmpUsedRegs);
  4162. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4163. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4164. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4165. RemoveInstruction(p_dist);
  4166. Result := True;
  4167. Exit;
  4168. end;
  4169. end;
  4170. end;
  4171. { Search for:
  4172. test %reg,%reg
  4173. j(c1) @lbl1
  4174. ...
  4175. @lbl:
  4176. test %reg,%reg (same register)
  4177. j(c2) @lbl2
  4178. If c2 is a subset of c1, change to:
  4179. test %reg,%reg
  4180. j(c1) @lbl2
  4181. (@lbl1 may become a dead label as a result)
  4182. }
  4183. if (taicpu(p).oper[1]^.typ = top_reg) and
  4184. (taicpu(p).oper[0]^.typ = top_reg) and
  4185. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4186. MatchInstruction(hp1, A_JCC, []) and
  4187. IsJumpToLabel(taicpu(hp1)) then
  4188. begin
  4189. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4190. p_label := nil;
  4191. if Assigned(JumpLabel) then
  4192. p_label := getlabelwithsym(JumpLabel);
  4193. if Assigned(p_label) and
  4194. GetNextInstruction(p_label, p_dist) and
  4195. MatchInstruction(p_dist, A_TEST, []) and
  4196. { It's fine if the second test uses smaller sub-registers }
  4197. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4198. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4199. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4200. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4201. GetNextInstruction(p_dist, hp1_dist) and
  4202. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4203. begin
  4204. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4205. if JumpLabel = JumpLabel_dist then
  4206. { This is an infinite loop }
  4207. Exit;
  4208. { Best optimisation when the first condition is a subset (or equal) of the second }
  4209. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4210. begin
  4211. { Any registers used here will already be allocated }
  4212. if Assigned(JumpLabel_dist) then
  4213. JumpLabel_dist.IncRefs;
  4214. if Assigned(JumpLabel) then
  4215. JumpLabel.DecRefs;
  4216. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4217. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4218. Result := True;
  4219. Exit;
  4220. end;
  4221. end;
  4222. end;
  4223. end;
  4224. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4225. var
  4226. hp1, hp2: tai;
  4227. ActiveReg: TRegister;
  4228. OldOffset: asizeint;
  4229. ThisConst: TCGInt;
  4230. function RegDeallocated: Boolean;
  4231. begin
  4232. TransferUsedRegs(TmpUsedRegs);
  4233. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4234. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4235. end;
  4236. begin
  4237. result:=false;
  4238. hp1 := nil;
  4239. { replace
  4240. addX const,%reg1
  4241. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4242. dealloc %reg1
  4243. by
  4244. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4245. }
  4246. if MatchOpType(taicpu(p),top_const,top_reg) then
  4247. begin
  4248. ActiveReg := taicpu(p).oper[1]^.reg;
  4249. { Ensures the entire register was updated }
  4250. if (taicpu(p).opsize >= S_L) and
  4251. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4252. MatchInstruction(hp1,A_LEA,[]) and
  4253. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4254. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4255. (
  4256. { Cover the case where the register in the reference is also the destination register }
  4257. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4258. (
  4259. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4260. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4261. RegDeallocated
  4262. )
  4263. ) then
  4264. begin
  4265. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4266. {$push}
  4267. {$R-}{$Q-}
  4268. { Explicitly disable overflow checking for these offset calculation
  4269. as those do not matter for the final result }
  4270. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4271. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4272. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4273. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4274. {$pop}
  4275. {$ifdef x86_64}
  4276. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4277. begin
  4278. { Overflow; abort }
  4279. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4280. end
  4281. else
  4282. {$endif x86_64}
  4283. begin
  4284. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4285. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4286. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4287. RemoveCurrentP(p, hp1)
  4288. else
  4289. RemoveCurrentP(p);
  4290. result:=true;
  4291. Exit;
  4292. end;
  4293. end;
  4294. if (
  4295. { Save calling GetNextInstructionUsingReg again }
  4296. Assigned(hp1) or
  4297. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4298. ) and
  4299. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4300. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4301. begin
  4302. if taicpu(hp1).oper[0]^.typ = top_const then
  4303. begin
  4304. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4305. if taicpu(hp1).opcode = A_ADD then
  4306. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4307. else
  4308. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4309. Result := True;
  4310. { Handle any overflows }
  4311. case taicpu(p).opsize of
  4312. S_B:
  4313. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4314. S_W:
  4315. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4316. S_L:
  4317. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4318. {$ifdef x86_64}
  4319. S_Q:
  4320. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4321. { Overflow; abort }
  4322. Result := False
  4323. else
  4324. taicpu(p).oper[0]^.val := ThisConst;
  4325. {$endif x86_64}
  4326. else
  4327. InternalError(2021102610);
  4328. end;
  4329. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4330. if Result then
  4331. begin
  4332. if (taicpu(p).oper[0]^.val < 0) and
  4333. (
  4334. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4335. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4336. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4337. ) then
  4338. begin
  4339. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4340. taicpu(p).opcode := A_SUB;
  4341. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4342. end
  4343. else
  4344. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4345. RemoveInstruction(hp1);
  4346. end;
  4347. end
  4348. else
  4349. begin
  4350. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4351. TransferUsedRegs(TmpUsedRegs);
  4352. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4353. hp2 := p;
  4354. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4355. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4356. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4357. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4358. begin
  4359. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4360. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4361. Asml.Remove(p);
  4362. Asml.InsertAfter(p, hp1);
  4363. p := hp1;
  4364. Result := True;
  4365. end;
  4366. end;
  4367. end;
  4368. end;
  4369. end;
  4370. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4371. var
  4372. hp1: tai;
  4373. ref: Integer;
  4374. saveref: treference;
  4375. TempReg: TRegister;
  4376. Multiple: TCGInt;
  4377. begin
  4378. Result:=false;
  4379. { removes seg register prefixes from LEA operations, as they
  4380. don't do anything}
  4381. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  4382. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4383. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4384. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4385. (
  4386. { do not mess with leas accessing the stack pointer
  4387. unless it's a null operation }
  4388. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4389. (
  4390. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4391. (taicpu(p).oper[0]^.ref^.offset = 0)
  4392. )
  4393. ) and
  4394. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4395. begin
  4396. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4397. begin
  4398. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4399. begin
  4400. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4401. taicpu(p).oper[1]^.reg);
  4402. InsertLLItem(p.previous,p.next, hp1);
  4403. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4404. p.free;
  4405. p:=hp1;
  4406. end
  4407. else
  4408. begin
  4409. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4410. RemoveCurrentP(p);
  4411. end;
  4412. Result:=true;
  4413. exit;
  4414. end
  4415. else if (
  4416. { continue to use lea to adjust the stack pointer,
  4417. it is the recommended way, but only if not optimizing for size }
  4418. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4419. (cs_opt_size in current_settings.optimizerswitches)
  4420. ) and
  4421. { If the flags register is in use, don't change the instruction
  4422. to an ADD otherwise this will scramble the flags. [Kit] }
  4423. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4424. ConvertLEA(taicpu(p)) then
  4425. begin
  4426. Result:=true;
  4427. exit;
  4428. end;
  4429. end;
  4430. if GetNextInstruction(p,hp1) and
  4431. (hp1.typ=ait_instruction) then
  4432. begin
  4433. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4434. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4435. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  4436. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  4437. begin
  4438. TransferUsedRegs(TmpUsedRegs);
  4439. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4440. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4441. begin
  4442. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4443. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4444. RemoveInstruction(hp1);
  4445. result:=true;
  4446. exit;
  4447. end;
  4448. end;
  4449. { changes
  4450. lea <ref1>, reg1
  4451. <op> ...,<ref. with reg1>,...
  4452. to
  4453. <op> ...,<ref1>,... }
  4454. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  4455. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  4456. not(MatchInstruction(hp1,A_LEA,[])) then
  4457. begin
  4458. { find a reference which uses reg1 }
  4459. 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
  4460. ref:=0
  4461. 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
  4462. ref:=1
  4463. else
  4464. ref:=-1;
  4465. if (ref<>-1) and
  4466. { reg1 must be either the base or the index }
  4467. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4468. begin
  4469. { reg1 can be removed from the reference }
  4470. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4471. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4472. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4473. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4474. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4475. else
  4476. Internalerror(2019111201);
  4477. { check if the can insert all data of the lea into the second instruction }
  4478. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4479. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4480. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4481. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4482. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4483. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4484. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4485. {$ifdef x86_64}
  4486. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4487. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4488. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4489. )
  4490. {$endif x86_64}
  4491. then
  4492. begin
  4493. { reg1 might not used by the second instruction after it is remove from the reference }
  4494. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4495. begin
  4496. TransferUsedRegs(TmpUsedRegs);
  4497. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4498. { reg1 is not updated so it might not be used afterwards }
  4499. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4500. begin
  4501. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4502. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4503. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4504. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4505. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4506. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4507. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4508. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4509. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4510. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4511. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4512. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4513. RemoveCurrentP(p, hp1);
  4514. result:=true;
  4515. exit;
  4516. end
  4517. end;
  4518. end;
  4519. { recover }
  4520. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4521. end;
  4522. end;
  4523. end;
  4524. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  4525. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  4526. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  4527. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  4528. begin
  4529. { Check common LEA/LEA conditions }
  4530. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4531. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4532. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4533. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4534. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4535. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4536. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4537. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4538. (
  4539. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4540. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4541. ) and (
  4542. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4543. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4544. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4545. ) then
  4546. begin
  4547. { changes
  4548. lea (regX,scale), reg1
  4549. lea offset(reg1,reg1), reg1
  4550. to
  4551. lea offset(regX,scale*2), reg1
  4552. and
  4553. lea (regX,scale1), reg1
  4554. lea offset(reg1,scale2), reg1
  4555. to
  4556. lea offset(regX,scale1*scale2), reg1
  4557. ... so long as the final scale does not exceed 8
  4558. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4559. }
  4560. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  4561. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4562. (
  4563. (
  4564. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4565. ) or (
  4566. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4567. (
  4568. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4569. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4570. )
  4571. )
  4572. ) and (
  4573. (
  4574. { lea (reg1,scale2), reg1 variant }
  4575. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4576. (
  4577. (
  4578. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4579. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4580. ) or (
  4581. { lea (regX,regX), reg1 variant }
  4582. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4583. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4584. )
  4585. )
  4586. ) or (
  4587. { lea (reg1,reg1), reg1 variant }
  4588. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4589. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4590. )
  4591. ) then
  4592. begin
  4593. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4594. { Make everything homogeneous to make calculations easier }
  4595. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4596. begin
  4597. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4598. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4599. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4600. else
  4601. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4602. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4603. end;
  4604. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4605. begin
  4606. { Just to prevent miscalculations }
  4607. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4608. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4609. else
  4610. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4611. end
  4612. else
  4613. begin
  4614. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4615. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4616. end;
  4617. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4618. RemoveCurrentP(p);
  4619. result:=true;
  4620. exit;
  4621. end
  4622. { changes
  4623. lea offset1(regX), reg1
  4624. lea offset2(reg1), reg1
  4625. to
  4626. lea offset1+offset2(regX), reg1 }
  4627. else if
  4628. (
  4629. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4630. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4631. ) or (
  4632. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4633. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4634. (
  4635. (
  4636. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4637. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4638. ) or (
  4639. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4640. (
  4641. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4642. (
  4643. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4644. (
  4645. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4646. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4647. )
  4648. )
  4649. )
  4650. )
  4651. )
  4652. ) then
  4653. begin
  4654. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4655. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4656. begin
  4657. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4658. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4659. { if the register is used as index and base, we have to increase for base as well
  4660. and adapt base }
  4661. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4662. begin
  4663. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4664. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4665. end;
  4666. end
  4667. else
  4668. begin
  4669. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4670. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4671. end;
  4672. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4673. begin
  4674. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4675. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4676. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4677. end;
  4678. RemoveCurrentP(p);
  4679. result:=true;
  4680. exit;
  4681. end;
  4682. end;
  4683. { Change:
  4684. leal/q $x(%reg1),%reg2
  4685. ...
  4686. shll/q $y,%reg2
  4687. To:
  4688. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  4689. }
  4690. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  4691. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4692. (taicpu(hp1).oper[0]^.val <= 3) then
  4693. begin
  4694. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  4695. TransferUsedRegs(TmpUsedRegs);
  4696. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4697. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  4698. if
  4699. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  4700. (this works even if scalefactor is zero) }
  4701. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  4702. { Ensure offset doesn't go out of bounds }
  4703. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  4704. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  4705. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  4706. (
  4707. (
  4708. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  4709. (
  4710. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4711. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  4712. (
  4713. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  4714. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4715. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  4716. )
  4717. )
  4718. ) or (
  4719. (
  4720. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  4721. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  4722. ) and
  4723. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  4724. )
  4725. ) then
  4726. begin
  4727. repeat
  4728. with taicpu(p).oper[0]^.ref^ do
  4729. begin
  4730. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  4731. if index = base then
  4732. begin
  4733. if Multiple > 4 then
  4734. { Optimisation will no longer work because resultant
  4735. scale factor will exceed 8 }
  4736. Break;
  4737. base := NR_NO;
  4738. scalefactor := 2;
  4739. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  4740. end
  4741. else if (base <> NR_NO) and (base <> NR_INVALID) then
  4742. begin
  4743. { Scale factor only works on the index register }
  4744. index := base;
  4745. base := NR_NO;
  4746. end;
  4747. { For safety }
  4748. if scalefactor <= 1 then
  4749. begin
  4750. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  4751. scalefactor := Multiple;
  4752. end
  4753. else
  4754. begin
  4755. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  4756. scalefactor := scalefactor * Multiple;
  4757. end;
  4758. offset := offset * Multiple;
  4759. end;
  4760. RemoveInstruction(hp1);
  4761. Result := True;
  4762. Exit;
  4763. { This repeat..until loop exists for the benefit of Break }
  4764. until True;
  4765. end;
  4766. end;
  4767. end;
  4768. end;
  4769. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  4770. var
  4771. hp1 : tai;
  4772. begin
  4773. DoSubAddOpt := False;
  4774. if taicpu(p).oper[0]^.typ <> top_const then
  4775. { Should have been confirmed before calling }
  4776. InternalError(2021102601);
  4777. if GetLastInstruction(p, hp1) and
  4778. (hp1.typ = ait_instruction) and
  4779. (taicpu(hp1).opsize = taicpu(p).opsize) then
  4780. case taicpu(hp1).opcode Of
  4781. A_DEC:
  4782. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4783. begin
  4784. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  4785. RemoveInstruction(hp1);
  4786. end;
  4787. A_SUB:
  4788. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4789. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4790. begin
  4791. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  4792. RemoveInstruction(hp1);
  4793. end;
  4794. A_ADD:
  4795. begin
  4796. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4797. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4798. begin
  4799. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  4800. RemoveInstruction(hp1);
  4801. if (taicpu(p).oper[0]^.val = 0) then
  4802. begin
  4803. hp1 := tai(p.next);
  4804. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  4805. if not GetLastInstruction(hp1, p) then
  4806. p := hp1;
  4807. DoSubAddOpt := True;
  4808. end
  4809. end;
  4810. end;
  4811. else
  4812. ;
  4813. end;
  4814. end;
  4815. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  4816. begin
  4817. Result := False;
  4818. if UpdateTmpUsedRegs then
  4819. TransferUsedRegs(TmpUsedRegs);
  4820. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4821. { The x86 assemblers have difficulty comparing values against absolute addresses }
  4822. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  4823. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  4824. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  4825. (
  4826. (
  4827. (taicpu(hp1).opcode = A_TEST)
  4828. ) or (
  4829. (taicpu(hp1).opcode = A_CMP) and
  4830. { A sanity check more than anything }
  4831. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  4832. )
  4833. ) then
  4834. begin
  4835. { change
  4836. mov mem, %reg
  4837. cmp/test x, %reg / test %reg,%reg
  4838. (reg deallocated)
  4839. to
  4840. cmp/test x, mem / cmp 0, mem
  4841. }
  4842. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4843. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  4844. begin
  4845. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  4846. if (taicpu(hp1).opcode = A_TEST) and
  4847. (
  4848. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  4849. MatchOperand(taicpu(hp1).oper[0]^, -1)
  4850. ) then
  4851. begin
  4852. taicpu(hp1).opcode := A_CMP;
  4853. taicpu(hp1).loadconst(0, 0);
  4854. end;
  4855. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  4856. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  4857. RemoveCurrentP(p, hp1);
  4858. Result := True;
  4859. Exit;
  4860. end;
  4861. end;
  4862. end;
  4863. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  4864. var
  4865. hp1, hp2: tai;
  4866. ActiveReg: TRegister;
  4867. OldOffset: asizeint;
  4868. ThisConst: TCGInt;
  4869. function RegDeallocated: Boolean;
  4870. begin
  4871. TransferUsedRegs(TmpUsedRegs);
  4872. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4873. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4874. end;
  4875. begin
  4876. Result:=false;
  4877. hp1 := nil;
  4878. { replace
  4879. subX const,%reg1
  4880. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4881. dealloc %reg1
  4882. by
  4883. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  4884. }
  4885. if MatchOpType(taicpu(p),top_const,top_reg) then
  4886. begin
  4887. ActiveReg := taicpu(p).oper[1]^.reg;
  4888. { Ensures the entire register was updated }
  4889. if (taicpu(p).opsize >= S_L) and
  4890. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4891. MatchInstruction(hp1,A_LEA,[]) and
  4892. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4893. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4894. (
  4895. { Cover the case where the register in the reference is also the destination register }
  4896. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4897. (
  4898. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4899. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4900. RegDeallocated
  4901. )
  4902. ) then
  4903. begin
  4904. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4905. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4906. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4907. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4908. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4909. {$ifdef x86_64}
  4910. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4911. begin
  4912. { Overflow; abort }
  4913. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4914. end
  4915. else
  4916. {$endif x86_64}
  4917. begin
  4918. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  4919. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4920. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4921. RemoveCurrentP(p, hp1)
  4922. else
  4923. RemoveCurrentP(p);
  4924. result:=true;
  4925. Exit;
  4926. end;
  4927. end;
  4928. if (
  4929. { Save calling GetNextInstructionUsingReg again }
  4930. Assigned(hp1) or
  4931. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4932. ) and
  4933. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  4934. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4935. begin
  4936. if taicpu(hp1).oper[0]^.typ = top_const then
  4937. begin
  4938. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  4939. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  4940. Result := True;
  4941. { Handle any overflows }
  4942. case taicpu(p).opsize of
  4943. S_B:
  4944. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4945. S_W:
  4946. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4947. S_L:
  4948. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4949. {$ifdef x86_64}
  4950. S_Q:
  4951. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4952. { Overflow; abort }
  4953. Result := False
  4954. else
  4955. taicpu(p).oper[0]^.val := ThisConst;
  4956. {$endif x86_64}
  4957. else
  4958. InternalError(2021102610);
  4959. end;
  4960. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4961. if Result then
  4962. begin
  4963. if (taicpu(p).oper[0]^.val < 0) and
  4964. (
  4965. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4966. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4967. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4968. ) then
  4969. begin
  4970. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  4971. taicpu(p).opcode := A_SUB;
  4972. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4973. end
  4974. else
  4975. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  4976. RemoveInstruction(hp1);
  4977. end;
  4978. end
  4979. else
  4980. begin
  4981. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  4982. TransferUsedRegs(TmpUsedRegs);
  4983. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4984. hp2 := p;
  4985. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4986. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4987. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4988. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4989. begin
  4990. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  4991. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  4992. Asml.Remove(p);
  4993. Asml.InsertAfter(p, hp1);
  4994. p := hp1;
  4995. Result := True;
  4996. Exit;
  4997. end;
  4998. end;
  4999. end;
  5000. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5001. { * change "sub/add const1, reg" or "dec reg" followed by
  5002. "sub const2, reg" to one "sub ..., reg" }
  5003. {$ifdef i386}
  5004. if (taicpu(p).oper[0]^.val = 2) and
  5005. (ActiveReg = NR_ESP) and
  5006. { Don't do the sub/push optimization if the sub }
  5007. { comes from setting up the stack frame (JM) }
  5008. (not(GetLastInstruction(p,hp1)) or
  5009. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5010. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5011. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5012. begin
  5013. hp1 := tai(p.next);
  5014. while Assigned(hp1) and
  5015. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5016. not RegReadByInstruction(NR_ESP,hp1) and
  5017. not RegModifiedByInstruction(NR_ESP,hp1) do
  5018. hp1 := tai(hp1.next);
  5019. if Assigned(hp1) and
  5020. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5021. begin
  5022. taicpu(hp1).changeopsize(S_L);
  5023. if taicpu(hp1).oper[0]^.typ=top_reg then
  5024. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5025. hp1 := tai(p.next);
  5026. RemoveCurrentp(p, hp1);
  5027. Result:=true;
  5028. exit;
  5029. end;
  5030. end;
  5031. {$endif i386}
  5032. if DoSubAddOpt(p) then
  5033. Result:=true;
  5034. end;
  5035. end;
  5036. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5037. var
  5038. TmpBool1,TmpBool2 : Boolean;
  5039. tmpref : treference;
  5040. hp1,hp2: tai;
  5041. mask: tcgint;
  5042. begin
  5043. Result:=false;
  5044. { All these optimisations work on "shl/sal const,%reg" }
  5045. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5046. Exit;
  5047. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5048. (taicpu(p).oper[0]^.val <= 3) then
  5049. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5050. begin
  5051. { should we check the next instruction? }
  5052. TmpBool1 := True;
  5053. { have we found an add/sub which could be
  5054. integrated in the lea? }
  5055. TmpBool2 := False;
  5056. reference_reset(tmpref,2,[]);
  5057. TmpRef.index := taicpu(p).oper[1]^.reg;
  5058. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5059. while TmpBool1 and
  5060. GetNextInstruction(p, hp1) and
  5061. (tai(hp1).typ = ait_instruction) and
  5062. ((((taicpu(hp1).opcode = A_ADD) or
  5063. (taicpu(hp1).opcode = A_SUB)) and
  5064. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5065. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5066. (((taicpu(hp1).opcode = A_INC) or
  5067. (taicpu(hp1).opcode = A_DEC)) and
  5068. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5069. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5070. ((taicpu(hp1).opcode = A_LEA) and
  5071. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5072. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5073. (not GetNextInstruction(hp1,hp2) or
  5074. not instrReadsFlags(hp2)) Do
  5075. begin
  5076. TmpBool1 := False;
  5077. if taicpu(hp1).opcode=A_LEA then
  5078. begin
  5079. if (TmpRef.base = NR_NO) and
  5080. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5081. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5082. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  5083. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5084. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5085. begin
  5086. TmpBool1 := True;
  5087. TmpBool2 := True;
  5088. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5089. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5090. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5091. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5092. RemoveInstruction(hp1);
  5093. end
  5094. end
  5095. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5096. begin
  5097. TmpBool1 := True;
  5098. TmpBool2 := True;
  5099. case taicpu(hp1).opcode of
  5100. A_ADD:
  5101. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5102. A_SUB:
  5103. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5104. else
  5105. internalerror(2019050536);
  5106. end;
  5107. RemoveInstruction(hp1);
  5108. end
  5109. else
  5110. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5111. (((taicpu(hp1).opcode = A_ADD) and
  5112. (TmpRef.base = NR_NO)) or
  5113. (taicpu(hp1).opcode = A_INC) or
  5114. (taicpu(hp1).opcode = A_DEC)) then
  5115. begin
  5116. TmpBool1 := True;
  5117. TmpBool2 := True;
  5118. case taicpu(hp1).opcode of
  5119. A_ADD:
  5120. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5121. A_INC:
  5122. inc(TmpRef.offset);
  5123. A_DEC:
  5124. dec(TmpRef.offset);
  5125. else
  5126. internalerror(2019050535);
  5127. end;
  5128. RemoveInstruction(hp1);
  5129. end;
  5130. end;
  5131. if TmpBool2
  5132. {$ifndef x86_64}
  5133. or
  5134. ((current_settings.optimizecputype < cpu_Pentium2) and
  5135. (taicpu(p).oper[0]^.val <= 3) and
  5136. not(cs_opt_size in current_settings.optimizerswitches))
  5137. {$endif x86_64}
  5138. then
  5139. begin
  5140. if not(TmpBool2) and
  5141. (taicpu(p).oper[0]^.val=1) then
  5142. begin
  5143. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5144. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5145. end
  5146. else
  5147. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  5148. taicpu(p).oper[1]^.reg);
  5149. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5150. InsertLLItem(p.previous, p.next, hp1);
  5151. p.free;
  5152. p := hp1;
  5153. end;
  5154. end
  5155. {$ifndef x86_64}
  5156. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5157. begin
  5158. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5159. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5160. (unlike shl, which is only Tairable in the U pipe) }
  5161. if taicpu(p).oper[0]^.val=1 then
  5162. begin
  5163. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5164. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  5165. InsertLLItem(p.previous, p.next, hp1);
  5166. p.free;
  5167. p := hp1;
  5168. end
  5169. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5170. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5171. else if (taicpu(p).opsize = S_L) and
  5172. (taicpu(p).oper[0]^.val<= 3) then
  5173. begin
  5174. reference_reset(tmpref,2,[]);
  5175. TmpRef.index := taicpu(p).oper[1]^.reg;
  5176. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5177. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  5178. InsertLLItem(p.previous, p.next, hp1);
  5179. p.free;
  5180. p := hp1;
  5181. end;
  5182. end
  5183. {$endif x86_64}
  5184. else if
  5185. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5186. (
  5187. (
  5188. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5189. SetAndTest(hp1, hp2)
  5190. {$ifdef x86_64}
  5191. ) or
  5192. (
  5193. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5194. GetNextInstruction(hp1, hp2) and
  5195. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5196. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5197. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5198. {$endif x86_64}
  5199. )
  5200. ) and
  5201. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5202. begin
  5203. { Change:
  5204. shl x, %reg1
  5205. mov -(1<<x), %reg2
  5206. and %reg2, %reg1
  5207. Or:
  5208. shl x, %reg1
  5209. and -(1<<x), %reg1
  5210. To just:
  5211. shl x, %reg1
  5212. Since the and operation only zeroes bits that are already zero from the shl operation
  5213. }
  5214. case taicpu(p).oper[0]^.val of
  5215. 8:
  5216. mask:=$FFFFFFFFFFFFFF00;
  5217. 16:
  5218. mask:=$FFFFFFFFFFFF0000;
  5219. 32:
  5220. mask:=$FFFFFFFF00000000;
  5221. 63:
  5222. { Constant pre-calculated to prevent overflow errors with Int64 }
  5223. mask:=$8000000000000000;
  5224. else
  5225. begin
  5226. if taicpu(p).oper[0]^.val >= 64 then
  5227. { Shouldn't happen realistically, since the register
  5228. is guaranteed to be set to zero at this point }
  5229. mask := 0
  5230. else
  5231. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5232. end;
  5233. end;
  5234. if taicpu(hp1).oper[0]^.val = mask then
  5235. begin
  5236. { Everything checks out, perform the optimisation, as long as
  5237. the FLAGS register isn't being used}
  5238. TransferUsedRegs(TmpUsedRegs);
  5239. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5240. {$ifdef x86_64}
  5241. if (hp1 <> hp2) then
  5242. begin
  5243. { "shl/mov/and" version }
  5244. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5245. { Don't do the optimisation if the FLAGS register is in use }
  5246. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5247. begin
  5248. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5249. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5250. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5251. begin
  5252. RemoveInstruction(hp1);
  5253. Result := True;
  5254. end;
  5255. { Only set Result to True if the 'mov' instruction was removed }
  5256. RemoveInstruction(hp2);
  5257. end;
  5258. end
  5259. else
  5260. {$endif x86_64}
  5261. begin
  5262. { "shl/and" version }
  5263. { Don't do the optimisation if the FLAGS register is in use }
  5264. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5265. begin
  5266. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5267. RemoveInstruction(hp1);
  5268. Result := True;
  5269. end;
  5270. end;
  5271. Exit;
  5272. end
  5273. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5274. begin
  5275. { Even if the mask doesn't allow for its removal, we might be
  5276. able to optimise the mask for the "shl/and" version, which
  5277. may permit other peephole optimisations }
  5278. {$ifdef DEBUG_AOPTCPU}
  5279. mask := taicpu(hp1).oper[0]^.val and mask;
  5280. if taicpu(hp1).oper[0]^.val <> mask then
  5281. begin
  5282. DebugMsg(
  5283. SPeepholeOptimization +
  5284. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5285. ' to $' + debug_tostr(mask) +
  5286. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5287. taicpu(hp1).oper[0]^.val := mask;
  5288. end;
  5289. {$else DEBUG_AOPTCPU}
  5290. { If debugging is off, just set the operand even if it's the same }
  5291. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5292. {$endif DEBUG_AOPTCPU}
  5293. end;
  5294. end;
  5295. {
  5296. change
  5297. shl/sal const,reg
  5298. <op> ...(...,reg,1),...
  5299. into
  5300. <op> ...(...,reg,1 shl const),...
  5301. if const in 1..3
  5302. }
  5303. if MatchOpType(taicpu(p), top_const, top_reg) and
  5304. (taicpu(p).oper[0]^.val in [1..3]) and
  5305. GetNextInstruction(p, hp1) and
  5306. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5307. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5308. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5309. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5310. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5311. begin
  5312. TransferUsedRegs(TmpUsedRegs);
  5313. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5314. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5315. begin
  5316. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5317. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5318. RemoveCurrentP(p);
  5319. Result:=true;
  5320. end;
  5321. end;
  5322. end;
  5323. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5324. var
  5325. CurrentRef: TReference;
  5326. FullReg: TRegister;
  5327. hp1, hp2: tai;
  5328. begin
  5329. Result := False;
  5330. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5331. Exit;
  5332. { We assume you've checked if the operand is actually a reference by
  5333. this point. If it isn't, you'll most likely get an access violation }
  5334. CurrentRef := first_mov.oper[1]^.ref^;
  5335. { Memory must be aligned }
  5336. if (CurrentRef.offset mod 4) <> 0 then
  5337. Exit;
  5338. Inc(CurrentRef.offset);
  5339. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5340. if MatchOperand(second_mov.oper[0]^, 0) and
  5341. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5342. GetNextInstruction(second_mov, hp1) and
  5343. (hp1.typ = ait_instruction) and
  5344. (taicpu(hp1).opcode = A_MOV) and
  5345. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5346. (taicpu(hp1).oper[0]^.val = 0) then
  5347. begin
  5348. Inc(CurrentRef.offset);
  5349. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5350. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5351. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5352. begin
  5353. case taicpu(hp1).opsize of
  5354. S_B:
  5355. if GetNextInstruction(hp1, hp2) and
  5356. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5357. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5358. (taicpu(hp2).oper[0]^.val = 0) then
  5359. begin
  5360. Inc(CurrentRef.offset);
  5361. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5362. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5363. (taicpu(hp2).opsize = S_B) then
  5364. begin
  5365. RemoveInstruction(hp1);
  5366. RemoveInstruction(hp2);
  5367. first_mov.opsize := S_L;
  5368. if first_mov.oper[0]^.typ = top_reg then
  5369. begin
  5370. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5371. { Reuse second_mov as a MOVZX instruction }
  5372. second_mov.opcode := A_MOVZX;
  5373. second_mov.opsize := S_BL;
  5374. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5375. second_mov.loadreg(1, FullReg);
  5376. first_mov.oper[0]^.reg := FullReg;
  5377. asml.Remove(second_mov);
  5378. asml.InsertBefore(second_mov, first_mov);
  5379. end
  5380. else
  5381. { It's a value }
  5382. begin
  5383. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5384. RemoveInstruction(second_mov);
  5385. end;
  5386. Result := True;
  5387. Exit;
  5388. end;
  5389. end;
  5390. S_W:
  5391. begin
  5392. RemoveInstruction(hp1);
  5393. first_mov.opsize := S_L;
  5394. if first_mov.oper[0]^.typ = top_reg then
  5395. begin
  5396. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5397. { Reuse second_mov as a MOVZX instruction }
  5398. second_mov.opcode := A_MOVZX;
  5399. second_mov.opsize := S_BL;
  5400. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5401. second_mov.loadreg(1, FullReg);
  5402. first_mov.oper[0]^.reg := FullReg;
  5403. asml.Remove(second_mov);
  5404. asml.InsertBefore(second_mov, first_mov);
  5405. end
  5406. else
  5407. { It's a value }
  5408. begin
  5409. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5410. RemoveInstruction(second_mov);
  5411. end;
  5412. Result := True;
  5413. Exit;
  5414. end;
  5415. else
  5416. ;
  5417. end;
  5418. end;
  5419. end;
  5420. end;
  5421. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5422. { returns true if a "continue" should be done after this optimization }
  5423. var
  5424. hp1, hp2: tai;
  5425. begin
  5426. Result := false;
  5427. if MatchOpType(taicpu(p),top_ref) and
  5428. GetNextInstruction(p, hp1) and
  5429. (hp1.typ = ait_instruction) and
  5430. (((taicpu(hp1).opcode = A_FLD) and
  5431. (taicpu(p).opcode = A_FSTP)) or
  5432. ((taicpu(p).opcode = A_FISTP) and
  5433. (taicpu(hp1).opcode = A_FILD))) and
  5434. MatchOpType(taicpu(hp1),top_ref) and
  5435. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5436. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5437. begin
  5438. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5439. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5440. GetNextInstruction(hp1, hp2) and
  5441. (hp2.typ = ait_instruction) and
  5442. IsExitCode(hp2) and
  5443. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5444. not(assigned(current_procinfo.procdef.funcretsym) and
  5445. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5446. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5447. begin
  5448. RemoveInstruction(hp1);
  5449. RemoveCurrentP(p, hp2);
  5450. RemoveLastDeallocForFuncRes(p);
  5451. Result := true;
  5452. end
  5453. else
  5454. { we can do this only in fast math mode as fstp is rounding ...
  5455. ... still disabled as it breaks the compiler and/or rtl }
  5456. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5457. { ... or if another fstp equal to the first one follows }
  5458. (GetNextInstruction(hp1,hp2) and
  5459. (hp2.typ = ait_instruction) and
  5460. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5461. (taicpu(p).opsize=taicpu(hp2).opsize))
  5462. ) and
  5463. { fst can't store an extended/comp value }
  5464. (taicpu(p).opsize <> S_FX) and
  5465. (taicpu(p).opsize <> S_IQ) then
  5466. begin
  5467. if (taicpu(p).opcode = A_FSTP) then
  5468. taicpu(p).opcode := A_FST
  5469. else
  5470. taicpu(p).opcode := A_FIST;
  5471. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5472. RemoveInstruction(hp1);
  5473. end;
  5474. end;
  5475. end;
  5476. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5477. var
  5478. hp1, hp2: tai;
  5479. begin
  5480. result:=false;
  5481. if MatchOpType(taicpu(p),top_reg) and
  5482. GetNextInstruction(p, hp1) and
  5483. (hp1.typ = Ait_Instruction) and
  5484. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5485. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5486. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5487. { change to
  5488. fld reg fxxx reg,st
  5489. fxxxp st, st1 (hp1)
  5490. Remark: non commutative operations must be reversed!
  5491. }
  5492. begin
  5493. case taicpu(hp1).opcode Of
  5494. A_FMULP,A_FADDP,
  5495. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5496. begin
  5497. case taicpu(hp1).opcode Of
  5498. A_FADDP: taicpu(hp1).opcode := A_FADD;
  5499. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  5500. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  5501. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  5502. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  5503. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  5504. else
  5505. internalerror(2019050534);
  5506. end;
  5507. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5508. taicpu(hp1).oper[1]^.reg := NR_ST;
  5509. RemoveCurrentP(p, hp1);
  5510. Result:=true;
  5511. exit;
  5512. end;
  5513. else
  5514. ;
  5515. end;
  5516. end
  5517. else
  5518. if MatchOpType(taicpu(p),top_ref) and
  5519. GetNextInstruction(p, hp2) and
  5520. (hp2.typ = Ait_Instruction) and
  5521. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  5522. (taicpu(p).opsize in [S_FS, S_FL]) and
  5523. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  5524. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  5525. if GetLastInstruction(p, hp1) and
  5526. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  5527. MatchOpType(taicpu(hp1),top_ref) and
  5528. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5529. if ((taicpu(hp2).opcode = A_FMULP) or
  5530. (taicpu(hp2).opcode = A_FADDP)) then
  5531. { change to
  5532. fld/fst mem1 (hp1) fld/fst mem1
  5533. fld mem1 (p) fadd/
  5534. faddp/ fmul st, st
  5535. fmulp st, st1 (hp2) }
  5536. begin
  5537. RemoveCurrentP(p, hp1);
  5538. if (taicpu(hp2).opcode = A_FADDP) then
  5539. taicpu(hp2).opcode := A_FADD
  5540. else
  5541. taicpu(hp2).opcode := A_FMUL;
  5542. taicpu(hp2).oper[1]^.reg := NR_ST;
  5543. end
  5544. else
  5545. { change to
  5546. fld/fst mem1 (hp1) fld/fst mem1
  5547. fld mem1 (p) fld st}
  5548. begin
  5549. taicpu(p).changeopsize(S_FL);
  5550. taicpu(p).loadreg(0,NR_ST);
  5551. end
  5552. else
  5553. begin
  5554. case taicpu(hp2).opcode Of
  5555. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5556. { change to
  5557. fld/fst mem1 (hp1) fld/fst mem1
  5558. fld mem2 (p) fxxx mem2
  5559. fxxxp st, st1 (hp2) }
  5560. begin
  5561. case taicpu(hp2).opcode Of
  5562. A_FADDP: taicpu(p).opcode := A_FADD;
  5563. A_FMULP: taicpu(p).opcode := A_FMUL;
  5564. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  5565. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  5566. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  5567. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  5568. else
  5569. internalerror(2019050533);
  5570. end;
  5571. RemoveInstruction(hp2);
  5572. end
  5573. else
  5574. ;
  5575. end
  5576. end
  5577. end;
  5578. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  5579. begin
  5580. Result := condition_in(cond1, cond2) or
  5581. { Not strictly subsets due to the actual flags checked, but because we're
  5582. comparing integers, E is a subset of AE and GE and their aliases }
  5583. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  5584. end;
  5585. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  5586. var
  5587. v: TCGInt;
  5588. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  5589. FirstMatch: Boolean;
  5590. NewReg: TRegister;
  5591. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  5592. begin
  5593. Result:=false;
  5594. { All these optimisations need a next instruction }
  5595. if not GetNextInstruction(p, hp1) then
  5596. Exit;
  5597. { Search for:
  5598. cmp ###,###
  5599. j(c1) @lbl1
  5600. ...
  5601. @lbl:
  5602. cmp ###.### (same comparison as above)
  5603. j(c2) @lbl2
  5604. If c1 is a subset of c2, change to:
  5605. cmp ###,###
  5606. j(c2) @lbl2
  5607. (@lbl1 may become a dead label as a result)
  5608. }
  5609. { Also handle cases where there are multiple jumps in a row }
  5610. p_jump := hp1;
  5611. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  5612. begin
  5613. if IsJumpToLabel(taicpu(p_jump)) then
  5614. begin
  5615. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  5616. p_label := nil;
  5617. if Assigned(JumpLabel) then
  5618. p_label := getlabelwithsym(JumpLabel);
  5619. if Assigned(p_label) and
  5620. GetNextInstruction(p_label, p_dist) and
  5621. MatchInstruction(p_dist, A_CMP, []) and
  5622. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  5623. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5624. GetNextInstruction(p_dist, hp1_dist) and
  5625. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5626. begin
  5627. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5628. if JumpLabel = JumpLabel_dist then
  5629. { This is an infinite loop }
  5630. Exit;
  5631. { Best optimisation when the first condition is a subset (or equal) of the second }
  5632. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  5633. begin
  5634. { Any registers used here will already be allocated }
  5635. if Assigned(JumpLabel_dist) then
  5636. JumpLabel_dist.IncRefs;
  5637. if Assigned(JumpLabel) then
  5638. JumpLabel.DecRefs;
  5639. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  5640. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  5641. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  5642. Result := True;
  5643. { Don't exit yet. Since p and p_jump haven't actually been
  5644. removed, we can check for more on this iteration }
  5645. end
  5646. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  5647. GetNextInstruction(hp1_dist, hp1_label) and
  5648. SkipAligns(hp1_label, hp1_label) and
  5649. (hp1_label.typ = ait_label) then
  5650. begin
  5651. JumpLabel_far := tai_label(hp1_label).labsym;
  5652. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  5653. { This is an infinite loop }
  5654. Exit;
  5655. if Assigned(JumpLabel_far) then
  5656. begin
  5657. { In this situation, if the first jump branches, the second one will never,
  5658. branch so change the destination label to after the second jump }
  5659. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  5660. if Assigned(JumpLabel) then
  5661. JumpLabel.DecRefs;
  5662. JumpLabel_far.IncRefs;
  5663. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  5664. Result := True;
  5665. { Don't exit yet. Since p and p_jump haven't actually been
  5666. removed, we can check for more on this iteration }
  5667. Continue;
  5668. end;
  5669. end;
  5670. end;
  5671. end;
  5672. { Search for:
  5673. cmp ###,###
  5674. j(c1) @lbl1
  5675. cmp ###,### (same as first)
  5676. Remove second cmp
  5677. }
  5678. if GetNextInstruction(p_jump, hp2) and
  5679. (
  5680. (
  5681. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  5682. (
  5683. (
  5684. MatchOpType(taicpu(p), top_const, top_reg) and
  5685. MatchOpType(taicpu(hp2), top_const, top_reg) and
  5686. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  5687. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5688. ) or (
  5689. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  5690. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  5691. )
  5692. )
  5693. ) or (
  5694. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  5695. MatchOperand(taicpu(p).oper[0]^, 0) and
  5696. (taicpu(p).oper[1]^.typ = top_reg) and
  5697. MatchInstruction(hp2, A_TEST, []) and
  5698. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5699. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  5700. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5701. )
  5702. ) then
  5703. begin
  5704. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  5705. RemoveInstruction(hp2);
  5706. Result := True;
  5707. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  5708. end;
  5709. GetNextInstruction(p_jump, p_jump);
  5710. end;
  5711. {
  5712. Try to optimise the following:
  5713. cmp $x,### ($x and $y can be registers or constants)
  5714. je @lbl1 (only reference)
  5715. cmp $y,### (### are identical)
  5716. @Lbl:
  5717. sete %reg1
  5718. Change to:
  5719. cmp $x,###
  5720. sete %reg2 (allocate new %reg2)
  5721. cmp $y,###
  5722. sete %reg1
  5723. orb %reg2,%reg1
  5724. (dealloc %reg2)
  5725. This adds an instruction (so don't perform under -Os), but it removes
  5726. a conditional branch.
  5727. }
  5728. if not (cs_opt_size in current_settings.optimizerswitches) and
  5729. (
  5730. (hp1 = p_jump) or
  5731. GetNextInstruction(p, hp1)
  5732. ) and
  5733. MatchInstruction(hp1, A_Jcc, []) and
  5734. IsJumpToLabel(taicpu(hp1)) and
  5735. (taicpu(hp1).condition in [C_E, C_Z]) and
  5736. GetNextInstruction(hp1, hp2) and
  5737. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  5738. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  5739. { The first operand of CMP instructions can only be a register or
  5740. immediate anyway, so no need to check }
  5741. GetNextInstruction(hp2, p_label) and
  5742. (p_label.typ = ait_label) and
  5743. (tai_label(p_label).labsym.getrefs = 1) and
  5744. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  5745. GetNextInstruction(p_label, p_dist) and
  5746. MatchInstruction(p_dist, A_SETcc, []) and
  5747. (taicpu(p_dist).condition in [C_E, C_Z]) and
  5748. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  5749. begin
  5750. TransferUsedRegs(TmpUsedRegs);
  5751. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5752. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5753. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  5754. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5755. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  5756. { Get the instruction after the SETcc instruction so we can
  5757. allocate a new register over the entire range }
  5758. GetNextInstruction(p_dist, hp1_dist) then
  5759. begin
  5760. { Register can appear in p if it's not used afterwards, so only
  5761. allocate between hp1 and hp1_dist }
  5762. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  5763. if NewReg <> NR_NO then
  5764. begin
  5765. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  5766. { Change the jump instruction into a SETcc instruction }
  5767. taicpu(hp1).opcode := A_SETcc;
  5768. taicpu(hp1).opsize := S_B;
  5769. taicpu(hp1).loadreg(0, NewReg);
  5770. { This is now a dead label }
  5771. tai_label(p_label).labsym.decrefs;
  5772. { Prefer adding before the next instruction so the FLAGS
  5773. register is deallicated first }
  5774. AsmL.InsertBefore(
  5775. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  5776. hp1_dist
  5777. );
  5778. Result := True;
  5779. { Don't exit yet, as p wasn't changed and hp1, while
  5780. modified, is still intact and might be optimised by the
  5781. SETcc optimisation below }
  5782. end;
  5783. end;
  5784. end;
  5785. if taicpu(p).oper[0]^.typ = top_const then
  5786. begin
  5787. if (taicpu(p).oper[0]^.val = 0) and
  5788. (taicpu(p).oper[1]^.typ = top_reg) and
  5789. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  5790. begin
  5791. hp2 := p;
  5792. FirstMatch := True;
  5793. { When dealing with "cmp $0,%reg", only ZF and SF contain
  5794. anything meaningful once it's converted to "test %reg,%reg";
  5795. additionally, some jumps will always (or never) branch, so
  5796. evaluate every jump immediately following the
  5797. comparison, optimising the conditions if possible.
  5798. Similarly with SETcc... those that are always set to 0 or 1
  5799. are changed to MOV instructions }
  5800. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  5801. (
  5802. GetNextInstruction(hp2, hp1) and
  5803. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  5804. ) do
  5805. begin
  5806. FirstMatch := False;
  5807. case taicpu(hp1).condition of
  5808. C_B, C_C, C_NAE, C_O:
  5809. { For B/NAE:
  5810. Will never branch since an unsigned integer can never be below zero
  5811. For C/O:
  5812. Result cannot overflow because 0 is being subtracted
  5813. }
  5814. begin
  5815. if taicpu(hp1).opcode = A_Jcc then
  5816. begin
  5817. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  5818. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  5819. RemoveInstruction(hp1);
  5820. { Since hp1 was deleted, hp2 must not be updated }
  5821. Continue;
  5822. end
  5823. else
  5824. begin
  5825. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  5826. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  5827. taicpu(hp1).opcode := A_MOV;
  5828. taicpu(hp1).ops := 2;
  5829. taicpu(hp1).condition := C_None;
  5830. taicpu(hp1).opsize := S_B;
  5831. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5832. taicpu(hp1).loadconst(0, 0);
  5833. end;
  5834. end;
  5835. C_BE, C_NA:
  5836. begin
  5837. { Will only branch if equal to zero }
  5838. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  5839. taicpu(hp1).condition := C_E;
  5840. end;
  5841. C_A, C_NBE:
  5842. begin
  5843. { Will only branch if not equal to zero }
  5844. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  5845. taicpu(hp1).condition := C_NE;
  5846. end;
  5847. C_AE, C_NB, C_NC, C_NO:
  5848. begin
  5849. { Will always branch }
  5850. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  5851. if taicpu(hp1).opcode = A_Jcc then
  5852. begin
  5853. MakeUnconditional(taicpu(hp1));
  5854. { Any jumps/set that follow will now be dead code }
  5855. RemoveDeadCodeAfterJump(taicpu(hp1));
  5856. Break;
  5857. end
  5858. else
  5859. begin
  5860. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  5861. taicpu(hp1).opcode := A_MOV;
  5862. taicpu(hp1).ops := 2;
  5863. taicpu(hp1).condition := C_None;
  5864. taicpu(hp1).opsize := S_B;
  5865. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5866. taicpu(hp1).loadconst(0, 1);
  5867. end;
  5868. end;
  5869. C_None:
  5870. InternalError(2020012201);
  5871. C_P, C_PE, C_NP, C_PO:
  5872. { We can't handle parity checks and they should never be generated
  5873. after a general-purpose CMP (it's used in some floating-point
  5874. comparisons that don't use CMP) }
  5875. InternalError(2020012202);
  5876. else
  5877. { Zero/Equality, Sign, their complements and all of the
  5878. signed comparisons do not need to be converted };
  5879. end;
  5880. hp2 := hp1;
  5881. end;
  5882. { Convert the instruction to a TEST }
  5883. taicpu(p).opcode := A_TEST;
  5884. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5885. Result := True;
  5886. Exit;
  5887. end
  5888. else if (taicpu(p).oper[0]^.val = 1) and
  5889. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5890. (taicpu(hp1).condition in [C_L, C_NGE]) then
  5891. begin
  5892. { Convert; To:
  5893. cmp $1,r/m cmp $0,r/m
  5894. jl @lbl jle @lbl
  5895. }
  5896. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  5897. taicpu(p).oper[0]^.val := 0;
  5898. taicpu(hp1).condition := C_LE;
  5899. { If the instruction is now "cmp $0,%reg", convert it to a
  5900. TEST (and effectively do the work of the "cmp $0,%reg" in
  5901. the block above)
  5902. If it's a reference, we can get away with not setting
  5903. Result to True because he haven't evaluated the jump
  5904. in this pass yet.
  5905. }
  5906. if (taicpu(p).oper[1]^.typ = top_reg) then
  5907. begin
  5908. taicpu(p).opcode := A_TEST;
  5909. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5910. Result := True;
  5911. end;
  5912. Exit;
  5913. end
  5914. else if (taicpu(p).oper[1]^.typ = top_reg)
  5915. {$ifdef x86_64}
  5916. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  5917. {$endif x86_64}
  5918. then
  5919. begin
  5920. { cmp register,$8000 neg register
  5921. je target --> jo target
  5922. .... only if register is deallocated before jump.}
  5923. case Taicpu(p).opsize of
  5924. S_B: v:=$80;
  5925. S_W: v:=$8000;
  5926. S_L: v:=qword($80000000);
  5927. else
  5928. internalerror(2013112905);
  5929. end;
  5930. if (taicpu(p).oper[0]^.val=v) and
  5931. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5932. (Taicpu(hp1).condition in [C_E,C_NE]) then
  5933. begin
  5934. TransferUsedRegs(TmpUsedRegs);
  5935. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  5936. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  5937. begin
  5938. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  5939. Taicpu(p).opcode:=A_NEG;
  5940. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  5941. Taicpu(p).clearop(1);
  5942. Taicpu(p).ops:=1;
  5943. if Taicpu(hp1).condition=C_E then
  5944. Taicpu(hp1).condition:=C_O
  5945. else
  5946. Taicpu(hp1).condition:=C_NO;
  5947. Result:=true;
  5948. exit;
  5949. end;
  5950. end;
  5951. end;
  5952. end;
  5953. if TrySwapMovCmp(p, hp1) then
  5954. begin
  5955. Result := True;
  5956. Exit;
  5957. end;
  5958. end;
  5959. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  5960. var
  5961. hp1: tai;
  5962. begin
  5963. {
  5964. remove the second (v)pxor from
  5965. pxor reg,reg
  5966. ...
  5967. pxor reg,reg
  5968. }
  5969. Result:=false;
  5970. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  5971. MatchOpType(taicpu(p),top_reg,top_reg) and
  5972. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  5973. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5974. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  5975. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  5976. begin
  5977. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  5978. RemoveInstruction(hp1);
  5979. Result:=true;
  5980. Exit;
  5981. end
  5982. {
  5983. replace
  5984. pxor reg1,reg1
  5985. movapd/s reg1,reg2
  5986. dealloc reg1
  5987. by
  5988. pxor reg2,reg2
  5989. }
  5990. else if GetNextInstruction(p,hp1) and
  5991. { we mix single and double opperations here because we assume that the compiler
  5992. generates vmovapd only after double operations and vmovaps only after single operations }
  5993. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5994. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  5995. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5996. (taicpu(p).oper[0]^.typ=top_reg) then
  5997. begin
  5998. TransferUsedRegs(TmpUsedRegs);
  5999. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6000. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6001. begin
  6002. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  6003. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6004. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6005. RemoveInstruction(hp1);
  6006. result:=true;
  6007. end;
  6008. end;
  6009. end;
  6010. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6011. var
  6012. hp1: tai;
  6013. begin
  6014. {
  6015. remove the second (v)pxor from
  6016. (v)pxor reg,reg
  6017. ...
  6018. (v)pxor reg,reg
  6019. }
  6020. Result:=false;
  6021. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6022. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6023. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6024. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6025. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6026. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6027. begin
  6028. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  6029. RemoveInstruction(hp1);
  6030. Result:=true;
  6031. Exit;
  6032. end
  6033. else
  6034. Result:=OptPass1VOP(p);
  6035. end;
  6036. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6037. var
  6038. hp1 : tai;
  6039. begin
  6040. result:=false;
  6041. { replace
  6042. IMul const,%mreg1,%mreg2
  6043. Mov %reg2,%mreg3
  6044. dealloc %mreg3
  6045. by
  6046. Imul const,%mreg1,%mreg23
  6047. }
  6048. if (taicpu(p).ops=3) and
  6049. GetNextInstruction(p,hp1) and
  6050. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6051. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6052. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6053. begin
  6054. TransferUsedRegs(TmpUsedRegs);
  6055. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6056. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6057. begin
  6058. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6059. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6060. RemoveInstruction(hp1);
  6061. result:=true;
  6062. end;
  6063. end;
  6064. end;
  6065. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6066. var
  6067. hp1 : tai;
  6068. begin
  6069. result:=false;
  6070. { replace
  6071. IMul %reg0,%reg1,%reg2
  6072. Mov %reg2,%reg3
  6073. dealloc %reg2
  6074. by
  6075. Imul %reg0,%reg1,%reg3
  6076. }
  6077. if GetNextInstruction(p,hp1) and
  6078. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6079. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6080. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6081. begin
  6082. TransferUsedRegs(TmpUsedRegs);
  6083. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6084. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6085. begin
  6086. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6087. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6088. RemoveInstruction(hp1);
  6089. result:=true;
  6090. end;
  6091. end;
  6092. end;
  6093. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6094. var
  6095. hp1: tai;
  6096. begin
  6097. Result:=false;
  6098. { get rid of
  6099. (v)cvtss2sd reg0,<reg1,>reg2
  6100. (v)cvtss2sd reg2,<reg2,>reg0
  6101. }
  6102. if GetNextInstruction(p,hp1) and
  6103. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6104. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6105. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6106. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6107. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6108. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6109. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6110. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6111. )
  6112. ) then
  6113. begin
  6114. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6115. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6116. begin
  6117. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6118. RemoveCurrentP(p);
  6119. RemoveInstruction(hp1);
  6120. end
  6121. else
  6122. begin
  6123. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6124. if taicpu(hp1).opcode=A_CVTSD2SS then
  6125. begin
  6126. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6127. taicpu(p).opcode:=A_MOVAPS;
  6128. end
  6129. else
  6130. begin
  6131. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6132. taicpu(p).opcode:=A_VMOVAPS;
  6133. end;
  6134. taicpu(p).ops:=2;
  6135. RemoveInstruction(hp1);
  6136. end;
  6137. Result:=true;
  6138. Exit;
  6139. end;
  6140. end;
  6141. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6142. var
  6143. hp1, hp2, hp3, hp4, hp5: tai;
  6144. ThisReg: TRegister;
  6145. begin
  6146. Result := False;
  6147. if not GetNextInstruction(p,hp1) or (hp1.typ <> ait_instruction) then
  6148. Exit;
  6149. {
  6150. convert
  6151. j<c> .L1
  6152. mov 1,reg
  6153. jmp .L2
  6154. .L1
  6155. mov 0,reg
  6156. .L2
  6157. into
  6158. mov 0,reg
  6159. set<not(c)> reg
  6160. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6161. would destroy the flag contents
  6162. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6163. executed at the same time as a previous comparison.
  6164. set<not(c)> reg
  6165. movzx reg, reg
  6166. }
  6167. if MatchInstruction(hp1,A_MOV,[]) and
  6168. (taicpu(hp1).oper[0]^.typ = top_const) and
  6169. (
  6170. (
  6171. (taicpu(hp1).oper[1]^.typ = top_reg)
  6172. {$ifdef i386}
  6173. { Under i386, ESI, EDI, EBP and ESP
  6174. don't have an 8-bit representation }
  6175. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6176. {$endif i386}
  6177. ) or (
  6178. {$ifdef i386}
  6179. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6180. {$endif i386}
  6181. (taicpu(hp1).opsize = S_B)
  6182. )
  6183. ) and
  6184. GetNextInstruction(hp1,hp2) and
  6185. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6186. GetNextInstruction(hp2,hp3) and
  6187. SkipAligns(hp3, hp3) and
  6188. (hp3.typ=ait_label) and
  6189. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6190. GetNextInstruction(hp3,hp4) and
  6191. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6192. (taicpu(hp4).oper[0]^.typ = top_const) and
  6193. (
  6194. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6195. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6196. ) and
  6197. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6198. GetNextInstruction(hp4,hp5) and
  6199. SkipAligns(hp5, hp5) and
  6200. (hp5.typ=ait_label) and
  6201. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6202. begin
  6203. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6204. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6205. tai_label(hp3).labsym.DecRefs;
  6206. { If this isn't the only reference to the middle label, we can
  6207. still make a saving - only that the first jump and everything
  6208. that follows will remain. }
  6209. if (tai_label(hp3).labsym.getrefs = 0) then
  6210. begin
  6211. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6212. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6213. else
  6214. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6215. { remove jump, first label and second MOV (also catching any aligns) }
  6216. repeat
  6217. if not GetNextInstruction(hp2, hp3) then
  6218. InternalError(2021040810);
  6219. RemoveInstruction(hp2);
  6220. hp2 := hp3;
  6221. until hp2 = hp5;
  6222. { Don't decrement reference count before the removal loop
  6223. above, otherwise GetNextInstruction won't stop on the
  6224. the label }
  6225. tai_label(hp5).labsym.DecRefs;
  6226. end
  6227. else
  6228. begin
  6229. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6230. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6231. else
  6232. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6233. end;
  6234. taicpu(p).opcode:=A_SETcc;
  6235. taicpu(p).opsize:=S_B;
  6236. taicpu(p).is_jmp:=False;
  6237. if taicpu(hp1).opsize=S_B then
  6238. begin
  6239. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6240. if taicpu(hp1).oper[1]^.typ = top_reg then
  6241. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6242. RemoveInstruction(hp1);
  6243. end
  6244. else
  6245. begin
  6246. { Will be a register because the size can't be S_B otherwise }
  6247. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6248. taicpu(p).loadreg(0, ThisReg);
  6249. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6250. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6251. begin
  6252. case taicpu(hp1).opsize of
  6253. S_W:
  6254. taicpu(hp1).opsize := S_BW;
  6255. S_L:
  6256. taicpu(hp1).opsize := S_BL;
  6257. {$ifdef x86_64}
  6258. S_Q:
  6259. begin
  6260. taicpu(hp1).opsize := S_BL;
  6261. { Change the destination register to 32-bit }
  6262. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6263. end;
  6264. {$endif x86_64}
  6265. else
  6266. InternalError(2021040820);
  6267. end;
  6268. taicpu(hp1).opcode := A_MOVZX;
  6269. taicpu(hp1).loadreg(0, ThisReg);
  6270. end
  6271. else
  6272. begin
  6273. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6274. { hp1 is already a MOV instruction with the correct register }
  6275. taicpu(hp1).loadconst(0, 0);
  6276. { Inserting it right before p will guarantee that the flags are also tracked }
  6277. asml.Remove(hp1);
  6278. asml.InsertBefore(hp1, p);
  6279. end;
  6280. end;
  6281. Result:=true;
  6282. exit;
  6283. end
  6284. end;
  6285. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6286. var
  6287. hp1, hp2, hp3: tai;
  6288. SourceRef, TargetRef: TReference;
  6289. CurrentReg: TRegister;
  6290. begin
  6291. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6292. if not UseAVX then
  6293. InternalError(2021100501);
  6294. Result := False;
  6295. { Look for the following to simplify:
  6296. vmovdqa/u x(mem1), %xmmreg
  6297. vmovdqa/u %xmmreg, y(mem2)
  6298. vmovdqa/u x+16(mem1), %xmmreg
  6299. vmovdqa/u %xmmreg, y+16(mem2)
  6300. Change to:
  6301. vmovdqa/u x(mem1), %ymmreg
  6302. vmovdqa/u %ymmreg, y(mem2)
  6303. vpxor %ymmreg, %ymmreg, %ymmreg
  6304. ( The VPXOR instruction is to zero the upper half, thus removing the
  6305. need to call the potentially expensive VZEROUPPER instruction. Other
  6306. peephole optimisations can remove VPXOR if it's unnecessary )
  6307. }
  6308. TransferUsedRegs(TmpUsedRegs);
  6309. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6310. { NOTE: In the optimisations below, if the references dictate that an
  6311. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6312. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6313. if (taicpu(p).opsize = S_XMM) and
  6314. MatchOpType(taicpu(p), top_ref, top_reg) and
  6315. GetNextInstruction(p, hp1) and
  6316. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6317. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6318. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6319. begin
  6320. SourceRef := taicpu(p).oper[0]^.ref^;
  6321. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6322. if GetNextInstruction(hp1, hp2) and
  6323. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6324. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6325. begin
  6326. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6327. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6328. Inc(SourceRef.offset, 16);
  6329. { Reuse the register in the first block move }
  6330. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6331. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6332. begin
  6333. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6334. Inc(TargetRef.offset, 16);
  6335. if GetNextInstruction(hp2, hp3) and
  6336. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6337. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6338. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6339. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6340. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6341. begin
  6342. { Update the register tracking to the new size }
  6343. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6344. { Remember that the offsets are 16 ahead }
  6345. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6346. if not (
  6347. ((SourceRef.offset mod 32) = 16) and
  6348. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6349. ) then
  6350. taicpu(p).opcode := A_VMOVDQU;
  6351. taicpu(p).opsize := S_YMM;
  6352. taicpu(p).oper[1]^.reg := CurrentReg;
  6353. if not (
  6354. ((TargetRef.offset mod 32) = 16) and
  6355. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6356. ) then
  6357. taicpu(hp1).opcode := A_VMOVDQU;
  6358. taicpu(hp1).opsize := S_YMM;
  6359. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6360. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6361. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6362. if (pi_uses_ymm in current_procinfo.flags) then
  6363. RemoveInstruction(hp2)
  6364. else
  6365. begin
  6366. taicpu(hp2).opcode := A_VPXOR;
  6367. taicpu(hp2).opsize := S_YMM;
  6368. taicpu(hp2).loadreg(0, CurrentReg);
  6369. taicpu(hp2).loadreg(1, CurrentReg);
  6370. taicpu(hp2).loadreg(2, CurrentReg);
  6371. taicpu(hp2).ops := 3;
  6372. end;
  6373. RemoveInstruction(hp3);
  6374. Result := True;
  6375. Exit;
  6376. end;
  6377. end
  6378. else
  6379. begin
  6380. { See if the next references are 16 less rather than 16 greater }
  6381. Dec(SourceRef.offset, 32); { -16 the other way }
  6382. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6383. begin
  6384. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6385. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6386. if GetNextInstruction(hp2, hp3) and
  6387. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6388. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6389. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6390. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6391. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6392. begin
  6393. { Update the register tracking to the new size }
  6394. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6395. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6396. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6397. if not(
  6398. ((SourceRef.offset mod 32) = 0) and
  6399. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6400. ) then
  6401. taicpu(hp2).opcode := A_VMOVDQU;
  6402. taicpu(hp2).opsize := S_YMM;
  6403. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6404. if not (
  6405. ((TargetRef.offset mod 32) = 0) and
  6406. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6407. ) then
  6408. taicpu(hp3).opcode := A_VMOVDQU;
  6409. taicpu(hp3).opsize := S_YMM;
  6410. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6411. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6412. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6413. if (pi_uses_ymm in current_procinfo.flags) then
  6414. RemoveInstruction(hp1)
  6415. else
  6416. begin
  6417. taicpu(hp1).opcode := A_VPXOR;
  6418. taicpu(hp1).opsize := S_YMM;
  6419. taicpu(hp1).loadreg(0, CurrentReg);
  6420. taicpu(hp1).loadreg(1, CurrentReg);
  6421. taicpu(hp1).loadreg(2, CurrentReg);
  6422. taicpu(hp1).ops := 3;
  6423. Asml.Remove(hp1);
  6424. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  6425. end;
  6426. RemoveCurrentP(p, hp2);
  6427. Result := True;
  6428. Exit;
  6429. end;
  6430. end;
  6431. end;
  6432. end;
  6433. end;
  6434. end;
  6435. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  6436. var
  6437. hp2, hp3, first_assignment: tai;
  6438. IncCount, OperIdx: Integer;
  6439. OrigLabel: TAsmLabel;
  6440. begin
  6441. Count := 0;
  6442. Result := False;
  6443. first_assignment := nil;
  6444. if (LoopCount >= 20) then
  6445. begin
  6446. { Guard against infinite loops }
  6447. Exit;
  6448. end;
  6449. if (taicpu(p).oper[0]^.typ <> top_ref) or
  6450. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  6451. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  6452. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  6453. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  6454. Exit;
  6455. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6456. {
  6457. change
  6458. jmp .L1
  6459. ...
  6460. .L1:
  6461. mov ##, ## ( multiple movs possible )
  6462. jmp/ret
  6463. into
  6464. mov ##, ##
  6465. jmp/ret
  6466. }
  6467. if not Assigned(hp1) then
  6468. begin
  6469. hp1 := GetLabelWithSym(OrigLabel);
  6470. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  6471. Exit;
  6472. end;
  6473. hp2 := hp1;
  6474. while Assigned(hp2) do
  6475. begin
  6476. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  6477. SkipLabels(hp2,hp2);
  6478. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  6479. Break;
  6480. case taicpu(hp2).opcode of
  6481. A_MOVSS:
  6482. begin
  6483. if taicpu(hp2).ops = 0 then
  6484. { Wrong MOVSS }
  6485. Break;
  6486. Inc(Count);
  6487. if Count >= 5 then
  6488. { Too many to be worthwhile }
  6489. Break;
  6490. GetNextInstruction(hp2, hp2);
  6491. Continue;
  6492. end;
  6493. A_MOV,
  6494. A_MOVD,
  6495. A_MOVQ,
  6496. A_MOVSX,
  6497. {$ifdef x86_64}
  6498. A_MOVSXD,
  6499. {$endif x86_64}
  6500. A_MOVZX,
  6501. A_MOVAPS,
  6502. A_MOVUPS,
  6503. A_MOVSD,
  6504. A_MOVAPD,
  6505. A_MOVUPD,
  6506. A_MOVDQA,
  6507. A_MOVDQU,
  6508. A_VMOVSS,
  6509. A_VMOVAPS,
  6510. A_VMOVUPS,
  6511. A_VMOVSD,
  6512. A_VMOVAPD,
  6513. A_VMOVUPD,
  6514. A_VMOVDQA,
  6515. A_VMOVDQU:
  6516. begin
  6517. Inc(Count);
  6518. if Count >= 5 then
  6519. { Too many to be worthwhile }
  6520. Break;
  6521. GetNextInstruction(hp2, hp2);
  6522. Continue;
  6523. end;
  6524. A_JMP:
  6525. begin
  6526. { Guard against infinite loops }
  6527. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  6528. Exit;
  6529. { Analyse this jump first in case it also duplicates assignments }
  6530. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  6531. begin
  6532. { Something did change! }
  6533. Result := True;
  6534. Inc(Count, IncCount);
  6535. if Count >= 5 then
  6536. begin
  6537. { Too many to be worthwhile }
  6538. Exit;
  6539. end;
  6540. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  6541. Break;
  6542. end;
  6543. Result := True;
  6544. Break;
  6545. end;
  6546. A_RET:
  6547. begin
  6548. Result := True;
  6549. Break;
  6550. end;
  6551. else
  6552. Break;
  6553. end;
  6554. end;
  6555. if Result then
  6556. begin
  6557. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  6558. if Count = 0 then
  6559. begin
  6560. Result := False;
  6561. Exit;
  6562. end;
  6563. hp3 := p;
  6564. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  6565. while True do
  6566. begin
  6567. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  6568. SkipLabels(hp1,hp1);
  6569. if (hp1.typ <> ait_instruction) then
  6570. InternalError(2021040720);
  6571. case taicpu(hp1).opcode of
  6572. A_JMP:
  6573. begin
  6574. { Change the original jump to the new destination }
  6575. OrigLabel.decrefs;
  6576. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  6577. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  6578. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6579. if not Assigned(first_assignment) then
  6580. InternalError(2021040810)
  6581. else
  6582. p := first_assignment;
  6583. Exit;
  6584. end;
  6585. A_RET:
  6586. begin
  6587. { Now change the jump into a RET instruction }
  6588. ConvertJumpToRET(p, hp1);
  6589. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6590. if not Assigned(first_assignment) then
  6591. InternalError(2021040811)
  6592. else
  6593. p := first_assignment;
  6594. Exit;
  6595. end;
  6596. else
  6597. begin
  6598. { Duplicate the MOV instruction }
  6599. hp3:=tai(hp1.getcopy);
  6600. if first_assignment = nil then
  6601. first_assignment := hp3;
  6602. asml.InsertBefore(hp3, p);
  6603. { Make sure the compiler knows about any final registers written here }
  6604. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  6605. with taicpu(hp3).oper[OperIdx]^ do
  6606. begin
  6607. case typ of
  6608. top_ref:
  6609. begin
  6610. if (ref^.base <> NR_NO) and
  6611. (getsupreg(ref^.base) <> RS_ESP) and
  6612. (getsupreg(ref^.base) <> RS_EBP)
  6613. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  6614. then
  6615. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  6616. if (ref^.index <> NR_NO) and
  6617. (getsupreg(ref^.index) <> RS_ESP) and
  6618. (getsupreg(ref^.index) <> RS_EBP)
  6619. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  6620. (ref^.index <> ref^.base) then
  6621. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  6622. end;
  6623. top_reg:
  6624. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  6625. else
  6626. ;
  6627. end;
  6628. end;
  6629. end;
  6630. end;
  6631. if not GetNextInstruction(hp1, hp1) then
  6632. { Should have dropped out earlier }
  6633. InternalError(2021040710);
  6634. end;
  6635. end;
  6636. end;
  6637. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  6638. var
  6639. hp2: tai;
  6640. X: Integer;
  6641. const
  6642. WriteOp: array[0..3] of set of TInsChange = (
  6643. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  6644. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  6645. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  6646. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  6647. RegWriteFlags: array[0..7] of set of TInsChange = (
  6648. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  6649. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  6650. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  6651. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  6652. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  6653. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  6654. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  6655. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  6656. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  6657. begin
  6658. { If we have something like:
  6659. cmp ###,%reg1
  6660. mov 0,%reg2
  6661. And no modified registers are shared, move the instruction to before
  6662. the comparison as this means it can be optimised without worrying
  6663. about the FLAGS register. (CMP/MOV is generated by
  6664. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  6665. As long as the second instruction doesn't use the flags or one of the
  6666. registers used by CMP or TEST (also check any references that use the
  6667. registers), then it can be moved prior to the comparison.
  6668. }
  6669. Result := False;
  6670. if (hp1.typ <> ait_instruction) or
  6671. taicpu(hp1).is_jmp or
  6672. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  6673. Exit;
  6674. { NOP is a pipeline fence, likely marking the beginning of the function
  6675. epilogue, so drop out. Similarly, drop out if POP or RET are
  6676. encountered }
  6677. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  6678. Exit;
  6679. if (taicpu(hp1).opcode = A_MOVSS) and
  6680. (taicpu(hp1).ops = 0) then
  6681. { Wrong MOVSS }
  6682. Exit;
  6683. { Check for writes to specific registers first }
  6684. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  6685. for X := 0 to 7 do
  6686. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  6687. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  6688. Exit;
  6689. for X := 0 to taicpu(hp1).ops - 1 do
  6690. begin
  6691. { Check to see if this operand writes to something }
  6692. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  6693. { And matches something in the CMP/TEST instruction }
  6694. (
  6695. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  6696. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  6697. (
  6698. { If it's a register, make sure the register written to doesn't
  6699. appear in the cmp instruction as part of a reference }
  6700. (taicpu(hp1).oper[X]^.typ = top_reg) and
  6701. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  6702. )
  6703. ) then
  6704. Exit;
  6705. end;
  6706. { The instruction can be safely moved }
  6707. asml.Remove(hp1);
  6708. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  6709. if not GetLastInstruction(p, hp2) then
  6710. asml.InsertBefore(hp1, p)
  6711. else
  6712. asml.InsertAfter(hp1, hp2);
  6713. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  6714. for X := 0 to taicpu(hp1).ops - 1 do
  6715. case taicpu(hp1).oper[X]^.typ of
  6716. top_reg:
  6717. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  6718. top_ref:
  6719. begin
  6720. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  6721. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  6722. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  6723. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  6724. end;
  6725. else
  6726. ;
  6727. end;
  6728. if taicpu(hp1).opcode = A_LEA then
  6729. { The flags will be overwritten by the CMP/TEST instruction }
  6730. ConvertLEA(taicpu(hp1));
  6731. Result := True;
  6732. end;
  6733. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  6734. function IsXCHGAcceptable: Boolean; inline;
  6735. begin
  6736. { Always accept if optimising for size }
  6737. Result := (cs_opt_size in current_settings.optimizerswitches) or
  6738. (
  6739. {$ifdef x86_64}
  6740. { XCHG takes 3 cycles on AMD Athlon64 }
  6741. (current_settings.optimizecputype >= cpu_core_i)
  6742. {$else x86_64}
  6743. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  6744. than 3, so it becomes a saving compared to three MOVs with two of
  6745. them able to execute simultaneously. [Kit] }
  6746. (current_settings.optimizecputype >= cpu_PentiumM)
  6747. {$endif x86_64}
  6748. );
  6749. end;
  6750. var
  6751. NewRef: TReference;
  6752. hp1, hp2, hp3, hp4: Tai;
  6753. {$ifndef x86_64}
  6754. OperIdx: Integer;
  6755. {$endif x86_64}
  6756. NewInstr : Taicpu;
  6757. NewAligh : Tai_align;
  6758. DestLabel: TAsmLabel;
  6759. function TryMovArith2Lea(InputInstr: tai): Boolean;
  6760. var
  6761. NextInstr: tai;
  6762. begin
  6763. Result := False;
  6764. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  6765. if not GetNextInstruction(InputInstr, NextInstr) or
  6766. (
  6767. { The FLAGS register isn't always tracked properly, so do not
  6768. perform this optimisation if a conditional statement follows }
  6769. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  6770. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  6771. ) then
  6772. begin
  6773. reference_reset(NewRef, 1, []);
  6774. NewRef.base := taicpu(p).oper[0]^.reg;
  6775. NewRef.scalefactor := 1;
  6776. if taicpu(InputInstr).opcode = A_ADD then
  6777. begin
  6778. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  6779. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  6780. end
  6781. else
  6782. begin
  6783. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  6784. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  6785. end;
  6786. taicpu(p).opcode := A_LEA;
  6787. taicpu(p).loadref(0, NewRef);
  6788. RemoveInstruction(InputInstr);
  6789. Result := True;
  6790. end;
  6791. end;
  6792. begin
  6793. Result:=false;
  6794. { This optimisation adds an instruction, so only do it for speed }
  6795. if not (cs_opt_size in current_settings.optimizerswitches) and
  6796. MatchOpType(taicpu(p), top_const, top_reg) and
  6797. (taicpu(p).oper[0]^.val = 0) then
  6798. begin
  6799. { To avoid compiler warning }
  6800. DestLabel := nil;
  6801. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  6802. InternalError(2021040750);
  6803. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  6804. Exit;
  6805. case hp1.typ of
  6806. ait_label:
  6807. begin
  6808. { Change:
  6809. mov $0,%reg mov $0,%reg
  6810. @Lbl1: @Lbl1:
  6811. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  6812. je @Lbl2 jne @Lbl2
  6813. To: To:
  6814. mov $0,%reg mov $0,%reg
  6815. jmp @Lbl2 jmp @Lbl3
  6816. (align) (align)
  6817. @Lbl1: @Lbl1:
  6818. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  6819. je @Lbl2 je @Lbl2
  6820. @Lbl3: <-- Only if label exists
  6821. (Not if it's optimised for size)
  6822. }
  6823. if not GetNextInstruction(hp1, hp2) then
  6824. Exit;
  6825. if not (cs_opt_size in current_settings.optimizerswitches) and
  6826. (hp2.typ = ait_instruction) and
  6827. (
  6828. { Register sizes must exactly match }
  6829. (
  6830. (taicpu(hp2).opcode = A_CMP) and
  6831. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  6832. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  6833. ) or (
  6834. (taicpu(hp2).opcode = A_TEST) and
  6835. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  6836. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  6837. )
  6838. ) and GetNextInstruction(hp2, hp3) and
  6839. (hp3.typ = ait_instruction) and
  6840. (taicpu(hp3).opcode = A_JCC) and
  6841. (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
  6842. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  6843. begin
  6844. { Check condition of jump }
  6845. { Always true? }
  6846. if condition_in(C_E, taicpu(hp3).condition) then
  6847. begin
  6848. { Copy label symbol and obtain matching label entry for the
  6849. conditional jump, as this will be our destination}
  6850. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  6851. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  6852. Result := True;
  6853. end
  6854. { Always false? }
  6855. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  6856. begin
  6857. { This is only worth it if there's a jump to take }
  6858. case hp2.typ of
  6859. ait_instruction:
  6860. begin
  6861. if taicpu(hp2).opcode = A_JMP then
  6862. begin
  6863. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  6864. { An unconditional jump follows the conditional jump which will always be false,
  6865. so use this jump's destination for the new jump }
  6866. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  6867. Result := True;
  6868. end
  6869. else if taicpu(hp2).opcode = A_JCC then
  6870. begin
  6871. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  6872. if condition_in(C_E, taicpu(hp2).condition) then
  6873. begin
  6874. { A second conditional jump follows the conditional jump which will always be false,
  6875. while the second jump is always True, so use this jump's destination for the new jump }
  6876. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  6877. Result := True;
  6878. end;
  6879. { Don't risk it if the jump isn't always true (Result remains False) }
  6880. end;
  6881. end;
  6882. else
  6883. { If anything else don't optimise };
  6884. end;
  6885. end;
  6886. if Result then
  6887. begin
  6888. { Just so we have something to insert as a paremeter}
  6889. reference_reset(NewRef, 1, []);
  6890. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  6891. { Now actually load the correct parameter }
  6892. NewInstr.loadsymbol(0, DestLabel, 0);
  6893. { Get instruction before original label (may not be p under -O3) }
  6894. if not GetLastInstruction(hp1, hp2) then
  6895. { Shouldn't fail here }
  6896. InternalError(2021040701);
  6897. DestLabel.increfs;
  6898. AsmL.InsertAfter(NewInstr, hp2);
  6899. { Add new alignment field }
  6900. (* AsmL.InsertAfter(
  6901. cai_align.create_max(
  6902. current_settings.alignment.jumpalign,
  6903. current_settings.alignment.jumpalignskipmax
  6904. ),
  6905. NewInstr
  6906. ); *)
  6907. end;
  6908. Exit;
  6909. end;
  6910. end;
  6911. else
  6912. ;
  6913. end;
  6914. end;
  6915. if not GetNextInstruction(p, hp1) then
  6916. Exit;
  6917. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  6918. and DoMovCmpMemOpt(p, hp1, True) then
  6919. begin
  6920. Result := True;
  6921. Exit;
  6922. end
  6923. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  6924. begin
  6925. { Sometimes the MOVs that OptPass2JMP produces can be improved
  6926. further, but we can't just put this jump optimisation in pass 1
  6927. because it tends to perform worse when conditional jumps are
  6928. nearby (e.g. when converting CMOV instructions). [Kit] }
  6929. if OptPass2JMP(hp1) then
  6930. { call OptPass1MOV once to potentially merge any MOVs that were created }
  6931. Result := OptPass1MOV(p)
  6932. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  6933. returned True and the instruction is still a MOV, thus checking
  6934. the optimisations below }
  6935. { If OptPass2JMP returned False, no optimisations were done to
  6936. the jump and there are no further optimisations that can be done
  6937. to the MOV instruction on this pass }
  6938. end
  6939. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6940. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  6941. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  6942. (taicpu(hp1).oper[1]^.typ = top_reg) and
  6943. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  6944. begin
  6945. { Change:
  6946. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  6947. addl/q $x,%reg2 subl/q $x,%reg2
  6948. To:
  6949. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  6950. }
  6951. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6952. { be lazy, checking separately for sub would be slightly better }
  6953. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  6954. begin
  6955. TransferUsedRegs(TmpUsedRegs);
  6956. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6957. if TryMovArith2Lea(hp1) then
  6958. begin
  6959. Result := True;
  6960. Exit;
  6961. end
  6962. end
  6963. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  6964. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  6965. { Same as above, but also adds or subtracts to %reg2 in between.
  6966. It's still valid as long as the flags aren't in use }
  6967. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  6968. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6969. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  6970. { be lazy, checking separately for sub would be slightly better }
  6971. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  6972. begin
  6973. TransferUsedRegs(TmpUsedRegs);
  6974. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6975. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6976. if TryMovArith2Lea(hp2) then
  6977. begin
  6978. Result := True;
  6979. Exit;
  6980. end;
  6981. end;
  6982. end
  6983. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6984. {$ifdef x86_64}
  6985. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  6986. {$else x86_64}
  6987. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  6988. {$endif x86_64}
  6989. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6990. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  6991. { mov reg1, reg2 mov reg1, reg2
  6992. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  6993. begin
  6994. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6995. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  6996. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  6997. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  6998. TransferUsedRegs(TmpUsedRegs);
  6999. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7000. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  7001. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  7002. then
  7003. begin
  7004. RemoveCurrentP(p, hp1);
  7005. Result:=true;
  7006. end;
  7007. exit;
  7008. end
  7009. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7010. IsXCHGAcceptable and
  7011. { XCHG doesn't support 8-byte registers }
  7012. (taicpu(p).opsize <> S_B) and
  7013. MatchInstruction(hp1, A_MOV, []) and
  7014. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7015. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7016. GetNextInstruction(hp1, hp2) and
  7017. MatchInstruction(hp2, A_MOV, []) and
  7018. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7019. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7020. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7021. begin
  7022. { mov %reg1,%reg2
  7023. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7024. mov %reg2,%reg3
  7025. (%reg2 not used afterwards)
  7026. Note that xchg takes 3 cycles to execute, and generally mov's take
  7027. only one cycle apiece, but the first two mov's can be executed in
  7028. parallel, only taking 2 cycles overall. Older processors should
  7029. therefore only optimise for size. [Kit]
  7030. }
  7031. TransferUsedRegs(TmpUsedRegs);
  7032. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7033. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7034. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7035. begin
  7036. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7037. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7038. taicpu(hp1).opcode := A_XCHG;
  7039. RemoveCurrentP(p, hp1);
  7040. RemoveInstruction(hp2);
  7041. Result := True;
  7042. Exit;
  7043. end;
  7044. end
  7045. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7046. MatchInstruction(hp1, A_SAR, []) then
  7047. begin
  7048. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  7049. begin
  7050. { the use of %edx also covers the opsize being S_L }
  7051. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7052. begin
  7053. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7054. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7055. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7056. begin
  7057. { Change:
  7058. movl %eax,%edx
  7059. sarl $31,%edx
  7060. To:
  7061. cltd
  7062. }
  7063. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7064. RemoveInstruction(hp1);
  7065. taicpu(p).opcode := A_CDQ;
  7066. taicpu(p).opsize := S_NO;
  7067. taicpu(p).clearop(1);
  7068. taicpu(p).clearop(0);
  7069. taicpu(p).ops:=0;
  7070. Result := True;
  7071. end
  7072. else if (cs_opt_size in current_settings.optimizerswitches) and
  7073. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7074. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7075. begin
  7076. { Change:
  7077. movl %edx,%eax
  7078. sarl $31,%edx
  7079. To:
  7080. movl %edx,%eax
  7081. cltd
  7082. Note that this creates a dependency between the two instructions,
  7083. so only perform if optimising for size.
  7084. }
  7085. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7086. taicpu(hp1).opcode := A_CDQ;
  7087. taicpu(hp1).opsize := S_NO;
  7088. taicpu(hp1).clearop(1);
  7089. taicpu(hp1).clearop(0);
  7090. taicpu(hp1).ops:=0;
  7091. end;
  7092. {$ifndef x86_64}
  7093. end
  7094. { Don't bother if CMOV is supported, because a more optimal
  7095. sequence would have been generated for the Abs() intrinsic }
  7096. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7097. { the use of %eax also covers the opsize being S_L }
  7098. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7099. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7100. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7101. GetNextInstruction(hp1, hp2) and
  7102. MatchInstruction(hp2, A_XOR, [S_L]) and
  7103. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7104. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7105. GetNextInstruction(hp2, hp3) and
  7106. MatchInstruction(hp3, A_SUB, [S_L]) and
  7107. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7108. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7109. begin
  7110. { Change:
  7111. movl %eax,%edx
  7112. sarl $31,%eax
  7113. xorl %eax,%edx
  7114. subl %eax,%edx
  7115. (Instruction that uses %edx)
  7116. (%eax deallocated)
  7117. (%edx deallocated)
  7118. To:
  7119. cltd
  7120. xorl %edx,%eax <-- Note the registers have swapped
  7121. subl %edx,%eax
  7122. (Instruction that uses %eax) <-- %eax rather than %edx
  7123. }
  7124. TransferUsedRegs(TmpUsedRegs);
  7125. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7126. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7127. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7128. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7129. begin
  7130. if GetNextInstruction(hp3, hp4) and
  7131. not RegModifiedByInstruction(NR_EDX, hp4) and
  7132. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7133. begin
  7134. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7135. taicpu(p).opcode := A_CDQ;
  7136. taicpu(p).clearop(1);
  7137. taicpu(p).clearop(0);
  7138. taicpu(p).ops:=0;
  7139. RemoveInstruction(hp1);
  7140. taicpu(hp2).loadreg(0, NR_EDX);
  7141. taicpu(hp2).loadreg(1, NR_EAX);
  7142. taicpu(hp3).loadreg(0, NR_EDX);
  7143. taicpu(hp3).loadreg(1, NR_EAX);
  7144. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7145. { Convert references in the following instruction (hp4) from %edx to %eax }
  7146. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7147. with taicpu(hp4).oper[OperIdx]^ do
  7148. case typ of
  7149. top_reg:
  7150. if getsupreg(reg) = RS_EDX then
  7151. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7152. top_ref:
  7153. begin
  7154. if getsupreg(reg) = RS_EDX then
  7155. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7156. if getsupreg(reg) = RS_EDX then
  7157. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7158. end;
  7159. else
  7160. ;
  7161. end;
  7162. end;
  7163. end;
  7164. {$else x86_64}
  7165. end;
  7166. end
  7167. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7168. { the use of %rdx also covers the opsize being S_Q }
  7169. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7170. begin
  7171. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7172. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7173. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7174. begin
  7175. { Change:
  7176. movq %rax,%rdx
  7177. sarq $63,%rdx
  7178. To:
  7179. cqto
  7180. }
  7181. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7182. RemoveInstruction(hp1);
  7183. taicpu(p).opcode := A_CQO;
  7184. taicpu(p).opsize := S_NO;
  7185. taicpu(p).clearop(1);
  7186. taicpu(p).clearop(0);
  7187. taicpu(p).ops:=0;
  7188. Result := True;
  7189. end
  7190. else if (cs_opt_size in current_settings.optimizerswitches) and
  7191. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7192. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7193. begin
  7194. { Change:
  7195. movq %rdx,%rax
  7196. sarq $63,%rdx
  7197. To:
  7198. movq %rdx,%rax
  7199. cqto
  7200. Note that this creates a dependency between the two instructions,
  7201. so only perform if optimising for size.
  7202. }
  7203. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7204. taicpu(hp1).opcode := A_CQO;
  7205. taicpu(hp1).opsize := S_NO;
  7206. taicpu(hp1).clearop(1);
  7207. taicpu(hp1).clearop(0);
  7208. taicpu(hp1).ops:=0;
  7209. {$endif x86_64}
  7210. end;
  7211. end;
  7212. end
  7213. else if MatchInstruction(hp1, A_MOV, []) and
  7214. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7215. { Though "GetNextInstruction" could be factored out, along with
  7216. the instructions that depend on hp2, it is an expensive call that
  7217. should be delayed for as long as possible, hence we do cheaper
  7218. checks first that are likely to be False. [Kit] }
  7219. begin
  7220. if (
  7221. (
  7222. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7223. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7224. (
  7225. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7226. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7227. )
  7228. ) or
  7229. (
  7230. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7231. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7232. (
  7233. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7234. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7235. )
  7236. )
  7237. ) and
  7238. GetNextInstruction(hp1, hp2) and
  7239. MatchInstruction(hp2, A_SAR, []) and
  7240. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7241. begin
  7242. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7243. begin
  7244. { Change:
  7245. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7246. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7247. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7248. To:
  7249. movl r/m,%eax <- Note the change in register
  7250. cltd
  7251. }
  7252. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7253. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7254. taicpu(p).loadreg(1, NR_EAX);
  7255. taicpu(hp1).opcode := A_CDQ;
  7256. taicpu(hp1).clearop(1);
  7257. taicpu(hp1).clearop(0);
  7258. taicpu(hp1).ops:=0;
  7259. RemoveInstruction(hp2);
  7260. (*
  7261. {$ifdef x86_64}
  7262. end
  7263. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7264. { This code sequence does not get generated - however it might become useful
  7265. if and when 128-bit signed integer types make an appearance, so the code
  7266. is kept here for when it is eventually needed. [Kit] }
  7267. (
  7268. (
  7269. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7270. (
  7271. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7272. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7273. )
  7274. ) or
  7275. (
  7276. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7277. (
  7278. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7279. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7280. )
  7281. )
  7282. ) and
  7283. GetNextInstruction(hp1, hp2) and
  7284. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7285. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7286. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7287. begin
  7288. { Change:
  7289. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7290. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7291. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7292. To:
  7293. movq r/m,%rax <- Note the change in register
  7294. cqto
  7295. }
  7296. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7297. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7298. taicpu(p).loadreg(1, NR_RAX);
  7299. taicpu(hp1).opcode := A_CQO;
  7300. taicpu(hp1).clearop(1);
  7301. taicpu(hp1).clearop(0);
  7302. taicpu(hp1).ops:=0;
  7303. RemoveInstruction(hp2);
  7304. {$endif x86_64}
  7305. *)
  7306. end;
  7307. end;
  7308. {$ifdef x86_64}
  7309. end
  7310. else if (taicpu(p).opsize = S_L) and
  7311. (taicpu(p).oper[1]^.typ = top_reg) and
  7312. (
  7313. MatchInstruction(hp1, A_MOV,[]) and
  7314. (taicpu(hp1).opsize = S_L) and
  7315. (taicpu(hp1).oper[1]^.typ = top_reg)
  7316. ) and (
  7317. GetNextInstruction(hp1, hp2) and
  7318. (tai(hp2).typ=ait_instruction) and
  7319. (taicpu(hp2).opsize = S_Q) and
  7320. (
  7321. (
  7322. MatchInstruction(hp2, A_ADD,[]) and
  7323. (taicpu(hp2).opsize = S_Q) and
  7324. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7325. (
  7326. (
  7327. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7328. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7329. ) or (
  7330. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7331. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7332. )
  7333. )
  7334. ) or (
  7335. MatchInstruction(hp2, A_LEA,[]) and
  7336. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7337. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7338. (
  7339. (
  7340. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7341. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7342. ) or (
  7343. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7344. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7345. )
  7346. ) and (
  7347. (
  7348. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7349. ) or (
  7350. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7351. )
  7352. )
  7353. )
  7354. )
  7355. ) and (
  7356. GetNextInstruction(hp2, hp3) and
  7357. MatchInstruction(hp3, A_SHR,[]) and
  7358. (taicpu(hp3).opsize = S_Q) and
  7359. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7360. (taicpu(hp3).oper[0]^.val = 1) and
  7361. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7362. ) then
  7363. begin
  7364. { Change movl x, reg1d movl x, reg1d
  7365. movl y, reg2d movl y, reg2d
  7366. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7367. shrq $1, reg1q shrq $1, reg1q
  7368. ( reg1d and reg2d can be switched around in the first two instructions )
  7369. To movl x, reg1d
  7370. addl y, reg1d
  7371. rcrl $1, reg1d
  7372. This corresponds to the common expression (x + y) shr 1, where
  7373. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7374. smaller code, but won't account for x + y causing an overflow). [Kit]
  7375. }
  7376. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7377. { Change first MOV command to have the same register as the final output }
  7378. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7379. else
  7380. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7381. { Change second MOV command to an ADD command. This is easier than
  7382. converting the existing command because it means we don't have to
  7383. touch 'y', which might be a complicated reference, and also the
  7384. fact that the third command might either be ADD or LEA. [Kit] }
  7385. taicpu(hp1).opcode := A_ADD;
  7386. { Delete old ADD/LEA instruction }
  7387. RemoveInstruction(hp2);
  7388. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7389. taicpu(hp3).opcode := A_RCR;
  7390. taicpu(hp3).changeopsize(S_L);
  7391. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7392. {$endif x86_64}
  7393. end;
  7394. end;
  7395. {$push}
  7396. {$q-}{$r-}
  7397. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7398. var
  7399. ThisReg: TRegister;
  7400. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7401. TargetSubReg: TSubRegister;
  7402. hp1, hp2: tai;
  7403. RegInUse, RegChanged, p_removed: Boolean;
  7404. { Store list of found instructions so we don't have to call
  7405. GetNextInstructionUsingReg multiple times }
  7406. InstrList: array of taicpu;
  7407. InstrMax, Index: Integer;
  7408. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7409. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7410. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7411. WorkingValue: TCgInt;
  7412. PreMessage: string;
  7413. { Data flow analysis }
  7414. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7415. BitwiseOnly, OrXorUsed,
  7416. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7417. function CheckOverflowConditions: Boolean;
  7418. begin
  7419. Result := True;
  7420. if (TestValSignedMax > SignedUpperLimit) then
  7421. UpperSignedOverflow := True;
  7422. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  7423. LowerSignedOverflow := True;
  7424. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  7425. LowerUnsignedOverflow := True;
  7426. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  7427. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  7428. begin
  7429. { Absolute overflow }
  7430. Result := False;
  7431. Exit;
  7432. end;
  7433. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  7434. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  7435. ShiftDownOverflow := True;
  7436. if (TestValMin < 0) or (TestValMax < 0) then
  7437. begin
  7438. LowerUnsignedOverflow := True;
  7439. UpperUnsignedOverflow := True;
  7440. end;
  7441. end;
  7442. procedure AdjustFinalLoad;
  7443. begin
  7444. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  7445. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  7446. begin
  7447. { Convert the output MOVZX to a MOV }
  7448. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7449. begin
  7450. { Or remove it completely! }
  7451. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  7452. { Be careful; if p = hp1 and p was also removed, p
  7453. will become a dangling pointer }
  7454. if p = hp1 then
  7455. begin
  7456. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7457. p_removed := True;
  7458. end
  7459. else
  7460. RemoveInstruction(hp1);
  7461. end
  7462. else
  7463. begin
  7464. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  7465. taicpu(hp1).opcode := A_MOV;
  7466. taicpu(hp1).oper[0]^.reg := ThisReg;
  7467. taicpu(hp1).opsize := TargetSize;
  7468. end;
  7469. end
  7470. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  7471. begin
  7472. { Need to change the size of the output }
  7473. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  7474. taicpu(hp1).oper[0]^.reg := ThisReg;
  7475. taicpu(hp1).opsize := S_BL;
  7476. end;
  7477. end;
  7478. function CompressInstructions: Boolean;
  7479. var
  7480. LocalIndex: Integer;
  7481. begin
  7482. Result := False;
  7483. { The objective here is to try to find a combination that
  7484. removes one of the MOV/Z instructions. }
  7485. if (
  7486. (taicpu(p).oper[0]^.typ <> top_reg) or
  7487. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  7488. ) and
  7489. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7490. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7491. begin
  7492. { Make a preference to remove the second MOVZX instruction }
  7493. case taicpu(hp1).opsize of
  7494. S_BL, S_WL:
  7495. begin
  7496. TargetSize := S_L;
  7497. TargetSubReg := R_SUBD;
  7498. end;
  7499. S_BW:
  7500. begin
  7501. TargetSize := S_W;
  7502. TargetSubReg := R_SUBW;
  7503. end;
  7504. else
  7505. InternalError(2020112302);
  7506. end;
  7507. end
  7508. else
  7509. begin
  7510. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  7511. begin
  7512. { Exceeded lower bound but not upper bound }
  7513. TargetSize := MaxSize;
  7514. end
  7515. else if not LowerUnsignedOverflow then
  7516. begin
  7517. { Size didn't exceed lower bound }
  7518. TargetSize := MinSize;
  7519. end
  7520. else
  7521. Exit;
  7522. end;
  7523. case TargetSize of
  7524. S_B:
  7525. TargetSubReg := R_SUBL;
  7526. S_W:
  7527. TargetSubReg := R_SUBW;
  7528. S_L:
  7529. TargetSubReg := R_SUBD;
  7530. else
  7531. InternalError(2020112350);
  7532. end;
  7533. { Update the register to its new size }
  7534. setsubreg(ThisReg, TargetSubReg);
  7535. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7536. begin
  7537. { Check to see if the active register is used afterwards;
  7538. if not, we can change it and make a saving. }
  7539. RegInUse := False;
  7540. TransferUsedRegs(TmpUsedRegs);
  7541. { The target register may be marked as in use to cross
  7542. a jump to a distant label, so exclude it }
  7543. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  7544. hp2 := p;
  7545. repeat
  7546. { Explicitly check for the excluded register (don't include the first
  7547. instruction as it may be reading from here }
  7548. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  7549. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  7550. begin
  7551. RegInUse := True;
  7552. Break;
  7553. end;
  7554. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  7555. if not GetNextInstruction(hp2, hp2) then
  7556. InternalError(2020112340);
  7557. until (hp2 = hp1);
  7558. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7559. { We might still be able to get away with this }
  7560. RegInUse := not
  7561. (
  7562. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  7563. (hp2.typ = ait_instruction) and
  7564. (
  7565. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7566. instruction that doesn't actually contain ThisReg }
  7567. (cs_opt_level3 in current_settings.optimizerswitches) or
  7568. RegInInstruction(ThisReg, hp2)
  7569. ) and
  7570. RegLoadedWithNewValue(ThisReg, hp2)
  7571. );
  7572. if not RegInUse then
  7573. begin
  7574. { Force the register size to the same as this instruction so it can be removed}
  7575. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  7576. begin
  7577. TargetSize := S_L;
  7578. TargetSubReg := R_SUBD;
  7579. end
  7580. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  7581. begin
  7582. TargetSize := S_W;
  7583. TargetSubReg := R_SUBW;
  7584. end;
  7585. ThisReg := taicpu(hp1).oper[1]^.reg;
  7586. setsubreg(ThisReg, TargetSubReg);
  7587. RegChanged := True;
  7588. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  7589. TransferUsedRegs(TmpUsedRegs);
  7590. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  7591. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  7592. if p = hp1 then
  7593. begin
  7594. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7595. p_removed := True;
  7596. end
  7597. else
  7598. RemoveInstruction(hp1);
  7599. { Instruction will become "mov %reg,%reg" }
  7600. if not p_removed and (taicpu(p).opcode = A_MOV) and
  7601. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  7602. begin
  7603. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  7604. RemoveCurrentP(p);
  7605. p_removed := True;
  7606. end
  7607. else
  7608. taicpu(p).oper[1]^.reg := ThisReg;
  7609. Result := True;
  7610. end
  7611. else
  7612. begin
  7613. if TargetSize <> MaxSize then
  7614. begin
  7615. { Since the register is in use, we have to force it to
  7616. MaxSize otherwise part of it may become undefined later on }
  7617. TargetSize := MaxSize;
  7618. case TargetSize of
  7619. S_B:
  7620. TargetSubReg := R_SUBL;
  7621. S_W:
  7622. TargetSubReg := R_SUBW;
  7623. S_L:
  7624. TargetSubReg := R_SUBD;
  7625. else
  7626. InternalError(2020112351);
  7627. end;
  7628. setsubreg(ThisReg, TargetSubReg);
  7629. end;
  7630. AdjustFinalLoad;
  7631. end;
  7632. end
  7633. else
  7634. AdjustFinalLoad;
  7635. if not p_removed then
  7636. begin
  7637. if TargetSize = MinSize then
  7638. begin
  7639. { Convert the input MOVZX to a MOV }
  7640. if (taicpu(p).oper[0]^.typ = top_reg) and
  7641. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7642. begin
  7643. { Or remove it completely! }
  7644. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  7645. DebugMsg(SPeepholeOptimization + tostr(InstrMax), p);
  7646. RemoveCurrentP(p);
  7647. p_removed := True;
  7648. end
  7649. else
  7650. begin
  7651. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  7652. taicpu(p).opcode := A_MOV;
  7653. taicpu(p).oper[1]^.reg := ThisReg;
  7654. taicpu(p).opsize := TargetSize;
  7655. end;
  7656. Result := True;
  7657. end
  7658. else if TargetSize <> MaxSize then
  7659. begin
  7660. case MaxSize of
  7661. S_L:
  7662. if TargetSize = S_W then
  7663. begin
  7664. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  7665. taicpu(p).opsize := S_BW;
  7666. taicpu(p).oper[1]^.reg := ThisReg;
  7667. Result := True;
  7668. end
  7669. else
  7670. InternalError(2020112341);
  7671. S_W:
  7672. if TargetSize = S_L then
  7673. begin
  7674. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  7675. taicpu(p).opsize := S_BL;
  7676. taicpu(p).oper[1]^.reg := ThisReg;
  7677. Result := True;
  7678. end
  7679. else
  7680. InternalError(2020112342);
  7681. else
  7682. ;
  7683. end;
  7684. end;
  7685. end;
  7686. { Now go through every instruction we found and change the
  7687. size. If TargetSize = MaxSize, then almost no changes are
  7688. needed and Result can remain False if it hasn't been set
  7689. yet.
  7690. If RegChanged is True, then the register requires changing
  7691. and so the point about TargetSize = MaxSize doesn't apply. }
  7692. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  7693. begin
  7694. for LocalIndex := 0 to InstrMax do
  7695. begin
  7696. { If p_removed is true, then the original MOV/Z was removed
  7697. and removing the AND instruction may not be safe if it
  7698. appears first }
  7699. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  7700. InternalError(2020112310);
  7701. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  7702. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  7703. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  7704. InstrList[LocalIndex].opsize := TargetSize;
  7705. end;
  7706. Result := True;
  7707. end;
  7708. end;
  7709. begin
  7710. Result := False;
  7711. p_removed := False;
  7712. ThisReg := taicpu(p).oper[1]^.reg;
  7713. { Check for:
  7714. movs/z ###,%ecx (or %cx or %rcx)
  7715. ...
  7716. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  7717. (dealloc %ecx)
  7718. Change to:
  7719. mov ###,%cl (if ### = %cl, then remove completely)
  7720. ...
  7721. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  7722. }
  7723. if (getsupreg(ThisReg) = RS_ECX) and
  7724. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  7725. (hp1.typ = ait_instruction) and
  7726. (
  7727. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7728. instruction that doesn't actually contain ECX }
  7729. (cs_opt_level3 in current_settings.optimizerswitches) or
  7730. RegInInstruction(NR_ECX, hp1) or
  7731. (
  7732. { It's common for the shift/rotate's read/write register to be
  7733. initialised in between, so under -O2 and under, search ahead
  7734. one more instruction
  7735. }
  7736. GetNextInstruction(hp1, hp1) and
  7737. (hp1.typ = ait_instruction) and
  7738. RegInInstruction(NR_ECX, hp1)
  7739. )
  7740. ) and
  7741. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  7742. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  7743. begin
  7744. TransferUsedRegs(TmpUsedRegs);
  7745. hp2 := p;
  7746. repeat
  7747. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7748. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  7749. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  7750. begin
  7751. case taicpu(p).opsize of
  7752. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7753. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  7754. begin
  7755. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  7756. RemoveCurrentP(p);
  7757. end
  7758. else
  7759. begin
  7760. taicpu(p).opcode := A_MOV;
  7761. taicpu(p).opsize := S_B;
  7762. taicpu(p).oper[1]^.reg := NR_CL;
  7763. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  7764. end;
  7765. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7766. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  7767. begin
  7768. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  7769. RemoveCurrentP(p);
  7770. end
  7771. else
  7772. begin
  7773. taicpu(p).opcode := A_MOV;
  7774. taicpu(p).opsize := S_W;
  7775. taicpu(p).oper[1]^.reg := NR_CX;
  7776. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  7777. end;
  7778. {$ifdef x86_64}
  7779. S_LQ:
  7780. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  7781. begin
  7782. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  7783. RemoveCurrentP(p);
  7784. end
  7785. else
  7786. begin
  7787. taicpu(p).opcode := A_MOV;
  7788. taicpu(p).opsize := S_L;
  7789. taicpu(p).oper[1]^.reg := NR_ECX;
  7790. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  7791. end;
  7792. {$endif x86_64}
  7793. else
  7794. InternalError(2021120401);
  7795. end;
  7796. Result := True;
  7797. Exit;
  7798. end;
  7799. end;
  7800. { This is anything but quick! }
  7801. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  7802. Exit;
  7803. SetLength(InstrList, 0);
  7804. InstrMax := -1;
  7805. case taicpu(p).opsize of
  7806. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7807. begin
  7808. {$if defined(i386) or defined(i8086)}
  7809. { If the target size is 8-bit, make sure we can actually encode it }
  7810. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  7811. Exit;
  7812. {$endif i386 or i8086}
  7813. LowerLimit := $FF;
  7814. SignedLowerLimit := $7F;
  7815. SignedLowerLimitBottom := -128;
  7816. MinSize := S_B;
  7817. if taicpu(p).opsize = S_BW then
  7818. begin
  7819. MaxSize := S_W;
  7820. UpperLimit := $FFFF;
  7821. SignedUpperLimit := $7FFF;
  7822. SignedUpperLimitBottom := -32768;
  7823. end
  7824. else
  7825. begin
  7826. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  7827. MaxSize := S_L;
  7828. UpperLimit := $FFFFFFFF;
  7829. SignedUpperLimit := $7FFFFFFF;
  7830. SignedUpperLimitBottom := -2147483648;
  7831. end;
  7832. end;
  7833. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7834. begin
  7835. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  7836. LowerLimit := $FFFF;
  7837. SignedLowerLimit := $7FFF;
  7838. SignedLowerLimitBottom := -32768;
  7839. UpperLimit := $FFFFFFFF;
  7840. SignedUpperLimit := $7FFFFFFF;
  7841. SignedUpperLimitBottom := -2147483648;
  7842. MinSize := S_W;
  7843. MaxSize := S_L;
  7844. end;
  7845. {$ifdef x86_64}
  7846. S_LQ:
  7847. begin
  7848. { Both the lower and upper limits are set to 32-bit. If a limit
  7849. is breached, then optimisation is impossible }
  7850. LowerLimit := $FFFFFFFF;
  7851. SignedLowerLimit := $7FFFFFFF;
  7852. SignedLowerLimitBottom := -2147483648;
  7853. UpperLimit := $FFFFFFFF;
  7854. SignedUpperLimit := $7FFFFFFF;
  7855. SignedUpperLimitBottom := -2147483648;
  7856. MinSize := S_L;
  7857. MaxSize := S_L;
  7858. end;
  7859. {$endif x86_64}
  7860. else
  7861. InternalError(2020112301);
  7862. end;
  7863. TestValMin := 0;
  7864. TestValMax := LowerLimit;
  7865. TestValSignedMax := SignedLowerLimit;
  7866. TryShiftDownLimit := LowerLimit;
  7867. TryShiftDown := S_NO;
  7868. ShiftDownOverflow := False;
  7869. RegChanged := False;
  7870. BitwiseOnly := True;
  7871. OrXorUsed := False;
  7872. UpperSignedOverflow := False;
  7873. LowerSignedOverflow := False;
  7874. UpperUnsignedOverflow := False;
  7875. LowerUnsignedOverflow := False;
  7876. hp1 := p;
  7877. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  7878. (hp1.typ = ait_instruction) and
  7879. (
  7880. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7881. instruction that doesn't actually contain ThisReg }
  7882. (cs_opt_level3 in current_settings.optimizerswitches) or
  7883. { This allows this Movx optimisation to work through the SETcc instructions
  7884. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  7885. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  7886. skip over these SETcc instructions). }
  7887. (taicpu(hp1).opcode = A_SETcc) or
  7888. RegInInstruction(ThisReg, hp1)
  7889. ) do
  7890. begin
  7891. case taicpu(hp1).opcode of
  7892. A_INC,A_DEC:
  7893. begin
  7894. { Has to be an exact match on the register }
  7895. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  7896. Break;
  7897. if taicpu(hp1).opcode = A_INC then
  7898. begin
  7899. Inc(TestValMin);
  7900. Inc(TestValMax);
  7901. Inc(TestValSignedMax);
  7902. end
  7903. else
  7904. begin
  7905. Dec(TestValMin);
  7906. Dec(TestValMax);
  7907. Dec(TestValSignedMax);
  7908. end;
  7909. end;
  7910. A_TEST, A_CMP:
  7911. begin
  7912. if (
  7913. { Too high a risk of non-linear behaviour that breaks DFA
  7914. here, unless it's cmp $0,%reg, which is equivalent to
  7915. test %reg,%reg }
  7916. OrXorUsed and
  7917. (taicpu(hp1).opcode = A_CMP) and
  7918. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  7919. ) or
  7920. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  7921. { Has to be an exact match on the register }
  7922. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  7923. (
  7924. { Permit "test %reg,%reg" }
  7925. (taicpu(hp1).opcode = A_TEST) and
  7926. (taicpu(hp1).oper[0]^.typ = top_reg) and
  7927. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  7928. ) or
  7929. (taicpu(hp1).oper[0]^.typ <> top_const) or
  7930. { Make sure the comparison value is not smaller than the
  7931. smallest allowed signed value for the minimum size (e.g.
  7932. -128 for 8-bit) }
  7933. not (
  7934. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  7935. { Is it in the negative range? }
  7936. (
  7937. (taicpu(hp1).oper[0]^.val < 0) and
  7938. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  7939. )
  7940. ) then
  7941. Break;
  7942. { Check to see if the active register is used afterwards }
  7943. TransferUsedRegs(TmpUsedRegs);
  7944. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  7945. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7946. begin
  7947. { Make sure the comparison or any previous instructions
  7948. hasn't pushed the test values outside of the range of
  7949. MinSize }
  7950. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  7951. begin
  7952. { Exceeded lower bound but not upper bound }
  7953. TargetSize := MaxSize;
  7954. end
  7955. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  7956. begin
  7957. { Size didn't exceed lower bound }
  7958. TargetSize := MinSize;
  7959. end
  7960. else
  7961. Break;
  7962. case TargetSize of
  7963. S_B:
  7964. TargetSubReg := R_SUBL;
  7965. S_W:
  7966. TargetSubReg := R_SUBW;
  7967. S_L:
  7968. TargetSubReg := R_SUBD;
  7969. else
  7970. InternalError(2021051002);
  7971. end;
  7972. { Update the register to its new size }
  7973. setsubreg(ThisReg, TargetSubReg);
  7974. taicpu(hp1).oper[1]^.reg := ThisReg;
  7975. taicpu(hp1).opsize := MinSize;
  7976. { Convert the input MOVZX to a MOV }
  7977. if (taicpu(p).oper[0]^.typ = top_reg) and
  7978. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7979. begin
  7980. { Or remove it completely! }
  7981. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  7982. RemoveCurrentP(p);
  7983. p_removed := True;
  7984. end
  7985. else
  7986. begin
  7987. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  7988. taicpu(p).opcode := A_MOV;
  7989. taicpu(p).oper[1]^.reg := ThisReg;
  7990. taicpu(p).opsize := MinSize;
  7991. end;
  7992. if (InstrMax >= 0) then
  7993. begin
  7994. for Index := 0 to InstrMax do
  7995. begin
  7996. { If p_removed is true, then the original MOV/Z was removed
  7997. and removing the AND instruction may not be safe if it
  7998. appears first }
  7999. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  8000. InternalError(2020112311);
  8001. if InstrList[Index].oper[0]^.typ = top_reg then
  8002. InstrList[Index].oper[0]^.reg := ThisReg;
  8003. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8004. InstrList[Index].opsize := MinSize;
  8005. end;
  8006. end;
  8007. Result := True;
  8008. Exit;
  8009. end;
  8010. end;
  8011. A_SETcc:
  8012. begin
  8013. { This allows this Movx optimisation to work through the SETcc instructions
  8014. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8015. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8016. skip over these SETcc instructions). }
  8017. if (cs_opt_level3 in current_settings.optimizerswitches) or
  8018. { Of course, break out if the current register is used }
  8019. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  8020. Break
  8021. else
  8022. { We must use Continue so the instruction doesn't get added
  8023. to InstrList }
  8024. Continue;
  8025. end;
  8026. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  8027. begin
  8028. if
  8029. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8030. { Has to be an exact match on the register }
  8031. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  8032. (
  8033. (
  8034. (taicpu(hp1).oper[0]^.typ = top_const) and
  8035. (
  8036. (
  8037. (taicpu(hp1).opcode = A_SHL) and
  8038. (
  8039. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  8040. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  8041. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  8042. )
  8043. ) or (
  8044. (taicpu(hp1).opcode <> A_SHL) and
  8045. (
  8046. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8047. { Is it in the negative range? }
  8048. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  8049. )
  8050. )
  8051. )
  8052. ) or (
  8053. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  8054. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  8055. )
  8056. ) then
  8057. Break;
  8058. { Only process OR and XOR if there are only bitwise operations,
  8059. since otherwise they can too easily fool the data flow
  8060. analysis (they can cause non-linear behaviour) }
  8061. case taicpu(hp1).opcode of
  8062. A_ADD:
  8063. begin
  8064. if OrXorUsed then
  8065. { Too high a risk of non-linear behaviour that breaks DFA here }
  8066. Break
  8067. else
  8068. BitwiseOnly := False;
  8069. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8070. begin
  8071. TestValMin := TestValMin * 2;
  8072. TestValMax := TestValMax * 2;
  8073. TestValSignedMax := TestValSignedMax * 2;
  8074. end
  8075. else
  8076. begin
  8077. WorkingValue := taicpu(hp1).oper[0]^.val;
  8078. TestValMin := TestValMin + WorkingValue;
  8079. TestValMax := TestValMax + WorkingValue;
  8080. TestValSignedMax := TestValSignedMax + WorkingValue;
  8081. end;
  8082. end;
  8083. A_SUB:
  8084. begin
  8085. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8086. begin
  8087. TestValMin := 0;
  8088. TestValMax := 0;
  8089. TestValSignedMax := 0;
  8090. end
  8091. else
  8092. begin
  8093. if OrXorUsed then
  8094. { Too high a risk of non-linear behaviour that breaks DFA here }
  8095. Break
  8096. else
  8097. BitwiseOnly := False;
  8098. WorkingValue := taicpu(hp1).oper[0]^.val;
  8099. TestValMin := TestValMin - WorkingValue;
  8100. TestValMax := TestValMax - WorkingValue;
  8101. TestValSignedMax := TestValSignedMax - WorkingValue;
  8102. end;
  8103. end;
  8104. A_AND:
  8105. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8106. begin
  8107. { we might be able to go smaller if AND appears first }
  8108. if InstrMax = -1 then
  8109. case MinSize of
  8110. S_B:
  8111. ;
  8112. S_W:
  8113. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8114. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8115. begin
  8116. TryShiftDown := S_B;
  8117. TryShiftDownLimit := $FF;
  8118. end;
  8119. S_L:
  8120. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8121. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8122. begin
  8123. TryShiftDown := S_B;
  8124. TryShiftDownLimit := $FF;
  8125. end
  8126. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8127. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8128. begin
  8129. TryShiftDown := S_W;
  8130. TryShiftDownLimit := $FFFF;
  8131. end;
  8132. else
  8133. InternalError(2020112320);
  8134. end;
  8135. WorkingValue := taicpu(hp1).oper[0]^.val;
  8136. TestValMin := TestValMin and WorkingValue;
  8137. TestValMax := TestValMax and WorkingValue;
  8138. TestValSignedMax := TestValSignedMax and WorkingValue;
  8139. end;
  8140. A_OR:
  8141. begin
  8142. if not BitwiseOnly then
  8143. Break;
  8144. OrXorUsed := True;
  8145. WorkingValue := taicpu(hp1).oper[0]^.val;
  8146. TestValMin := TestValMin or WorkingValue;
  8147. TestValMax := TestValMax or WorkingValue;
  8148. TestValSignedMax := TestValSignedMax or WorkingValue;
  8149. end;
  8150. A_XOR:
  8151. begin
  8152. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8153. begin
  8154. TestValMin := 0;
  8155. TestValMax := 0;
  8156. TestValSignedMax := 0;
  8157. end
  8158. else
  8159. begin
  8160. if not BitwiseOnly then
  8161. Break;
  8162. OrXorUsed := True;
  8163. WorkingValue := taicpu(hp1).oper[0]^.val;
  8164. TestValMin := TestValMin xor WorkingValue;
  8165. TestValMax := TestValMax xor WorkingValue;
  8166. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8167. end;
  8168. end;
  8169. A_SHL:
  8170. begin
  8171. BitwiseOnly := False;
  8172. WorkingValue := taicpu(hp1).oper[0]^.val;
  8173. TestValMin := TestValMin shl WorkingValue;
  8174. TestValMax := TestValMax shl WorkingValue;
  8175. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8176. end;
  8177. A_SHR,
  8178. { The first instruction was MOVZX, so the value won't be negative }
  8179. A_SAR:
  8180. begin
  8181. if InstrMax <> -1 then
  8182. BitwiseOnly := False
  8183. else
  8184. { we might be able to go smaller if SHR appears first }
  8185. case MinSize of
  8186. S_B:
  8187. ;
  8188. S_W:
  8189. if (taicpu(hp1).oper[0]^.val >= 8) then
  8190. begin
  8191. TryShiftDown := S_B;
  8192. TryShiftDownLimit := $FF;
  8193. TryShiftDownSignedLimit := $7F;
  8194. TryShiftDownSignedLimitLower := -128;
  8195. end;
  8196. S_L:
  8197. if (taicpu(hp1).oper[0]^.val >= 24) then
  8198. begin
  8199. TryShiftDown := S_B;
  8200. TryShiftDownLimit := $FF;
  8201. TryShiftDownSignedLimit := $7F;
  8202. TryShiftDownSignedLimitLower := -128;
  8203. end
  8204. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8205. begin
  8206. TryShiftDown := S_W;
  8207. TryShiftDownLimit := $FFFF;
  8208. TryShiftDownSignedLimit := $7FFF;
  8209. TryShiftDownSignedLimitLower := -32768;
  8210. end;
  8211. else
  8212. InternalError(2020112321);
  8213. end;
  8214. WorkingValue := taicpu(hp1).oper[0]^.val;
  8215. if taicpu(hp1).opcode = A_SAR then
  8216. begin
  8217. TestValMin := SarInt64(TestValMin, WorkingValue);
  8218. TestValMax := SarInt64(TestValMax, WorkingValue);
  8219. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8220. end
  8221. else
  8222. begin
  8223. TestValMin := TestValMin shr WorkingValue;
  8224. TestValMax := TestValMax shr WorkingValue;
  8225. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8226. end;
  8227. end;
  8228. else
  8229. InternalError(2020112303);
  8230. end;
  8231. end;
  8232. (*
  8233. A_IMUL:
  8234. case taicpu(hp1).ops of
  8235. 2:
  8236. begin
  8237. if not MatchOpType(hp1, top_reg, top_reg) or
  8238. { Has to be an exact match on the register }
  8239. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8240. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8241. Break;
  8242. TestValMin := TestValMin * TestValMin;
  8243. TestValMax := TestValMax * TestValMax;
  8244. TestValSignedMax := TestValSignedMax * TestValMax;
  8245. end;
  8246. 3:
  8247. begin
  8248. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8249. { Has to be an exact match on the register }
  8250. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8251. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8252. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8253. { Is it in the negative range? }
  8254. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8255. Break;
  8256. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8257. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8258. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8259. end;
  8260. else
  8261. Break;
  8262. end;
  8263. A_IDIV:
  8264. case taicpu(hp1).ops of
  8265. 3:
  8266. begin
  8267. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8268. { Has to be an exact match on the register }
  8269. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8270. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8271. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8272. { Is it in the negative range? }
  8273. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8274. Break;
  8275. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  8276. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  8277. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  8278. end;
  8279. else
  8280. Break;
  8281. end;
  8282. *)
  8283. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8284. begin
  8285. { If there are no instructions in between, then we might be able to make a saving }
  8286. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  8287. Break;
  8288. { We have something like:
  8289. movzbw %dl,%dx
  8290. ...
  8291. movswl %dx,%edx
  8292. Change the latter to a zero-extension then enter the
  8293. A_MOVZX case branch.
  8294. }
  8295. {$ifdef x86_64}
  8296. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8297. begin
  8298. { this becomes a zero extension from 32-bit to 64-bit, but
  8299. the upper 32 bits are already zero, so just delete the
  8300. instruction }
  8301. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  8302. RemoveInstruction(hp1);
  8303. Result := True;
  8304. Exit;
  8305. end
  8306. else
  8307. {$endif x86_64}
  8308. begin
  8309. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  8310. taicpu(hp1).opcode := A_MOVZX;
  8311. {$ifdef x86_64}
  8312. case taicpu(hp1).opsize of
  8313. S_BQ:
  8314. begin
  8315. taicpu(hp1).opsize := S_BL;
  8316. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8317. end;
  8318. S_WQ:
  8319. begin
  8320. taicpu(hp1).opsize := S_WL;
  8321. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8322. end;
  8323. S_LQ:
  8324. begin
  8325. taicpu(hp1).opcode := A_MOV;
  8326. taicpu(hp1).opsize := S_L;
  8327. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8328. { In this instance, we need to break out because the
  8329. instruction is no longer MOVZX or MOVSXD }
  8330. Result := True;
  8331. Exit;
  8332. end;
  8333. else
  8334. ;
  8335. end;
  8336. {$endif x86_64}
  8337. Result := CompressInstructions;
  8338. Exit;
  8339. end;
  8340. end;
  8341. A_MOVZX:
  8342. begin
  8343. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  8344. Break;
  8345. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  8346. begin
  8347. if (InstrMax = -1) and
  8348. { Will return false if the second parameter isn't ThisReg
  8349. (can happen on -O2 and under) }
  8350. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8351. begin
  8352. { The two MOVZX instructions are adjacent, so remove the first one }
  8353. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  8354. RemoveCurrentP(p);
  8355. Result := True;
  8356. Exit;
  8357. end;
  8358. Break;
  8359. end;
  8360. Result := CompressInstructions;
  8361. Exit;
  8362. end;
  8363. else
  8364. { This includes ADC, SBB and IDIV }
  8365. Break;
  8366. end;
  8367. if not CheckOverflowConditions then
  8368. Break;
  8369. { Contains highest index (so instruction count - 1) }
  8370. Inc(InstrMax);
  8371. if InstrMax > High(InstrList) then
  8372. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8373. InstrList[InstrMax] := taicpu(hp1);
  8374. end;
  8375. end;
  8376. {$pop}
  8377. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  8378. var
  8379. hp1 : tai;
  8380. begin
  8381. Result:=false;
  8382. if (taicpu(p).ops >= 2) and
  8383. ((taicpu(p).oper[0]^.typ = top_const) or
  8384. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  8385. (taicpu(p).oper[1]^.typ = top_reg) and
  8386. ((taicpu(p).ops = 2) or
  8387. ((taicpu(p).oper[2]^.typ = top_reg) and
  8388. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  8389. GetLastInstruction(p,hp1) and
  8390. MatchInstruction(hp1,A_MOV,[]) and
  8391. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8392. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8393. begin
  8394. TransferUsedRegs(TmpUsedRegs);
  8395. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  8396. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  8397. { change
  8398. mov reg1,reg2
  8399. imul y,reg2 to imul y,reg1,reg2 }
  8400. begin
  8401. taicpu(p).ops := 3;
  8402. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  8403. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8404. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  8405. RemoveInstruction(hp1);
  8406. result:=true;
  8407. end;
  8408. end;
  8409. end;
  8410. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  8411. var
  8412. ThisLabel: TAsmLabel;
  8413. begin
  8414. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  8415. ThisLabel.decrefs;
  8416. taicpu(p).opcode := A_RET;
  8417. taicpu(p).is_jmp := false;
  8418. taicpu(p).ops := taicpu(ret_p).ops;
  8419. case taicpu(ret_p).ops of
  8420. 0:
  8421. taicpu(p).clearop(0);
  8422. 1:
  8423. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  8424. else
  8425. internalerror(2016041301);
  8426. end;
  8427. { If the original label is now dead, it might turn out that the label
  8428. immediately follows p. As a result, everything beyond it, which will
  8429. be just some final register configuration and a RET instruction, is
  8430. now dead code. [Kit] }
  8431. { NOTE: This is much faster than introducing a OptPass2RET routine and
  8432. running RemoveDeadCodeAfterJump for each RET instruction, because
  8433. this optimisation rarely happens and most RETs appear at the end of
  8434. routines where there is nothing that can be stripped. [Kit] }
  8435. if not ThisLabel.is_used then
  8436. RemoveDeadCodeAfterJump(p);
  8437. end;
  8438. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  8439. var
  8440. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  8441. Unconditional, PotentialModified: Boolean;
  8442. OperPtr: POper;
  8443. NewRef: TReference;
  8444. InstrList: array of taicpu;
  8445. InstrMax, Index: Integer;
  8446. const
  8447. {$ifdef DEBUG_AOPTCPU}
  8448. SNoFlags: shortstring = ' so the flags aren''t modified';
  8449. {$else DEBUG_AOPTCPU}
  8450. SNoFlags = '';
  8451. {$endif DEBUG_AOPTCPU}
  8452. begin
  8453. Result:=false;
  8454. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  8455. begin
  8456. if MatchInstruction(hp1, A_TEST, [S_B]) and
  8457. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8458. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8459. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8460. GetNextInstruction(hp1, hp2) and
  8461. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  8462. { Change from: To:
  8463. set(C) %reg j(~C) label
  8464. test %reg,%reg/cmp $0,%reg
  8465. je label
  8466. set(C) %reg j(C) label
  8467. test %reg,%reg/cmp $0,%reg
  8468. jne label
  8469. (Also do something similar with sete/setne instead of je/jne)
  8470. }
  8471. begin
  8472. { Before we do anything else, we need to check the instructions
  8473. in between SETcc and TEST to make sure they don't modify the
  8474. FLAGS register - if -O2 or under, there won't be any
  8475. instructions between SET and TEST }
  8476. TransferUsedRegs(TmpUsedRegs);
  8477. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8478. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8479. begin
  8480. next := p;
  8481. SetLength(InstrList, 0);
  8482. InstrMax := -1;
  8483. PotentialModified := False;
  8484. { Make a note of every instruction that modifies the FLAGS
  8485. register }
  8486. while GetNextInstruction(next, next) and (next <> hp1) do
  8487. begin
  8488. if next.typ <> ait_instruction then
  8489. { GetNextInstructionUsingReg should have returned False }
  8490. InternalError(2021051701);
  8491. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  8492. begin
  8493. case taicpu(next).opcode of
  8494. A_SETcc,
  8495. A_CMOVcc,
  8496. A_Jcc:
  8497. begin
  8498. if PotentialModified then
  8499. { Not safe because the flags were modified earlier }
  8500. Exit
  8501. else
  8502. { Condition is the same as the initial SETcc, so this is safe
  8503. (don't add to instruction list though) }
  8504. Continue;
  8505. end;
  8506. A_ADD:
  8507. begin
  8508. if (taicpu(next).opsize = S_B) or
  8509. { LEA doesn't support 8-bit operands }
  8510. (taicpu(next).oper[1]^.typ <> top_reg) or
  8511. { Must write to a register }
  8512. (taicpu(next).oper[0]^.typ = top_ref) then
  8513. { Require a constant or a register }
  8514. Exit;
  8515. PotentialModified := True;
  8516. end;
  8517. A_SUB:
  8518. begin
  8519. if (taicpu(next).opsize = S_B) or
  8520. { LEA doesn't support 8-bit operands }
  8521. (taicpu(next).oper[1]^.typ <> top_reg) or
  8522. { Must write to a register }
  8523. (taicpu(next).oper[0]^.typ <> top_const) or
  8524. (taicpu(next).oper[0]^.val = $80000000) then
  8525. { Can't subtract a register with LEA - also
  8526. check that the value isn't -2^31, as this
  8527. can't be negated }
  8528. Exit;
  8529. PotentialModified := True;
  8530. end;
  8531. A_SAL,
  8532. A_SHL:
  8533. begin
  8534. if (taicpu(next).opsize = S_B) or
  8535. { LEA doesn't support 8-bit operands }
  8536. (taicpu(next).oper[1]^.typ <> top_reg) or
  8537. { Must write to a register }
  8538. (taicpu(next).oper[0]^.typ <> top_const) or
  8539. (taicpu(next).oper[0]^.val < 0) or
  8540. (taicpu(next).oper[0]^.val > 3) then
  8541. Exit;
  8542. PotentialModified := True;
  8543. end;
  8544. A_IMUL:
  8545. begin
  8546. if (taicpu(next).ops <> 3) or
  8547. (taicpu(next).oper[1]^.typ <> top_reg) or
  8548. { Must write to a register }
  8549. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  8550. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  8551. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  8552. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  8553. Exit
  8554. else
  8555. PotentialModified := True;
  8556. end;
  8557. else
  8558. { Don't know how to change this, so abort }
  8559. Exit;
  8560. end;
  8561. { Contains highest index (so instruction count - 1) }
  8562. Inc(InstrMax);
  8563. if InstrMax > High(InstrList) then
  8564. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8565. InstrList[InstrMax] := taicpu(next);
  8566. end;
  8567. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  8568. end;
  8569. if not Assigned(next) or (next <> hp1) then
  8570. { It should be equal to hp1 }
  8571. InternalError(2021051702);
  8572. { Cycle through each instruction and check to see if we can
  8573. change them to versions that don't modify the flags }
  8574. if (InstrMax >= 0) then
  8575. begin
  8576. for Index := 0 to InstrMax do
  8577. case InstrList[Index].opcode of
  8578. A_ADD:
  8579. begin
  8580. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  8581. InstrList[Index].opcode := A_LEA;
  8582. reference_reset(NewRef, 1, []);
  8583. NewRef.base := InstrList[Index].oper[1]^.reg;
  8584. if InstrList[Index].oper[0]^.typ = top_reg then
  8585. begin
  8586. NewRef.index := InstrList[Index].oper[0]^.reg;
  8587. NewRef.scalefactor := 1;
  8588. end
  8589. else
  8590. NewRef.offset := InstrList[Index].oper[0]^.val;
  8591. InstrList[Index].loadref(0, NewRef);
  8592. end;
  8593. A_SUB:
  8594. begin
  8595. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  8596. InstrList[Index].opcode := A_LEA;
  8597. reference_reset(NewRef, 1, []);
  8598. NewRef.base := InstrList[Index].oper[1]^.reg;
  8599. NewRef.offset := -InstrList[Index].oper[0]^.val;
  8600. InstrList[Index].loadref(0, NewRef);
  8601. end;
  8602. A_SHL,
  8603. A_SAL:
  8604. begin
  8605. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  8606. InstrList[Index].opcode := A_LEA;
  8607. reference_reset(NewRef, 1, []);
  8608. NewRef.index := InstrList[Index].oper[1]^.reg;
  8609. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  8610. InstrList[Index].loadref(0, NewRef);
  8611. end;
  8612. A_IMUL:
  8613. begin
  8614. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  8615. InstrList[Index].opcode := A_LEA;
  8616. reference_reset(NewRef, 1, []);
  8617. NewRef.index := InstrList[Index].oper[1]^.reg;
  8618. case InstrList[Index].oper[0]^.val of
  8619. 2, 4, 8:
  8620. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  8621. else {3, 5 and 9}
  8622. begin
  8623. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  8624. NewRef.base := InstrList[Index].oper[1]^.reg;
  8625. end;
  8626. end;
  8627. InstrList[Index].loadref(0, NewRef);
  8628. end;
  8629. else
  8630. InternalError(2021051710);
  8631. end;
  8632. end;
  8633. { Mark the FLAGS register as used across this whole block }
  8634. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  8635. end;
  8636. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  8637. JumpC := taicpu(hp2).condition;
  8638. Unconditional := False;
  8639. if conditions_equal(JumpC, C_E) then
  8640. SetC := inverse_cond(taicpu(p).condition)
  8641. else if conditions_equal(JumpC, C_NE) then
  8642. SetC := taicpu(p).condition
  8643. else
  8644. { We've got something weird here (and inefficent) }
  8645. begin
  8646. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  8647. SetC := C_NONE;
  8648. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  8649. if condition_in(C_AE, JumpC) then
  8650. Unconditional := True
  8651. else
  8652. { Not sure what to do with this jump - drop out }
  8653. Exit;
  8654. end;
  8655. RemoveInstruction(hp1);
  8656. if Unconditional then
  8657. MakeUnconditional(taicpu(hp2))
  8658. else
  8659. begin
  8660. if SetC = C_NONE then
  8661. InternalError(2018061402);
  8662. taicpu(hp2).SetCondition(SetC);
  8663. end;
  8664. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  8665. TmpUsedRegs }
  8666. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  8667. begin
  8668. RemoveCurrentp(p, hp2);
  8669. if taicpu(hp2).opcode = A_SETcc then
  8670. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  8671. else
  8672. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  8673. end
  8674. else
  8675. if taicpu(hp2).opcode = A_SETcc then
  8676. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  8677. else
  8678. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  8679. Result := True;
  8680. end
  8681. else if
  8682. { Make sure the instructions are adjacent }
  8683. (
  8684. not (cs_opt_level3 in current_settings.optimizerswitches) or
  8685. GetNextInstruction(p, hp1)
  8686. ) and
  8687. MatchInstruction(hp1, A_MOV, [S_B]) and
  8688. { Writing to memory is allowed }
  8689. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  8690. begin
  8691. {
  8692. Watch out for sequences such as:
  8693. set(c)b %regb
  8694. movb %regb,(ref)
  8695. movb $0,1(ref)
  8696. movb $0,2(ref)
  8697. movb $0,3(ref)
  8698. Much more efficient to turn it into:
  8699. movl $0,%regl
  8700. set(c)b %regb
  8701. movl %regl,(ref)
  8702. Or:
  8703. set(c)b %regb
  8704. movzbl %regb,%regl
  8705. movl %regl,(ref)
  8706. }
  8707. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  8708. GetNextInstruction(hp1, hp2) and
  8709. MatchInstruction(hp2, A_MOV, [S_B]) and
  8710. (taicpu(hp2).oper[1]^.typ = top_ref) and
  8711. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  8712. begin
  8713. { Don't do anything else except set Result to True }
  8714. end
  8715. else
  8716. begin
  8717. if taicpu(p).oper[0]^.typ = top_reg then
  8718. begin
  8719. TransferUsedRegs(TmpUsedRegs);
  8720. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8721. end;
  8722. { If it's not a register, it's a memory address }
  8723. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  8724. begin
  8725. { Even if the register is still in use, we can minimise the
  8726. pipeline stall by changing the MOV into another SETcc. }
  8727. taicpu(hp1).opcode := A_SETcc;
  8728. taicpu(hp1).condition := taicpu(p).condition;
  8729. if taicpu(hp1).oper[1]^.typ = top_ref then
  8730. begin
  8731. { Swapping the operand pointers like this is probably a
  8732. bit naughty, but it is far faster than using loadoper
  8733. to transfer the reference from oper[1] to oper[0] if
  8734. you take into account the extra procedure calls and
  8735. the memory allocation and deallocation required }
  8736. OperPtr := taicpu(hp1).oper[1];
  8737. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  8738. taicpu(hp1).oper[0] := OperPtr;
  8739. end
  8740. else
  8741. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  8742. taicpu(hp1).clearop(1);
  8743. taicpu(hp1).ops := 1;
  8744. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  8745. end
  8746. else
  8747. begin
  8748. if taicpu(hp1).oper[1]^.typ = top_reg then
  8749. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  8750. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8751. RemoveInstruction(hp1);
  8752. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  8753. end
  8754. end;
  8755. Result := True;
  8756. end;
  8757. end;
  8758. end;
  8759. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  8760. var
  8761. hp1: tai;
  8762. Count: Integer;
  8763. OrigLabel: TAsmLabel;
  8764. begin
  8765. result := False;
  8766. { Sometimes, the optimisations below can permit this }
  8767. RemoveDeadCodeAfterJump(p);
  8768. 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
  8769. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  8770. begin
  8771. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8772. { Also a side-effect of optimisations }
  8773. if CollapseZeroDistJump(p, OrigLabel) then
  8774. begin
  8775. Result := True;
  8776. Exit;
  8777. end;
  8778. hp1 := GetLabelWithSym(OrigLabel);
  8779. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  8780. begin
  8781. case taicpu(hp1).opcode of
  8782. A_RET:
  8783. {
  8784. change
  8785. jmp .L1
  8786. ...
  8787. .L1:
  8788. ret
  8789. into
  8790. ret
  8791. }
  8792. begin
  8793. ConvertJumpToRET(p, hp1);
  8794. result:=true;
  8795. end;
  8796. { Check any kind of direct assignment instruction }
  8797. A_MOV,
  8798. A_MOVD,
  8799. A_MOVQ,
  8800. A_MOVSX,
  8801. {$ifdef x86_64}
  8802. A_MOVSXD,
  8803. {$endif x86_64}
  8804. A_MOVZX,
  8805. A_MOVAPS,
  8806. A_MOVUPS,
  8807. A_MOVSD,
  8808. A_MOVAPD,
  8809. A_MOVUPD,
  8810. A_MOVDQA,
  8811. A_MOVDQU,
  8812. A_VMOVSS,
  8813. A_VMOVAPS,
  8814. A_VMOVUPS,
  8815. A_VMOVSD,
  8816. A_VMOVAPD,
  8817. A_VMOVUPD,
  8818. A_VMOVDQA,
  8819. A_VMOVDQU:
  8820. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  8821. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  8822. begin
  8823. Result := True;
  8824. Exit;
  8825. end;
  8826. else
  8827. ;
  8828. end;
  8829. end;
  8830. end;
  8831. end;
  8832. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  8833. begin
  8834. CanBeCMOV:=assigned(p) and
  8835. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  8836. { we can't use cmov ref,reg because
  8837. ref could be nil and cmov still throws an exception
  8838. if ref=nil but the mov isn't done (FK)
  8839. or ((taicpu(p).oper[0]^.typ = top_ref) and
  8840. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  8841. }
  8842. (taicpu(p).oper[1]^.typ = top_reg) and
  8843. (
  8844. (taicpu(p).oper[0]^.typ = top_reg) or
  8845. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  8846. it is not expected that this can cause a seg. violation }
  8847. (
  8848. (taicpu(p).oper[0]^.typ = top_ref) and
  8849. IsRefSafe(taicpu(p).oper[0]^.ref)
  8850. )
  8851. );
  8852. end;
  8853. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  8854. var
  8855. hp1,hp2: tai;
  8856. {$ifndef i8086}
  8857. hp3,hp4,hpmov2, hp5: tai;
  8858. l : Longint;
  8859. condition : TAsmCond;
  8860. {$endif i8086}
  8861. carryadd_opcode : TAsmOp;
  8862. symbol: TAsmSymbol;
  8863. increg, tmpreg: TRegister;
  8864. begin
  8865. result:=false;
  8866. if GetNextInstruction(p,hp1) and (hp1.typ=ait_instruction) then
  8867. begin
  8868. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8869. if (
  8870. (
  8871. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  8872. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  8873. (Taicpu(hp1).oper[0]^.val=1)
  8874. ) or
  8875. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  8876. ) and
  8877. GetNextInstruction(hp1,hp2) and
  8878. SkipAligns(hp2, hp2) and
  8879. (hp2.typ = ait_label) and
  8880. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  8881. { jb @@1 cmc
  8882. inc/dec operand --> adc/sbb operand,0
  8883. @@1:
  8884. ... and ...
  8885. jnb @@1
  8886. inc/dec operand --> adc/sbb operand,0
  8887. @@1: }
  8888. begin
  8889. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  8890. begin
  8891. case taicpu(hp1).opcode of
  8892. A_INC,
  8893. A_ADD:
  8894. carryadd_opcode:=A_ADC;
  8895. A_DEC,
  8896. A_SUB:
  8897. carryadd_opcode:=A_SBB;
  8898. else
  8899. InternalError(2021011001);
  8900. end;
  8901. Taicpu(p).clearop(0);
  8902. Taicpu(p).ops:=0;
  8903. Taicpu(p).is_jmp:=false;
  8904. Taicpu(p).opcode:=A_CMC;
  8905. Taicpu(p).condition:=C_NONE;
  8906. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  8907. Taicpu(hp1).ops:=2;
  8908. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  8909. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  8910. else
  8911. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  8912. Taicpu(hp1).loadconst(0,0);
  8913. Taicpu(hp1).opcode:=carryadd_opcode;
  8914. result:=true;
  8915. exit;
  8916. end
  8917. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  8918. begin
  8919. case taicpu(hp1).opcode of
  8920. A_INC,
  8921. A_ADD:
  8922. carryadd_opcode:=A_ADC;
  8923. A_DEC,
  8924. A_SUB:
  8925. carryadd_opcode:=A_SBB;
  8926. else
  8927. InternalError(2021011002);
  8928. end;
  8929. Taicpu(hp1).ops:=2;
  8930. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  8931. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  8932. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  8933. else
  8934. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  8935. Taicpu(hp1).loadconst(0,0);
  8936. Taicpu(hp1).opcode:=carryadd_opcode;
  8937. RemoveCurrentP(p, hp1);
  8938. result:=true;
  8939. exit;
  8940. end
  8941. {
  8942. jcc @@1 setcc tmpreg
  8943. inc/dec/add/sub operand -> (movzx tmpreg)
  8944. @@1: add/sub tmpreg,operand
  8945. While this increases code size slightly, it makes the code much faster if the
  8946. jump is unpredictable
  8947. }
  8948. else if not(cs_opt_size in current_settings.optimizerswitches) then
  8949. begin
  8950. { search for an available register which is volatile }
  8951. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  8952. if increg <> NR_NO then
  8953. begin
  8954. { We don't need to check if tmpreg is in hp1 or not, because
  8955. it will be marked as in use at p (if not, this is
  8956. indictive of a compiler bug). }
  8957. TAsmLabel(symbol).decrefs;
  8958. Taicpu(p).clearop(0);
  8959. Taicpu(p).ops:=1;
  8960. Taicpu(p).is_jmp:=false;
  8961. Taicpu(p).opcode:=A_SETcc;
  8962. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  8963. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  8964. Taicpu(p).loadreg(0,increg);
  8965. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  8966. begin
  8967. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  8968. R_SUBW:
  8969. begin
  8970. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  8971. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  8972. end;
  8973. R_SUBD:
  8974. begin
  8975. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  8976. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  8977. end;
  8978. {$ifdef x86_64}
  8979. R_SUBQ:
  8980. begin
  8981. { MOVZX doesn't have a 64-bit variant, because
  8982. the 32-bit version implicitly zeroes the
  8983. upper 32-bits of the destination register }
  8984. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  8985. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  8986. setsubreg(tmpreg, R_SUBQ);
  8987. end;
  8988. {$endif x86_64}
  8989. else
  8990. Internalerror(2020030601);
  8991. end;
  8992. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  8993. asml.InsertAfter(hp2,p);
  8994. end
  8995. else
  8996. tmpreg := increg;
  8997. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  8998. begin
  8999. Taicpu(hp1).ops:=2;
  9000. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9001. end;
  9002. Taicpu(hp1).loadreg(0,tmpreg);
  9003. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9004. Result := True;
  9005. { p is no longer a Jcc instruction, so exit }
  9006. Exit;
  9007. end;
  9008. end;
  9009. end;
  9010. { Detect the following:
  9011. jmp<cond> @Lbl1
  9012. jmp @Lbl2
  9013. ...
  9014. @Lbl1:
  9015. ret
  9016. Change to:
  9017. jmp<inv_cond> @Lbl2
  9018. ret
  9019. }
  9020. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9021. begin
  9022. hp2:=getlabelwithsym(TAsmLabel(symbol));
  9023. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  9024. MatchInstruction(hp2,A_RET,[S_NO]) then
  9025. begin
  9026. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  9027. { Change label address to that of the unconditional jump }
  9028. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  9029. TAsmLabel(symbol).DecRefs;
  9030. taicpu(hp1).opcode := A_RET;
  9031. taicpu(hp1).is_jmp := false;
  9032. taicpu(hp1).ops := taicpu(hp2).ops;
  9033. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  9034. case taicpu(hp2).ops of
  9035. 0:
  9036. taicpu(hp1).clearop(0);
  9037. 1:
  9038. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  9039. else
  9040. internalerror(2016041302);
  9041. end;
  9042. end;
  9043. {$ifndef i8086}
  9044. end
  9045. {
  9046. convert
  9047. j<c> .L1
  9048. mov 1,reg
  9049. jmp .L2
  9050. .L1
  9051. mov 0,reg
  9052. .L2
  9053. into
  9054. mov 0,reg
  9055. set<not(c)> reg
  9056. take care of alignment and that the mov 0,reg is not converted into a xor as this
  9057. would destroy the flag contents
  9058. }
  9059. else if MatchInstruction(hp1,A_MOV,[]) and
  9060. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9061. {$ifdef i386}
  9062. (
  9063. { Under i386, ESI, EDI, EBP and ESP
  9064. don't have an 8-bit representation }
  9065. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9066. ) and
  9067. {$endif i386}
  9068. (taicpu(hp1).oper[0]^.val=1) and
  9069. GetNextInstruction(hp1,hp2) and
  9070. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9071. GetNextInstruction(hp2,hp3) and
  9072. { skip align }
  9073. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9074. (hp3.typ=ait_label) and
  9075. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9076. (tai_label(hp3).labsym.getrefs=1) and
  9077. GetNextInstruction(hp3,hp4) and
  9078. MatchInstruction(hp4,A_MOV,[]) and
  9079. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9080. (taicpu(hp4).oper[0]^.val=0) and
  9081. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9082. GetNextInstruction(hp4,hp5) and
  9083. (hp5.typ=ait_label) and
  9084. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9085. (tai_label(hp5).labsym.getrefs=1) then
  9086. begin
  9087. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9088. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9089. { remove last label }
  9090. RemoveInstruction(hp5);
  9091. { remove second label }
  9092. RemoveInstruction(hp3);
  9093. { if align is present remove it }
  9094. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9095. RemoveInstruction(hp3);
  9096. { remove jmp }
  9097. RemoveInstruction(hp2);
  9098. if taicpu(hp1).opsize=S_B then
  9099. RemoveInstruction(hp1)
  9100. else
  9101. taicpu(hp1).loadconst(0,0);
  9102. taicpu(hp4).opcode:=A_SETcc;
  9103. taicpu(hp4).opsize:=S_B;
  9104. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9105. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9106. taicpu(hp4).opercnt:=1;
  9107. taicpu(hp4).ops:=1;
  9108. taicpu(hp4).freeop(1);
  9109. RemoveCurrentP(p);
  9110. Result:=true;
  9111. exit;
  9112. end
  9113. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9114. begin
  9115. { check for
  9116. jCC xxx
  9117. <several movs>
  9118. xxx:
  9119. }
  9120. l:=0;
  9121. while assigned(hp1) and
  9122. CanBeCMOV(hp1) and
  9123. { stop on labels }
  9124. not(hp1.typ=ait_label) do
  9125. begin
  9126. inc(l);
  9127. GetNextInstruction(hp1,hp1);
  9128. end;
  9129. if assigned(hp1) then
  9130. begin
  9131. if FindLabel(tasmlabel(symbol),hp1) then
  9132. begin
  9133. if (l<=4) and (l>0) then
  9134. begin
  9135. condition:=inverse_cond(taicpu(p).condition);
  9136. UpdateUsedRegs(tai(p.next));
  9137. GetNextInstruction(p,hp1);
  9138. repeat
  9139. if not Assigned(hp1) then
  9140. InternalError(2018062900);
  9141. taicpu(hp1).opcode:=A_CMOVcc;
  9142. taicpu(hp1).condition:=condition;
  9143. UpdateUsedRegs(tai(hp1.next));
  9144. GetNextInstruction(hp1,hp1);
  9145. until not(CanBeCMOV(hp1));
  9146. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9147. hp2 := hp1;
  9148. repeat
  9149. if not Assigned(hp2) then
  9150. InternalError(2018062910);
  9151. case hp2.typ of
  9152. ait_label:
  9153. { What we expected - break out of the loop (it won't be a dead label at the top of
  9154. a cluster because that was optimised at an earlier stage) }
  9155. Break;
  9156. ait_align:
  9157. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9158. begin
  9159. hp2 := tai(hp2.Next);
  9160. Continue;
  9161. end;
  9162. else
  9163. begin
  9164. { Might be a comment or temporary allocation entry }
  9165. if not (hp2.typ in SkipInstr) then
  9166. InternalError(2018062911);
  9167. hp2 := tai(hp2.Next);
  9168. Continue;
  9169. end;
  9170. end;
  9171. until False;
  9172. { Now we can safely decrement the reference count }
  9173. tasmlabel(symbol).decrefs;
  9174. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9175. { Remove the original jump }
  9176. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9177. UpdateUsedRegs(tai(hp2.next));
  9178. GetNextInstruction(hp2, p); { Instruction after the label }
  9179. { Remove the label if this is its final reference }
  9180. if (tasmlabel(symbol).getrefs=0) then
  9181. StripLabelFast(hp1);
  9182. if Assigned(p) then
  9183. result:=true;
  9184. exit;
  9185. end;
  9186. end
  9187. else
  9188. begin
  9189. { check further for
  9190. jCC xxx
  9191. <several movs 1>
  9192. jmp yyy
  9193. xxx:
  9194. <several movs 2>
  9195. yyy:
  9196. }
  9197. { hp2 points to jmp yyy }
  9198. hp2:=hp1;
  9199. { skip hp1 to xxx (or an align right before it) }
  9200. GetNextInstruction(hp1, hp1);
  9201. if assigned(hp2) and
  9202. assigned(hp1) and
  9203. (l<=3) and
  9204. (hp2.typ=ait_instruction) and
  9205. (taicpu(hp2).is_jmp) and
  9206. (taicpu(hp2).condition=C_None) and
  9207. { real label and jump, no further references to the
  9208. label are allowed }
  9209. (tasmlabel(symbol).getrefs=1) and
  9210. FindLabel(tasmlabel(symbol),hp1) then
  9211. begin
  9212. l:=0;
  9213. { skip hp1 to <several moves 2> }
  9214. if (hp1.typ = ait_align) then
  9215. GetNextInstruction(hp1, hp1);
  9216. GetNextInstruction(hp1, hpmov2);
  9217. hp1 := hpmov2;
  9218. while assigned(hp1) and
  9219. CanBeCMOV(hp1) do
  9220. begin
  9221. inc(l);
  9222. GetNextInstruction(hp1, hp1);
  9223. end;
  9224. { hp1 points to yyy (or an align right before it) }
  9225. hp3 := hp1;
  9226. if assigned(hp1) and
  9227. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9228. begin
  9229. condition:=inverse_cond(taicpu(p).condition);
  9230. UpdateUsedRegs(tai(p.next));
  9231. GetNextInstruction(p,hp1);
  9232. repeat
  9233. taicpu(hp1).opcode:=A_CMOVcc;
  9234. taicpu(hp1).condition:=condition;
  9235. UpdateUsedRegs(tai(hp1.next));
  9236. GetNextInstruction(hp1,hp1);
  9237. until not(assigned(hp1)) or
  9238. not(CanBeCMOV(hp1));
  9239. condition:=inverse_cond(condition);
  9240. if GetLastInstruction(hpmov2,hp1) then
  9241. UpdateUsedRegs(tai(hp1.next));
  9242. hp1 := hpmov2;
  9243. { hp1 is now at <several movs 2> }
  9244. while Assigned(hp1) and CanBeCMOV(hp1) do
  9245. begin
  9246. taicpu(hp1).opcode:=A_CMOVcc;
  9247. taicpu(hp1).condition:=condition;
  9248. UpdateUsedRegs(tai(hp1.next));
  9249. GetNextInstruction(hp1,hp1);
  9250. end;
  9251. hp1 := p;
  9252. { Get first instruction after label }
  9253. UpdateUsedRegs(tai(hp3.next));
  9254. GetNextInstruction(hp3, p);
  9255. if assigned(p) and (hp3.typ = ait_align) then
  9256. GetNextInstruction(p, p);
  9257. { Don't dereference yet, as doing so will cause
  9258. GetNextInstruction to skip the label and
  9259. optional align marker. [Kit] }
  9260. GetNextInstruction(hp2, hp4);
  9261. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9262. { remove jCC }
  9263. RemoveInstruction(hp1);
  9264. { Now we can safely decrement it }
  9265. tasmlabel(symbol).decrefs;
  9266. { Remove label xxx (it will have a ref of zero due to the initial check }
  9267. StripLabelFast(hp4);
  9268. { remove jmp }
  9269. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9270. RemoveInstruction(hp2);
  9271. { As before, now we can safely decrement it }
  9272. tasmlabel(symbol).decrefs;
  9273. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9274. if tasmlabel(symbol).getrefs = 0 then
  9275. StripLabelFast(hp3);
  9276. if Assigned(p) then
  9277. result:=true;
  9278. exit;
  9279. end;
  9280. end;
  9281. end;
  9282. end;
  9283. {$endif i8086}
  9284. end;
  9285. end;
  9286. end;
  9287. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9288. var
  9289. hp1,hp2,hp3: tai;
  9290. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9291. NewSize: TOpSize;
  9292. NewRegSize: TSubRegister;
  9293. Limit: TCgInt;
  9294. SwapOper: POper;
  9295. begin
  9296. result:=false;
  9297. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9298. GetNextInstruction(p,hp1) and
  9299. (hp1.typ = ait_instruction);
  9300. if reg_and_hp1_is_instr and
  9301. (
  9302. (taicpu(hp1).opcode <> A_LEA) or
  9303. { If the LEA instruction can be converted into an arithmetic instruction,
  9304. it may be possible to then fold it. }
  9305. (
  9306. { If the flags register is in use, don't change the instruction
  9307. to an ADD otherwise this will scramble the flags. [Kit] }
  9308. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9309. ConvertLEA(taicpu(hp1))
  9310. )
  9311. ) and
  9312. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9313. GetNextInstruction(hp1,hp2) and
  9314. MatchInstruction(hp2,A_MOV,[]) and
  9315. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9316. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9317. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9318. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9319. {$ifdef i386}
  9320. { not all registers have byte size sub registers on i386 }
  9321. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9322. {$endif i386}
  9323. (((taicpu(hp1).ops=2) and
  9324. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9325. ((taicpu(hp1).ops=1) and
  9326. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9327. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9328. begin
  9329. { change movsX/movzX reg/ref, reg2
  9330. add/sub/or/... reg3/$const, reg2
  9331. mov reg2 reg/ref
  9332. to add/sub/or/... reg3/$const, reg/ref }
  9333. { by example:
  9334. movswl %si,%eax movswl %si,%eax p
  9335. decl %eax addl %edx,%eax hp1
  9336. movw %ax,%si movw %ax,%si hp2
  9337. ->
  9338. movswl %si,%eax movswl %si,%eax p
  9339. decw %eax addw %edx,%eax hp1
  9340. movw %ax,%si movw %ax,%si hp2
  9341. }
  9342. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9343. {
  9344. ->
  9345. movswl %si,%eax movswl %si,%eax p
  9346. decw %si addw %dx,%si hp1
  9347. movw %ax,%si movw %ax,%si hp2
  9348. }
  9349. case taicpu(hp1).ops of
  9350. 1:
  9351. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9352. 2:
  9353. begin
  9354. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9355. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9356. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9357. end;
  9358. else
  9359. internalerror(2008042702);
  9360. end;
  9361. {
  9362. ->
  9363. decw %si addw %dx,%si p
  9364. }
  9365. DebugMsg(SPeepholeOptimization + 'var3',p);
  9366. RemoveCurrentP(p, hp1);
  9367. RemoveInstruction(hp2);
  9368. Result := True;
  9369. Exit;
  9370. end;
  9371. if reg_and_hp1_is_instr and
  9372. (taicpu(hp1).opcode = A_MOV) and
  9373. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9374. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  9375. {$ifdef x86_64}
  9376. { check for implicit extension to 64 bit }
  9377. or
  9378. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9379. (taicpu(hp1).opsize=S_Q) and
  9380. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  9381. )
  9382. {$endif x86_64}
  9383. )
  9384. then
  9385. begin
  9386. { change
  9387. movx %reg1,%reg2
  9388. mov %reg2,%reg3
  9389. dealloc %reg2
  9390. into
  9391. movx %reg,%reg3
  9392. }
  9393. TransferUsedRegs(TmpUsedRegs);
  9394. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9395. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  9396. begin
  9397. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  9398. {$ifdef x86_64}
  9399. if (taicpu(p).opsize in [S_BL,S_WL]) and
  9400. (taicpu(hp1).opsize=S_Q) then
  9401. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  9402. else
  9403. {$endif x86_64}
  9404. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  9405. RemoveInstruction(hp1);
  9406. Result := True;
  9407. Exit;
  9408. end;
  9409. end;
  9410. if reg_and_hp1_is_instr and
  9411. ((taicpu(hp1).opcode=A_MOV) or
  9412. (taicpu(hp1).opcode=A_ADD) or
  9413. (taicpu(hp1).opcode=A_SUB) or
  9414. (taicpu(hp1).opcode=A_CMP) or
  9415. (taicpu(hp1).opcode=A_OR) or
  9416. (taicpu(hp1).opcode=A_XOR) or
  9417. (taicpu(hp1).opcode=A_AND)
  9418. ) and
  9419. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9420. begin
  9421. AndTest := (taicpu(hp1).opcode=A_AND) and
  9422. GetNextInstruction(hp1, hp2) and
  9423. (hp2.typ = ait_instruction) and
  9424. (
  9425. (
  9426. (taicpu(hp2).opcode=A_TEST) and
  9427. (
  9428. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  9429. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  9430. (
  9431. { If the AND and TEST instructions share a constant, this is also valid }
  9432. (taicpu(hp1).oper[0]^.typ = top_const) and
  9433. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  9434. )
  9435. ) and
  9436. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9437. ) or
  9438. (
  9439. (taicpu(hp2).opcode=A_CMP) and
  9440. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9441. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9442. )
  9443. );
  9444. { change
  9445. movx (oper),%reg2
  9446. and $x,%reg2
  9447. test %reg2,%reg2
  9448. dealloc %reg2
  9449. into
  9450. op %reg1,%reg3
  9451. if the second op accesses only the bits stored in reg1
  9452. }
  9453. if ((taicpu(p).oper[0]^.typ=top_reg) or
  9454. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  9455. (taicpu(hp1).oper[0]^.typ = top_const) and
  9456. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9457. AndTest then
  9458. begin
  9459. { Check if the AND constant is in range }
  9460. case taicpu(p).opsize of
  9461. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9462. begin
  9463. NewSize := S_B;
  9464. Limit := $FF;
  9465. end;
  9466. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9467. begin
  9468. NewSize := S_W;
  9469. Limit := $FFFF;
  9470. end;
  9471. {$ifdef x86_64}
  9472. S_LQ:
  9473. begin
  9474. NewSize := S_L;
  9475. Limit := $FFFFFFFF;
  9476. end;
  9477. {$endif x86_64}
  9478. else
  9479. InternalError(2021120303);
  9480. end;
  9481. if (
  9482. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  9483. { Check for negative operands }
  9484. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  9485. ) and
  9486. GetNextInstruction(hp2,hp3) and
  9487. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  9488. (taicpu(hp3).condition in [C_E,C_NE]) then
  9489. begin
  9490. TransferUsedRegs(TmpUsedRegs);
  9491. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9492. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9493. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  9494. begin
  9495. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  9496. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9497. taicpu(hp1).opcode := A_TEST;
  9498. taicpu(hp1).opsize := NewSize;
  9499. RemoveInstruction(hp2);
  9500. RemoveCurrentP(p, hp1);
  9501. Result:=true;
  9502. exit;
  9503. end;
  9504. end;
  9505. end;
  9506. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  9507. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  9508. (taicpu(hp1).opsize=S_B)) or
  9509. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  9510. (taicpu(hp1).opsize=S_W))
  9511. {$ifdef x86_64}
  9512. or ((taicpu(p).opsize=S_LQ) and
  9513. (taicpu(hp1).opsize=S_L))
  9514. {$endif x86_64}
  9515. ) and
  9516. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  9517. begin
  9518. { change
  9519. movx %reg1,%reg2
  9520. op %reg2,%reg3
  9521. dealloc %reg2
  9522. into
  9523. op %reg1,%reg3
  9524. if the second op accesses only the bits stored in reg1
  9525. }
  9526. TransferUsedRegs(TmpUsedRegs);
  9527. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9528. if AndTest then
  9529. begin
  9530. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9531. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9532. end
  9533. else
  9534. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9535. if not RegUsed then
  9536. begin
  9537. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  9538. if taicpu(p).oper[0]^.typ=top_reg then
  9539. begin
  9540. case taicpu(hp1).opsize of
  9541. S_B:
  9542. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  9543. S_W:
  9544. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  9545. S_L:
  9546. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  9547. else
  9548. Internalerror(2020102301);
  9549. end;
  9550. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  9551. end
  9552. else
  9553. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  9554. RemoveCurrentP(p);
  9555. if AndTest then
  9556. RemoveInstruction(hp2);
  9557. result:=true;
  9558. exit;
  9559. end;
  9560. end
  9561. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  9562. (
  9563. { Bitwise operations only }
  9564. (taicpu(hp1).opcode=A_AND) or
  9565. (taicpu(hp1).opcode=A_TEST) or
  9566. (
  9567. (taicpu(hp1).oper[0]^.typ = top_const) and
  9568. (
  9569. (taicpu(hp1).opcode=A_OR) or
  9570. (taicpu(hp1).opcode=A_XOR)
  9571. )
  9572. )
  9573. ) and
  9574. (
  9575. (taicpu(hp1).oper[0]^.typ = top_const) or
  9576. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  9577. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  9578. ) then
  9579. begin
  9580. { change
  9581. movx %reg2,%reg2
  9582. op const,%reg2
  9583. into
  9584. op const,%reg2 (smaller version)
  9585. movx %reg2,%reg2
  9586. also change
  9587. movx %reg1,%reg2
  9588. and/test (oper),%reg2
  9589. dealloc %reg2
  9590. into
  9591. and/test (oper),%reg1
  9592. }
  9593. case taicpu(p).opsize of
  9594. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9595. begin
  9596. NewSize := S_B;
  9597. NewRegSize := R_SUBL;
  9598. Limit := $FF;
  9599. end;
  9600. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9601. begin
  9602. NewSize := S_W;
  9603. NewRegSize := R_SUBW;
  9604. Limit := $FFFF;
  9605. end;
  9606. {$ifdef x86_64}
  9607. S_LQ:
  9608. begin
  9609. NewSize := S_L;
  9610. NewRegSize := R_SUBD;
  9611. Limit := $FFFFFFFF;
  9612. end;
  9613. {$endif x86_64}
  9614. else
  9615. Internalerror(2021120302);
  9616. end;
  9617. TransferUsedRegs(TmpUsedRegs);
  9618. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9619. if AndTest then
  9620. begin
  9621. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9622. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9623. end
  9624. else
  9625. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9626. if
  9627. (
  9628. (taicpu(p).opcode = A_MOVZX) and
  9629. (
  9630. (taicpu(hp1).opcode=A_AND) or
  9631. (taicpu(hp1).opcode=A_TEST)
  9632. ) and
  9633. not (
  9634. { If both are references, then the final instruction will have
  9635. both operands as references, which is not allowed }
  9636. (taicpu(p).oper[0]^.typ = top_ref) and
  9637. (taicpu(hp1).oper[0]^.typ = top_ref)
  9638. ) and
  9639. not RegUsed
  9640. ) or
  9641. (
  9642. (
  9643. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  9644. not RegUsed
  9645. ) and
  9646. (taicpu(p).oper[0]^.typ = top_reg) and
  9647. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9648. (taicpu(hp1).oper[0]^.typ = top_const) and
  9649. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  9650. ) then
  9651. begin
  9652. {$if defined(i386) or defined(i8086)}
  9653. { If the target size is 8-bit, make sure we can actually encode it }
  9654. if (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
  9655. Exit;
  9656. {$endif i386 or i8086}
  9657. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  9658. taicpu(hp1).opsize := NewSize;
  9659. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9660. if AndTest then
  9661. begin
  9662. RemoveInstruction(hp2);
  9663. if not RegUsed then
  9664. begin
  9665. taicpu(hp1).opcode := A_TEST;
  9666. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  9667. begin
  9668. { Make sure the reference is the second operand }
  9669. SwapOper := taicpu(hp1).oper[0];
  9670. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  9671. taicpu(hp1).oper[1] := SwapOper;
  9672. end;
  9673. end;
  9674. end;
  9675. case taicpu(hp1).oper[0]^.typ of
  9676. top_reg:
  9677. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  9678. top_const:
  9679. { For the AND/TEST case }
  9680. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  9681. else
  9682. ;
  9683. end;
  9684. if RegUsed then
  9685. begin
  9686. AsmL.Remove(p);
  9687. AsmL.InsertAfter(p, hp1);
  9688. p := hp1;
  9689. end
  9690. else
  9691. RemoveCurrentP(p, hp1);
  9692. result:=true;
  9693. exit;
  9694. end;
  9695. end;
  9696. end;
  9697. if reg_and_hp1_is_instr and
  9698. (taicpu(p).oper[0]^.typ = top_reg) and
  9699. (
  9700. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  9701. ) and
  9702. (taicpu(hp1).oper[0]^.typ = top_const) and
  9703. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9704. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  9705. { Minimum shift value allowed is the bit difference between the sizes }
  9706. (taicpu(hp1).oper[0]^.val >=
  9707. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  9708. 8 * (
  9709. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  9710. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  9711. )
  9712. ) then
  9713. begin
  9714. { For:
  9715. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  9716. shl/sal ##, %reg1
  9717. Remove the movsx/movzx instruction if the shift overwrites the
  9718. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  9719. }
  9720. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  9721. RemoveCurrentP(p, hp1);
  9722. Result := True;
  9723. Exit;
  9724. end
  9725. else if reg_and_hp1_is_instr and
  9726. (taicpu(p).oper[0]^.typ = top_reg) and
  9727. (
  9728. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  9729. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  9730. ) and
  9731. (taicpu(hp1).oper[0]^.typ = top_const) and
  9732. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9733. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  9734. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  9735. (taicpu(hp1).oper[0]^.val <
  9736. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  9737. 8 * (
  9738. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  9739. )
  9740. ) then
  9741. begin
  9742. { For:
  9743. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  9744. sar ##, %reg1 shr ##, %reg1
  9745. Move the shift to before the movx instruction if the shift value
  9746. is not too large.
  9747. }
  9748. asml.Remove(hp1);
  9749. asml.InsertBefore(hp1, p);
  9750. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  9751. case taicpu(p).opsize of
  9752. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  9753. taicpu(hp1).opsize := S_B;
  9754. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  9755. taicpu(hp1).opsize := S_W;
  9756. {$ifdef x86_64}
  9757. S_LQ:
  9758. taicpu(hp1).opsize := S_L;
  9759. {$endif}
  9760. else
  9761. InternalError(2020112401);
  9762. end;
  9763. if (taicpu(hp1).opcode = A_SHR) then
  9764. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  9765. else
  9766. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  9767. Result := True;
  9768. end;
  9769. if reg_and_hp1_is_instr and
  9770. (taicpu(p).oper[0]^.typ = top_reg) and
  9771. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9772. (
  9773. (taicpu(hp1).opcode = taicpu(p).opcode)
  9774. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  9775. {$ifdef x86_64}
  9776. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  9777. {$endif x86_64}
  9778. ) then
  9779. begin
  9780. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  9781. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  9782. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  9783. begin
  9784. {
  9785. For example:
  9786. movzbw %al,%ax
  9787. movzwl %ax,%eax
  9788. Compress into:
  9789. movzbl %al,%eax
  9790. }
  9791. RegUsed := False;
  9792. case taicpu(p).opsize of
  9793. S_BW:
  9794. case taicpu(hp1).opsize of
  9795. S_WL:
  9796. begin
  9797. taicpu(p).opsize := S_BL;
  9798. RegUsed := True;
  9799. end;
  9800. {$ifdef x86_64}
  9801. S_WQ:
  9802. begin
  9803. if taicpu(p).opcode = A_MOVZX then
  9804. begin
  9805. taicpu(p).opsize := S_BL;
  9806. { 64-bit zero extension is implicit, so change to the 32-bit register }
  9807. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9808. end
  9809. else
  9810. taicpu(p).opsize := S_BQ;
  9811. RegUsed := True;
  9812. end;
  9813. {$endif x86_64}
  9814. else
  9815. ;
  9816. end;
  9817. {$ifdef x86_64}
  9818. S_BL:
  9819. case taicpu(hp1).opsize of
  9820. S_LQ:
  9821. begin
  9822. if taicpu(p).opcode = A_MOVZX then
  9823. begin
  9824. taicpu(p).opsize := S_BL;
  9825. { 64-bit zero extension is implicit, so change to the 32-bit register }
  9826. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9827. end
  9828. else
  9829. taicpu(p).opsize := S_BQ;
  9830. RegUsed := True;
  9831. end;
  9832. else
  9833. ;
  9834. end;
  9835. S_WL:
  9836. case taicpu(hp1).opsize of
  9837. S_LQ:
  9838. begin
  9839. if taicpu(p).opcode = A_MOVZX then
  9840. begin
  9841. taicpu(p).opsize := S_WL;
  9842. { 64-bit zero extension is implicit, so change to the 32-bit register }
  9843. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9844. end
  9845. else
  9846. taicpu(p).opsize := S_WQ;
  9847. RegUsed := True;
  9848. end;
  9849. else
  9850. ;
  9851. end;
  9852. {$endif x86_64}
  9853. else
  9854. ;
  9855. end;
  9856. if RegUsed then
  9857. begin
  9858. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  9859. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  9860. RemoveInstruction(hp1);
  9861. Result := True;
  9862. Exit;
  9863. end;
  9864. end;
  9865. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  9866. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  9867. GetNextInstruction(hp1, hp2) and
  9868. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  9869. (
  9870. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  9871. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  9872. {$ifdef x86_64}
  9873. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  9874. {$endif x86_64}
  9875. ) and
  9876. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  9877. (
  9878. (
  9879. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9880. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  9881. ) or
  9882. (
  9883. { Only allow the operands in reverse order for TEST instructions }
  9884. (taicpu(hp2).opcode = A_TEST) and
  9885. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  9886. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  9887. )
  9888. ) then
  9889. begin
  9890. {
  9891. For example:
  9892. movzbl %al,%eax
  9893. movzbl (ref),%edx
  9894. andl %edx,%eax
  9895. (%edx deallocated)
  9896. Change to:
  9897. andb (ref),%al
  9898. movzbl %al,%eax
  9899. Rules are:
  9900. - First two instructions have the same opcode and opsize
  9901. - First instruction's operands are the same super-register
  9902. - Second instruction operates on a different register
  9903. - Third instruction is AND, OR, XOR or TEST
  9904. - Third instruction's operands are the destination registers of the first two instructions
  9905. - Third instruction writes to the destination register of the first instruction (except with TEST)
  9906. - Second instruction's destination register is deallocated afterwards
  9907. }
  9908. TransferUsedRegs(TmpUsedRegs);
  9909. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9910. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9911. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  9912. begin
  9913. case taicpu(p).opsize of
  9914. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9915. NewSize := S_B;
  9916. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9917. NewSize := S_W;
  9918. {$ifdef x86_64}
  9919. S_LQ:
  9920. NewSize := S_L;
  9921. {$endif x86_64}
  9922. else
  9923. InternalError(2021120301);
  9924. end;
  9925. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  9926. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  9927. taicpu(hp2).opsize := NewSize;
  9928. RemoveInstruction(hp1);
  9929. { With TEST, it's best to keep the MOVX instruction at the top }
  9930. if (taicpu(hp2).opcode <> A_TEST) then
  9931. begin
  9932. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  9933. asml.Remove(p);
  9934. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  9935. asml.InsertAfter(p, hp2);
  9936. p := hp2;
  9937. end
  9938. else
  9939. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  9940. Result := True;
  9941. Exit;
  9942. end;
  9943. end;
  9944. end;
  9945. if taicpu(p).opcode=A_MOVZX then
  9946. begin
  9947. { removes superfluous And's after movzx's }
  9948. if reg_and_hp1_is_instr and
  9949. (taicpu(hp1).opcode = A_AND) and
  9950. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9951. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  9952. {$ifdef x86_64}
  9953. { check for implicit extension to 64 bit }
  9954. or
  9955. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9956. (taicpu(hp1).opsize=S_Q) and
  9957. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  9958. )
  9959. {$endif x86_64}
  9960. )
  9961. then
  9962. begin
  9963. case taicpu(p).opsize Of
  9964. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9965. if (taicpu(hp1).oper[0]^.val = $ff) then
  9966. begin
  9967. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  9968. RemoveInstruction(hp1);
  9969. Result:=true;
  9970. exit;
  9971. end;
  9972. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9973. if (taicpu(hp1).oper[0]^.val = $ffff) then
  9974. begin
  9975. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  9976. RemoveInstruction(hp1);
  9977. Result:=true;
  9978. exit;
  9979. end;
  9980. {$ifdef x86_64}
  9981. S_LQ:
  9982. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  9983. begin
  9984. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  9985. RemoveInstruction(hp1);
  9986. Result:=true;
  9987. exit;
  9988. end;
  9989. {$endif x86_64}
  9990. else
  9991. ;
  9992. end;
  9993. { we cannot get rid of the and, but can we get rid of the movz ?}
  9994. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  9995. begin
  9996. case taicpu(p).opsize Of
  9997. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9998. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  9999. begin
  10000. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  10001. RemoveCurrentP(p,hp1);
  10002. Result:=true;
  10003. exit;
  10004. end;
  10005. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10006. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  10007. begin
  10008. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  10009. RemoveCurrentP(p,hp1);
  10010. Result:=true;
  10011. exit;
  10012. end;
  10013. {$ifdef x86_64}
  10014. S_LQ:
  10015. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  10016. begin
  10017. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  10018. RemoveCurrentP(p,hp1);
  10019. Result:=true;
  10020. exit;
  10021. end;
  10022. {$endif x86_64}
  10023. else
  10024. ;
  10025. end;
  10026. end;
  10027. end;
  10028. { changes some movzx constructs to faster synonyms (all examples
  10029. are given with eax/ax, but are also valid for other registers)}
  10030. if MatchOpType(taicpu(p),top_reg,top_reg) then
  10031. begin
  10032. case taicpu(p).opsize of
  10033. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  10034. (the machine code is equivalent to movzbl %al,%eax), but the
  10035. code generator still generates that assembler instruction and
  10036. it is silently converted. This should probably be checked.
  10037. [Kit] }
  10038. S_BW:
  10039. begin
  10040. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10041. (
  10042. not IsMOVZXAcceptable
  10043. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  10044. or (
  10045. (cs_opt_size in current_settings.optimizerswitches) and
  10046. (taicpu(p).oper[1]^.reg = NR_AX)
  10047. )
  10048. ) then
  10049. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  10050. begin
  10051. DebugMsg(SPeepholeOptimization + 'var7',p);
  10052. taicpu(p).opcode := A_AND;
  10053. taicpu(p).changeopsize(S_W);
  10054. taicpu(p).loadConst(0,$ff);
  10055. Result := True;
  10056. end
  10057. else if not IsMOVZXAcceptable and
  10058. GetNextInstruction(p, hp1) and
  10059. (tai(hp1).typ = ait_instruction) and
  10060. (taicpu(hp1).opcode = A_AND) and
  10061. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10062. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10063. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  10064. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  10065. begin
  10066. DebugMsg(SPeepholeOptimization + 'var8',p);
  10067. taicpu(p).opcode := A_MOV;
  10068. taicpu(p).changeopsize(S_W);
  10069. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10070. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10071. Result := True;
  10072. end;
  10073. end;
  10074. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10075. S_BL:
  10076. begin
  10077. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10078. (
  10079. not IsMOVZXAcceptable
  10080. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10081. or (
  10082. (cs_opt_size in current_settings.optimizerswitches) and
  10083. (taicpu(p).oper[1]^.reg = NR_EAX)
  10084. )
  10085. ) then
  10086. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10087. begin
  10088. DebugMsg(SPeepholeOptimization + 'var9',p);
  10089. taicpu(p).opcode := A_AND;
  10090. taicpu(p).changeopsize(S_L);
  10091. taicpu(p).loadConst(0,$ff);
  10092. Result := True;
  10093. end
  10094. else if not IsMOVZXAcceptable and
  10095. GetNextInstruction(p, hp1) and
  10096. (tai(hp1).typ = ait_instruction) and
  10097. (taicpu(hp1).opcode = A_AND) and
  10098. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10099. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10100. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10101. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10102. begin
  10103. DebugMsg(SPeepholeOptimization + 'var10',p);
  10104. taicpu(p).opcode := A_MOV;
  10105. taicpu(p).changeopsize(S_L);
  10106. { do not use R_SUBWHOLE
  10107. as movl %rdx,%eax
  10108. is invalid in assembler PM }
  10109. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10110. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10111. Result := True;
  10112. end;
  10113. end;
  10114. {$endif i8086}
  10115. S_WL:
  10116. if not IsMOVZXAcceptable then
  10117. begin
  10118. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10119. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10120. begin
  10121. DebugMsg(SPeepholeOptimization + 'var11',p);
  10122. taicpu(p).opcode := A_AND;
  10123. taicpu(p).changeopsize(S_L);
  10124. taicpu(p).loadConst(0,$ffff);
  10125. Result := True;
  10126. end
  10127. else if GetNextInstruction(p, hp1) and
  10128. (tai(hp1).typ = ait_instruction) and
  10129. (taicpu(hp1).opcode = A_AND) and
  10130. (taicpu(hp1).oper[0]^.typ = top_const) and
  10131. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10132. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10133. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10134. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10135. begin
  10136. DebugMsg(SPeepholeOptimization + 'var12',p);
  10137. taicpu(p).opcode := A_MOV;
  10138. taicpu(p).changeopsize(S_L);
  10139. { do not use R_SUBWHOLE
  10140. as movl %rdx,%eax
  10141. is invalid in assembler PM }
  10142. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10143. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10144. Result := True;
  10145. end;
  10146. end;
  10147. else
  10148. InternalError(2017050705);
  10149. end;
  10150. end
  10151. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10152. begin
  10153. if GetNextInstruction(p, hp1) and
  10154. (tai(hp1).typ = ait_instruction) and
  10155. (taicpu(hp1).opcode = A_AND) and
  10156. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10157. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10158. begin
  10159. //taicpu(p).opcode := A_MOV;
  10160. case taicpu(p).opsize Of
  10161. S_BL:
  10162. begin
  10163. DebugMsg(SPeepholeOptimization + 'var13',p);
  10164. taicpu(hp1).changeopsize(S_L);
  10165. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10166. end;
  10167. S_WL:
  10168. begin
  10169. DebugMsg(SPeepholeOptimization + 'var14',p);
  10170. taicpu(hp1).changeopsize(S_L);
  10171. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10172. end;
  10173. S_BW:
  10174. begin
  10175. DebugMsg(SPeepholeOptimization + 'var15',p);
  10176. taicpu(hp1).changeopsize(S_W);
  10177. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10178. end;
  10179. else
  10180. Internalerror(2017050704)
  10181. end;
  10182. Result := True;
  10183. end;
  10184. end;
  10185. end;
  10186. end;
  10187. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10188. var
  10189. hp1, hp2 : tai;
  10190. MaskLength : Cardinal;
  10191. MaskedBits : TCgInt;
  10192. ActiveReg : TRegister;
  10193. begin
  10194. Result:=false;
  10195. { There are no optimisations for reference targets }
  10196. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10197. Exit;
  10198. while GetNextInstruction(p, hp1) and
  10199. (hp1.typ = ait_instruction) do
  10200. begin
  10201. if (taicpu(p).oper[0]^.typ = top_const) then
  10202. begin
  10203. case taicpu(hp1).opcode of
  10204. A_AND:
  10205. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10206. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10207. { the second register must contain the first one, so compare their subreg types }
  10208. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10209. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10210. { change
  10211. and const1, reg
  10212. and const2, reg
  10213. to
  10214. and (const1 and const2), reg
  10215. }
  10216. begin
  10217. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10218. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10219. RemoveCurrentP(p, hp1);
  10220. Result:=true;
  10221. exit;
  10222. end;
  10223. A_CMP:
  10224. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10225. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10226. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10227. { Just check that the condition on the next instruction is compatible }
  10228. GetNextInstruction(hp1, hp2) and
  10229. (hp2.typ = ait_instruction) and
  10230. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10231. then
  10232. { change
  10233. and 2^n, reg
  10234. cmp 2^n, reg
  10235. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10236. to
  10237. and 2^n, reg
  10238. test reg, reg
  10239. j(~c) / set(~c) / cmov(~c)
  10240. }
  10241. begin
  10242. { Keep TEST instruction in, rather than remove it, because
  10243. it may trigger other optimisations such as MovAndTest2Test }
  10244. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10245. taicpu(hp1).opcode := A_TEST;
  10246. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10247. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10248. Result := True;
  10249. Exit;
  10250. end;
  10251. A_MOVZX:
  10252. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10253. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10254. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10255. (
  10256. (
  10257. (taicpu(p).opsize=S_W) and
  10258. (taicpu(hp1).opsize=S_BW)
  10259. ) or
  10260. (
  10261. (taicpu(p).opsize=S_L) and
  10262. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10263. )
  10264. {$ifdef x86_64}
  10265. or
  10266. (
  10267. (taicpu(p).opsize=S_Q) and
  10268. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10269. )
  10270. {$endif x86_64}
  10271. ) then
  10272. begin
  10273. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10274. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10275. ) or
  10276. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10277. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10278. then
  10279. begin
  10280. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10281. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10282. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10283. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10284. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10285. }
  10286. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10287. RemoveInstruction(hp1);
  10288. { See if there are other optimisations possible }
  10289. Continue;
  10290. end;
  10291. end;
  10292. A_SHL:
  10293. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10294. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10295. begin
  10296. {$ifopt R+}
  10297. {$define RANGE_WAS_ON}
  10298. {$R-}
  10299. {$endif}
  10300. { get length of potential and mask }
  10301. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10302. { really a mask? }
  10303. {$ifdef RANGE_WAS_ON}
  10304. {$R+}
  10305. {$endif}
  10306. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10307. { unmasked part shifted out? }
  10308. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10309. begin
  10310. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10311. RemoveCurrentP(p, hp1);
  10312. Result:=true;
  10313. exit;
  10314. end;
  10315. end;
  10316. A_SHR:
  10317. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10318. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10319. (taicpu(hp1).oper[0]^.val <= 63) then
  10320. begin
  10321. { Does SHR combined with the AND cover all the bits?
  10322. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10323. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10324. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10325. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10326. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10327. begin
  10328. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10329. RemoveCurrentP(p, hp1);
  10330. Result := True;
  10331. Exit;
  10332. end;
  10333. end;
  10334. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10335. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10336. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10337. begin
  10338. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10339. (
  10340. (
  10341. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10342. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10343. ) or (
  10344. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10345. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10346. {$ifdef x86_64}
  10347. ) or (
  10348. (taicpu(hp1).opsize = S_LQ) and
  10349. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10350. {$endif x86_64}
  10351. )
  10352. ) then
  10353. begin
  10354. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10355. begin
  10356. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10357. RemoveInstruction(hp1);
  10358. { See if there are other optimisations possible }
  10359. Continue;
  10360. end;
  10361. { The super-registers are the same though.
  10362. Note that this change by itself doesn't improve
  10363. code speed, but it opens up other optimisations. }
  10364. {$ifdef x86_64}
  10365. { Convert 64-bit register to 32-bit }
  10366. case taicpu(hp1).opsize of
  10367. S_BQ:
  10368. begin
  10369. taicpu(hp1).opsize := S_BL;
  10370. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10371. end;
  10372. S_WQ:
  10373. begin
  10374. taicpu(hp1).opsize := S_WL;
  10375. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10376. end
  10377. else
  10378. ;
  10379. end;
  10380. {$endif x86_64}
  10381. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  10382. taicpu(hp1).opcode := A_MOVZX;
  10383. { See if there are other optimisations possible }
  10384. Continue;
  10385. end;
  10386. end;
  10387. else
  10388. ;
  10389. end;
  10390. end
  10391. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  10392. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  10393. begin
  10394. {$ifdef x86_64}
  10395. if (taicpu(p).opsize = S_Q) then
  10396. begin
  10397. { Never necessary }
  10398. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  10399. RemoveCurrentP(p, hp1);
  10400. Result := True;
  10401. Exit;
  10402. end;
  10403. {$endif x86_64}
  10404. { Forward check to determine necessity of and %reg,%reg }
  10405. TransferUsedRegs(TmpUsedRegs);
  10406. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10407. { Saves on a bunch of dereferences }
  10408. ActiveReg := taicpu(p).oper[1]^.reg;
  10409. case taicpu(hp1).opcode of
  10410. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10411. if (
  10412. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10413. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10414. ) and
  10415. (
  10416. (taicpu(hp1).opcode <> A_MOV) or
  10417. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  10418. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  10419. ) and
  10420. not (
  10421. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  10422. (taicpu(hp1).opcode = A_MOV) and
  10423. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  10424. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  10425. ) and
  10426. (
  10427. (
  10428. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10429. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  10430. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  10431. ) or
  10432. (
  10433. {$ifdef x86_64}
  10434. (
  10435. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  10436. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  10437. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  10438. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  10439. ) and
  10440. {$endif x86_64}
  10441. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  10442. )
  10443. ) then
  10444. begin
  10445. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  10446. RemoveCurrentP(p, hp1);
  10447. Result := True;
  10448. Exit;
  10449. end;
  10450. A_ADD,
  10451. A_AND,
  10452. A_BSF,
  10453. A_BSR,
  10454. A_BTC,
  10455. A_BTR,
  10456. A_BTS,
  10457. A_OR,
  10458. A_SUB,
  10459. A_XOR:
  10460. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  10461. if (
  10462. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10463. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10464. ) and
  10465. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  10466. begin
  10467. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  10468. RemoveCurrentP(p, hp1);
  10469. Result := True;
  10470. Exit;
  10471. end;
  10472. A_CMP,
  10473. A_TEST:
  10474. if (
  10475. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10476. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10477. ) and
  10478. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  10479. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  10480. begin
  10481. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  10482. RemoveCurrentP(p, hp1);
  10483. Result := True;
  10484. Exit;
  10485. end;
  10486. A_BSWAP,
  10487. A_NEG,
  10488. A_NOT:
  10489. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  10490. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  10491. begin
  10492. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  10493. RemoveCurrentP(p, hp1);
  10494. Result := True;
  10495. Exit;
  10496. end;
  10497. else
  10498. ;
  10499. end;
  10500. end;
  10501. if (taicpu(hp1).is_jmp) and
  10502. (taicpu(hp1).opcode<>A_JMP) and
  10503. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  10504. begin
  10505. { change
  10506. and x, reg
  10507. jxx
  10508. to
  10509. test x, reg
  10510. jxx
  10511. if reg is deallocated before the
  10512. jump, but only if it's a conditional jump (PFV)
  10513. }
  10514. taicpu(p).opcode := A_TEST;
  10515. Exit;
  10516. end;
  10517. Break;
  10518. end;
  10519. { Lone AND tests }
  10520. if (taicpu(p).oper[0]^.typ = top_const) then
  10521. begin
  10522. {
  10523. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  10524. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  10525. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  10526. }
  10527. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  10528. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  10529. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  10530. begin
  10531. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  10532. if taicpu(p).opsize = S_L then
  10533. begin
  10534. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  10535. Result := True;
  10536. end;
  10537. end;
  10538. end;
  10539. { Backward check to determine necessity of and %reg,%reg }
  10540. if (taicpu(p).oper[0]^.typ = top_reg) and
  10541. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10542. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10543. GetLastInstruction(p, hp2) and
  10544. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  10545. { Check size of adjacent instruction to determine if the AND is
  10546. effectively a null operation }
  10547. (
  10548. (taicpu(p).opsize = taicpu(hp2).opsize) or
  10549. { Note: Don't include S_Q }
  10550. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  10551. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  10552. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  10553. ) then
  10554. begin
  10555. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  10556. { If GetNextInstruction returned False, hp1 will be nil }
  10557. RemoveCurrentP(p, hp1);
  10558. Result := True;
  10559. Exit;
  10560. end;
  10561. end;
  10562. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  10563. var
  10564. hp1: tai; NewRef: TReference;
  10565. { This entire nested function is used in an if-statement below, but we
  10566. want to avoid all the used reg transfers and GetNextInstruction calls
  10567. until we really have to check }
  10568. function MemRegisterNotUsedLater: Boolean; inline;
  10569. var
  10570. hp2: tai;
  10571. begin
  10572. TransferUsedRegs(TmpUsedRegs);
  10573. hp2 := p;
  10574. repeat
  10575. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10576. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10577. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  10578. end;
  10579. begin
  10580. Result := False;
  10581. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  10582. Exit;
  10583. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  10584. begin
  10585. { Change:
  10586. add %reg2,%reg1
  10587. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  10588. To:
  10589. mov/s/z #(%reg1,%reg2),%reg1
  10590. }
  10591. if MatchOpType(taicpu(p), top_reg, top_reg) and
  10592. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  10593. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  10594. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  10595. (
  10596. (
  10597. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  10598. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  10599. { r/esp cannot be an index }
  10600. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  10601. ) or (
  10602. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  10603. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  10604. )
  10605. ) and (
  10606. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  10607. (
  10608. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  10609. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10610. MemRegisterNotUsedLater
  10611. )
  10612. ) then
  10613. begin
  10614. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  10615. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  10616. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  10617. RemoveCurrentp(p, hp1);
  10618. Result := True;
  10619. Exit;
  10620. end;
  10621. { Change:
  10622. addl/q $x,%reg1
  10623. movl/q %reg1,%reg2
  10624. To:
  10625. leal/q $x(%reg1),%reg2
  10626. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  10627. Breaks the dependency chain.
  10628. }
  10629. if MatchOpType(taicpu(p),top_const,top_reg) and
  10630. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  10631. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10632. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  10633. (
  10634. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  10635. not (cs_opt_size in current_settings.optimizerswitches) or
  10636. (
  10637. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  10638. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  10639. )
  10640. ) then
  10641. begin
  10642. { Change the MOV instruction to a LEA instruction, and update the
  10643. first operand }
  10644. reference_reset(NewRef, 1, []);
  10645. NewRef.base := taicpu(p).oper[1]^.reg;
  10646. NewRef.scalefactor := 1;
  10647. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  10648. taicpu(hp1).opcode := A_LEA;
  10649. taicpu(hp1).loadref(0, NewRef);
  10650. TransferUsedRegs(TmpUsedRegs);
  10651. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10652. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  10653. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  10654. begin
  10655. { Move what is now the LEA instruction to before the SUB instruction }
  10656. Asml.Remove(hp1);
  10657. Asml.InsertBefore(hp1, p);
  10658. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  10659. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  10660. p := hp1;
  10661. end
  10662. else
  10663. begin
  10664. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  10665. RemoveCurrentP(p, hp1);
  10666. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  10667. end;
  10668. Result := True;
  10669. end;
  10670. end;
  10671. end;
  10672. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  10673. var
  10674. SubReg: TSubRegister;
  10675. begin
  10676. Result:=false;
  10677. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  10678. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  10679. with taicpu(p).oper[0]^.ref^ do
  10680. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  10681. begin
  10682. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  10683. begin
  10684. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  10685. taicpu(p).opcode := A_ADD;
  10686. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  10687. Result := True;
  10688. end
  10689. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  10690. begin
  10691. if (base <> NR_NO) then
  10692. begin
  10693. if (scalefactor <= 1) then
  10694. begin
  10695. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  10696. taicpu(p).opcode := A_ADD;
  10697. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  10698. Result := True;
  10699. end;
  10700. end
  10701. else
  10702. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  10703. if (scalefactor in [2, 4, 8]) then
  10704. begin
  10705. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  10706. taicpu(p).loadconst(0, BsrByte(scalefactor));
  10707. taicpu(p).opcode := A_SHL;
  10708. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  10709. Result := True;
  10710. end;
  10711. end;
  10712. end;
  10713. end;
  10714. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  10715. var
  10716. hp1: tai; NewRef: TReference;
  10717. begin
  10718. { Change:
  10719. subl/q $x,%reg1
  10720. movl/q %reg1,%reg2
  10721. To:
  10722. leal/q $-x(%reg1),%reg2
  10723. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  10724. Breaks the dependency chain and potentially permits the removal of
  10725. a CMP instruction if one follows.
  10726. }
  10727. Result := False;
  10728. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  10729. MatchOpType(taicpu(p),top_const,top_reg) and
  10730. GetNextInstruction(p, hp1) and
  10731. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  10732. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10733. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  10734. (
  10735. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  10736. not (cs_opt_size in current_settings.optimizerswitches) or
  10737. (
  10738. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  10739. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  10740. )
  10741. ) then
  10742. begin
  10743. { Change the MOV instruction to a LEA instruction, and update the
  10744. first operand }
  10745. reference_reset(NewRef, 1, []);
  10746. NewRef.base := taicpu(p).oper[1]^.reg;
  10747. NewRef.scalefactor := 1;
  10748. NewRef.offset := -taicpu(p).oper[0]^.val;
  10749. taicpu(hp1).opcode := A_LEA;
  10750. taicpu(hp1).loadref(0, NewRef);
  10751. TransferUsedRegs(TmpUsedRegs);
  10752. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10753. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  10754. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  10755. begin
  10756. { Move what is now the LEA instruction to before the SUB instruction }
  10757. Asml.Remove(hp1);
  10758. Asml.InsertBefore(hp1, p);
  10759. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  10760. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  10761. p := hp1;
  10762. end
  10763. else
  10764. begin
  10765. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  10766. RemoveCurrentP(p, hp1);
  10767. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  10768. end;
  10769. Result := True;
  10770. end;
  10771. end;
  10772. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  10773. begin
  10774. { we can skip all instructions not messing with the stack pointer }
  10775. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  10776. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  10777. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  10778. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  10779. ({(taicpu(hp1).ops=0) or }
  10780. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  10781. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  10782. ) and }
  10783. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  10784. )
  10785. ) do
  10786. GetNextInstruction(hp1,hp1);
  10787. Result:=assigned(hp1);
  10788. end;
  10789. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  10790. var
  10791. hp1, hp2, hp3, hp4, hp5: tai;
  10792. begin
  10793. Result:=false;
  10794. hp5:=nil;
  10795. { replace
  10796. leal(q) x(<stackpointer>),<stackpointer>
  10797. call procname
  10798. leal(q) -x(<stackpointer>),<stackpointer>
  10799. ret
  10800. by
  10801. jmp procname
  10802. but do it only on level 4 because it destroys stack back traces
  10803. }
  10804. if (cs_opt_level4 in current_settings.optimizerswitches) and
  10805. MatchOpType(taicpu(p),top_ref,top_reg) and
  10806. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  10807. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  10808. { the -8 or -24 are not required, but bail out early if possible,
  10809. higher values are unlikely }
  10810. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  10811. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  10812. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  10813. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  10814. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  10815. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  10816. GetNextInstruction(p, hp1) and
  10817. { Take a copy of hp1 }
  10818. SetAndTest(hp1, hp4) and
  10819. { trick to skip label }
  10820. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  10821. SkipSimpleInstructions(hp1) and
  10822. MatchInstruction(hp1,A_CALL,[S_NO]) and
  10823. GetNextInstruction(hp1, hp2) and
  10824. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  10825. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  10826. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  10827. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  10828. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  10829. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  10830. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  10831. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  10832. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  10833. GetNextInstruction(hp2, hp3) and
  10834. { trick to skip label }
  10835. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  10836. (MatchInstruction(hp3,A_RET,[S_NO]) or
  10837. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  10838. SetAndTest(hp3,hp5) and
  10839. GetNextInstruction(hp3,hp3) and
  10840. MatchInstruction(hp3,A_RET,[S_NO])
  10841. )
  10842. ) and
  10843. (taicpu(hp3).ops=0) then
  10844. begin
  10845. taicpu(hp1).opcode := A_JMP;
  10846. taicpu(hp1).is_jmp := true;
  10847. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  10848. RemoveCurrentP(p, hp4);
  10849. RemoveInstruction(hp2);
  10850. RemoveInstruction(hp3);
  10851. if Assigned(hp5) then
  10852. begin
  10853. AsmL.Remove(hp5);
  10854. ASmL.InsertBefore(hp5,hp1)
  10855. end;
  10856. Result:=true;
  10857. end;
  10858. end;
  10859. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  10860. {$ifdef x86_64}
  10861. var
  10862. hp1, hp2, hp3, hp4, hp5: tai;
  10863. {$endif x86_64}
  10864. begin
  10865. Result:=false;
  10866. {$ifdef x86_64}
  10867. hp5:=nil;
  10868. { replace
  10869. push %rax
  10870. call procname
  10871. pop %rcx
  10872. ret
  10873. by
  10874. jmp procname
  10875. but do it only on level 4 because it destroys stack back traces
  10876. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  10877. for all supported calling conventions
  10878. }
  10879. if (cs_opt_level4 in current_settings.optimizerswitches) and
  10880. MatchOpType(taicpu(p),top_reg) and
  10881. (taicpu(p).oper[0]^.reg=NR_RAX) and
  10882. GetNextInstruction(p, hp1) and
  10883. { Take a copy of hp1 }
  10884. SetAndTest(hp1, hp4) and
  10885. { trick to skip label }
  10886. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  10887. SkipSimpleInstructions(hp1) and
  10888. MatchInstruction(hp1,A_CALL,[S_NO]) and
  10889. GetNextInstruction(hp1, hp2) and
  10890. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  10891. MatchOpType(taicpu(hp2),top_reg) and
  10892. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  10893. GetNextInstruction(hp2, hp3) and
  10894. { trick to skip label }
  10895. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  10896. (MatchInstruction(hp3,A_RET,[S_NO]) or
  10897. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  10898. SetAndTest(hp3,hp5) and
  10899. GetNextInstruction(hp3,hp3) and
  10900. MatchInstruction(hp3,A_RET,[S_NO])
  10901. )
  10902. ) and
  10903. (taicpu(hp3).ops=0) then
  10904. begin
  10905. taicpu(hp1).opcode := A_JMP;
  10906. taicpu(hp1).is_jmp := true;
  10907. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  10908. RemoveCurrentP(p, hp4);
  10909. RemoveInstruction(hp2);
  10910. RemoveInstruction(hp3);
  10911. if Assigned(hp5) then
  10912. begin
  10913. AsmL.Remove(hp5);
  10914. ASmL.InsertBefore(hp5,hp1)
  10915. end;
  10916. Result:=true;
  10917. end;
  10918. {$endif x86_64}
  10919. end;
  10920. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  10921. var
  10922. Value, RegName: string;
  10923. begin
  10924. Result:=false;
  10925. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  10926. begin
  10927. case taicpu(p).oper[0]^.val of
  10928. 0:
  10929. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  10930. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  10931. begin
  10932. { change "mov $0,%reg" into "xor %reg,%reg" }
  10933. taicpu(p).opcode := A_XOR;
  10934. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  10935. Result := True;
  10936. {$ifdef x86_64}
  10937. end
  10938. else if (taicpu(p).opsize = S_Q) then
  10939. begin
  10940. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  10941. { The actual optimization }
  10942. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  10943. taicpu(p).changeopsize(S_L);
  10944. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  10945. Result := True;
  10946. end;
  10947. $1..$FFFFFFFF:
  10948. begin
  10949. { Code size reduction by J. Gareth "Kit" Moreton }
  10950. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  10951. case taicpu(p).opsize of
  10952. S_Q:
  10953. begin
  10954. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  10955. Value := debug_tostr(taicpu(p).oper[0]^.val);
  10956. { The actual optimization }
  10957. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  10958. taicpu(p).changeopsize(S_L);
  10959. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  10960. Result := True;
  10961. end;
  10962. else
  10963. { Do nothing };
  10964. end;
  10965. {$endif x86_64}
  10966. end;
  10967. -1:
  10968. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  10969. if (cs_opt_size in current_settings.optimizerswitches) and
  10970. (taicpu(p).opsize <> S_B) and
  10971. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  10972. begin
  10973. { change "mov $-1,%reg" into "or $-1,%reg" }
  10974. { NOTES:
  10975. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  10976. - This operation creates a false dependency on the register, so only do it when optimising for size
  10977. - 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
  10978. }
  10979. taicpu(p).opcode := A_OR;
  10980. Result := True;
  10981. end;
  10982. else
  10983. { Do nothing };
  10984. end;
  10985. end;
  10986. end;
  10987. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  10988. var
  10989. hp1: tai;
  10990. begin
  10991. { Detect:
  10992. andw x, %ax (0 <= x < $8000)
  10993. ...
  10994. movzwl %ax,%eax
  10995. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  10996. }
  10997. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  10998. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  10999. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  11000. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11001. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11002. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11003. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11004. begin
  11005. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  11006. taicpu(hp1).opcode := A_CWDE;
  11007. taicpu(hp1).clearop(0);
  11008. taicpu(hp1).clearop(1);
  11009. taicpu(hp1).ops := 0;
  11010. { A change was made, but not with p, so move forward 1 }
  11011. p := tai(p.Next);
  11012. Result := True;
  11013. end;
  11014. end;
  11015. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  11016. begin
  11017. Result := False;
  11018. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  11019. Exit;
  11020. { Convert:
  11021. movswl %ax,%eax -> cwtl
  11022. movslq %eax,%rax -> cdqe
  11023. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  11024. refer to the same opcode and depends only on the assembler's
  11025. current operand-size attribute. [Kit]
  11026. }
  11027. with taicpu(p) do
  11028. case opsize of
  11029. S_WL:
  11030. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  11031. begin
  11032. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  11033. opcode := A_CWDE;
  11034. clearop(0);
  11035. clearop(1);
  11036. ops := 0;
  11037. Result := True;
  11038. end;
  11039. {$ifdef x86_64}
  11040. S_LQ:
  11041. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  11042. begin
  11043. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  11044. opcode := A_CDQE;
  11045. clearop(0);
  11046. clearop(1);
  11047. ops := 0;
  11048. Result := True;
  11049. end;
  11050. {$endif x86_64}
  11051. else
  11052. ;
  11053. end;
  11054. end;
  11055. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  11056. var
  11057. hp1: tai;
  11058. begin
  11059. { Detect:
  11060. shr x, %ax (x > 0)
  11061. ...
  11062. movzwl %ax,%eax
  11063. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11064. }
  11065. Result := False;
  11066. if MatchOpType(taicpu(p), top_const, top_reg) and
  11067. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11068. (taicpu(p).oper[0]^.val > 0) and
  11069. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11070. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11071. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11072. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11073. begin
  11074. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11075. taicpu(hp1).opcode := A_CWDE;
  11076. taicpu(hp1).clearop(0);
  11077. taicpu(hp1).clearop(1);
  11078. taicpu(hp1).ops := 0;
  11079. { A change was made, but not with p, so move forward 1 }
  11080. p := tai(p.Next);
  11081. Result := True;
  11082. end;
  11083. end;
  11084. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11085. var
  11086. hp1, hp2: tai;
  11087. Opposite, SecondOpposite: TAsmOp;
  11088. NewCond: TAsmCond;
  11089. begin
  11090. Result := False;
  11091. { Change:
  11092. add/sub 128,(dest)
  11093. To:
  11094. sub/add -128,(dest)
  11095. This generaally takes fewer bytes to encode because -128 can be stored
  11096. in a signed byte, whereas +128 cannot.
  11097. }
  11098. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11099. begin
  11100. if taicpu(p).opcode = A_ADD then
  11101. Opposite := A_SUB
  11102. else
  11103. Opposite := A_ADD;
  11104. { Be careful if the flags are in use, because the CF flag inverts
  11105. when changing from ADD to SUB and vice versa }
  11106. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11107. GetNextInstruction(p, hp1) then
  11108. begin
  11109. TransferUsedRegs(TmpUsedRegs);
  11110. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11111. hp2 := hp1;
  11112. { Scan ahead to check if everything's safe }
  11113. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11114. begin
  11115. if (hp1.typ <> ait_instruction) then
  11116. { Probably unsafe since the flags are still in use }
  11117. Exit;
  11118. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11119. { Stop searching at an unconditional jump }
  11120. Break;
  11121. if not
  11122. (
  11123. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11124. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11125. ) and
  11126. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11127. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11128. Exit;
  11129. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11130. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11131. { Move to the next instruction }
  11132. GetNextInstruction(hp1, hp1);
  11133. end;
  11134. while Assigned(hp2) and (hp2 <> hp1) do
  11135. begin
  11136. NewCond := C_None;
  11137. case taicpu(hp2).condition of
  11138. C_A, C_NBE:
  11139. NewCond := C_BE;
  11140. C_B, C_C, C_NAE:
  11141. NewCond := C_AE;
  11142. C_AE, C_NB, C_NC:
  11143. NewCond := C_B;
  11144. C_BE, C_NA:
  11145. NewCond := C_A;
  11146. else
  11147. { No change needed };
  11148. end;
  11149. if NewCond <> C_None then
  11150. begin
  11151. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11152. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11153. taicpu(hp2).condition := NewCond;
  11154. end
  11155. else
  11156. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11157. begin
  11158. { Because of the flipping of the carry bit, to ensure
  11159. the operation remains equivalent, ADC becomes SBB
  11160. and vice versa, and the constant is not-inverted.
  11161. If multiple ADCs or SBBs appear in a row, each one
  11162. changed causes the carry bit to invert, so they all
  11163. need to be flipped }
  11164. if taicpu(hp2).opcode = A_ADC then
  11165. SecondOpposite := A_SBB
  11166. else
  11167. SecondOpposite := A_ADC;
  11168. if taicpu(hp2).oper[0]^.typ <> top_const then
  11169. { Should have broken out of this optimisation already }
  11170. InternalError(2021112901);
  11171. 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]^) + ' -> ' +
  11172. 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);
  11173. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11174. taicpu(hp2).opcode := SecondOpposite;
  11175. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11176. end;
  11177. { Move to the next instruction }
  11178. GetNextInstruction(hp2, hp2);
  11179. end;
  11180. if (hp2 <> hp1) then
  11181. InternalError(2021111501);
  11182. end;
  11183. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11184. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11185. taicpu(p).opcode := Opposite;
  11186. taicpu(p).oper[0]^.val := -128;
  11187. { No further optimisations can be made on this instruction, so move
  11188. onto the next one to save time }
  11189. p := tai(p.Next);
  11190. UpdateUsedRegs(p);
  11191. Result := True;
  11192. Exit;
  11193. end;
  11194. { Detect:
  11195. add/sub %reg2,(dest)
  11196. add/sub x, (dest)
  11197. (dest can be a register or a reference)
  11198. Swap the instructions to minimise a pipeline stall. This reverses the
  11199. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11200. optimisations could be made.
  11201. }
  11202. if (taicpu(p).oper[0]^.typ = top_reg) and
  11203. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11204. (
  11205. (
  11206. (taicpu(p).oper[1]^.typ = top_reg) and
  11207. { We can try searching further ahead if we're writing to a register }
  11208. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11209. ) or
  11210. (
  11211. (taicpu(p).oper[1]^.typ = top_ref) and
  11212. GetNextInstruction(p, hp1)
  11213. )
  11214. ) and
  11215. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11216. (taicpu(hp1).oper[0]^.typ = top_const) and
  11217. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11218. begin
  11219. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11220. TransferUsedRegs(TmpUsedRegs);
  11221. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11222. hp2 := p;
  11223. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11224. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11225. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11226. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11227. begin
  11228. asml.remove(hp1);
  11229. asml.InsertBefore(hp1, p);
  11230. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11231. Result := True;
  11232. end;
  11233. end;
  11234. end;
  11235. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11236. begin
  11237. Result:=false;
  11238. { change "cmp $0, %reg" to "test %reg, %reg" }
  11239. if MatchOpType(taicpu(p),top_const,top_reg) and
  11240. (taicpu(p).oper[0]^.val = 0) then
  11241. begin
  11242. taicpu(p).opcode := A_TEST;
  11243. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11244. Result:=true;
  11245. end;
  11246. end;
  11247. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11248. var
  11249. IsTestConstX : Boolean;
  11250. hp1,hp2 : tai;
  11251. begin
  11252. Result:=false;
  11253. { removes the line marked with (x) from the sequence
  11254. and/or/xor/add/sub/... $x, %y
  11255. test/or %y, %y | test $-1, %y (x)
  11256. j(n)z _Label
  11257. as the first instruction already adjusts the ZF
  11258. %y operand may also be a reference }
  11259. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11260. MatchOperand(taicpu(p).oper[0]^,-1);
  11261. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11262. GetLastInstruction(p, hp1) and
  11263. (tai(hp1).typ = ait_instruction) and
  11264. GetNextInstruction(p,hp2) and
  11265. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11266. case taicpu(hp1).opcode Of
  11267. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  11268. { These two instructions set the zero flag if the result is zero }
  11269. A_POPCNT, A_LZCNT:
  11270. begin
  11271. if (
  11272. { With POPCNT, an input of zero will set the zero flag
  11273. because the population count of zero is zero }
  11274. (taicpu(hp1).opcode = A_POPCNT) and
  11275. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  11276. (
  11277. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  11278. { Faster than going through the second half of the 'or'
  11279. condition below }
  11280. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  11281. )
  11282. ) or (
  11283. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  11284. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11285. { and in case of carry for A(E)/B(E)/C/NC }
  11286. (
  11287. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11288. (
  11289. (taicpu(hp1).opcode <> A_ADD) and
  11290. (taicpu(hp1).opcode <> A_SUB) and
  11291. (taicpu(hp1).opcode <> A_LZCNT)
  11292. )
  11293. )
  11294. ) then
  11295. begin
  11296. RemoveCurrentP(p, hp2);
  11297. Result:=true;
  11298. Exit;
  11299. end;
  11300. end;
  11301. A_SHL, A_SAL, A_SHR, A_SAR:
  11302. begin
  11303. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11304. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11305. { therefore, it's only safe to do this optimization for }
  11306. { shifts by a (nonzero) constant }
  11307. (taicpu(hp1).oper[0]^.typ = top_const) and
  11308. (taicpu(hp1).oper[0]^.val <> 0) and
  11309. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11310. { and in case of carry for A(E)/B(E)/C/NC }
  11311. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11312. begin
  11313. RemoveCurrentP(p, hp2);
  11314. Result:=true;
  11315. Exit;
  11316. end;
  11317. end;
  11318. A_DEC, A_INC, A_NEG:
  11319. begin
  11320. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11321. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11322. { and in case of carry for A(E)/B(E)/C/NC }
  11323. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11324. begin
  11325. RemoveCurrentP(p, hp2);
  11326. Result:=true;
  11327. Exit;
  11328. end;
  11329. end
  11330. else
  11331. ;
  11332. end; { case }
  11333. { change "test $-1,%reg" into "test %reg,%reg" }
  11334. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11335. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11336. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11337. if MatchInstruction(p, A_OR, []) and
  11338. { Can only match if they're both registers }
  11339. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11340. begin
  11341. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11342. taicpu(p).opcode := A_TEST;
  11343. { No need to set Result to True, as we've done all the optimisations we can }
  11344. end;
  11345. end;
  11346. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11347. var
  11348. hp1,hp3 : tai;
  11349. {$ifndef x86_64}
  11350. hp2 : taicpu;
  11351. {$endif x86_64}
  11352. begin
  11353. Result:=false;
  11354. hp3:=nil;
  11355. {$ifndef x86_64}
  11356. { don't do this on modern CPUs, this really hurts them due to
  11357. broken call/ret pairing }
  11358. if (current_settings.optimizecputype < cpu_Pentium2) and
  11359. not(cs_create_pic in current_settings.moduleswitches) and
  11360. GetNextInstruction(p, hp1) and
  11361. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11362. MatchOpType(taicpu(hp1),top_ref) and
  11363. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11364. begin
  11365. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  11366. InsertLLItem(p.previous, p, hp2);
  11367. taicpu(p).opcode := A_JMP;
  11368. taicpu(p).is_jmp := true;
  11369. RemoveInstruction(hp1);
  11370. Result:=true;
  11371. end
  11372. else
  11373. {$endif x86_64}
  11374. { replace
  11375. call procname
  11376. ret
  11377. by
  11378. jmp procname
  11379. but do it only on level 4 because it destroys stack back traces
  11380. else if the subroutine is marked as no return, remove the ret
  11381. }
  11382. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  11383. (po_noreturn in current_procinfo.procdef.procoptions)) and
  11384. GetNextInstruction(p, hp1) and
  11385. (MatchInstruction(hp1,A_RET,[S_NO]) or
  11386. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  11387. SetAndTest(hp1,hp3) and
  11388. GetNextInstruction(hp1,hp1) and
  11389. MatchInstruction(hp1,A_RET,[S_NO])
  11390. )
  11391. ) and
  11392. (taicpu(hp1).ops=0) then
  11393. begin
  11394. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11395. { we might destroy stack alignment here if we do not do a call }
  11396. (target_info.stackalign<=sizeof(SizeUInt)) then
  11397. begin
  11398. taicpu(p).opcode := A_JMP;
  11399. taicpu(p).is_jmp := true;
  11400. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  11401. end
  11402. else
  11403. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  11404. RemoveInstruction(hp1);
  11405. if Assigned(hp3) then
  11406. begin
  11407. AsmL.Remove(hp3);
  11408. AsmL.InsertBefore(hp3,p)
  11409. end;
  11410. Result:=true;
  11411. end;
  11412. end;
  11413. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  11414. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  11415. begin
  11416. case OpSize of
  11417. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11418. Result := (Val <= $FF) and (Val >= -128);
  11419. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11420. Result := (Val <= $FFFF) and (Val >= -32768);
  11421. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  11422. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  11423. else
  11424. Result := True;
  11425. end;
  11426. end;
  11427. var
  11428. hp1, hp2 : tai;
  11429. SizeChange: Boolean;
  11430. PreMessage: string;
  11431. begin
  11432. Result := False;
  11433. if (taicpu(p).oper[0]^.typ = top_reg) and
  11434. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11435. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  11436. begin
  11437. { Change (using movzbl %al,%eax as an example):
  11438. movzbl %al, %eax movzbl %al, %eax
  11439. cmpl x, %eax testl %eax,%eax
  11440. To:
  11441. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  11442. movzbl %al, %eax movzbl %al, %eax
  11443. Smaller instruction and minimises pipeline stall as the CPU
  11444. doesn't have to wait for the register to get zero-extended. [Kit]
  11445. Also allow if the smaller of the two registers is being checked,
  11446. as this still removes the false dependency.
  11447. }
  11448. if
  11449. (
  11450. (
  11451. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  11452. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  11453. ) or (
  11454. { If MatchOperand returns True, they must both be registers }
  11455. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  11456. )
  11457. ) and
  11458. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  11459. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  11460. begin
  11461. 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);
  11462. asml.Remove(hp1);
  11463. asml.InsertBefore(hp1, p);
  11464. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  11465. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  11466. begin
  11467. taicpu(hp1).opcode := A_TEST;
  11468. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  11469. end;
  11470. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11471. case taicpu(p).opsize of
  11472. S_BW, S_BL:
  11473. begin
  11474. SizeChange := taicpu(hp1).opsize <> S_B;
  11475. taicpu(hp1).changeopsize(S_B);
  11476. end;
  11477. S_WL:
  11478. begin
  11479. SizeChange := taicpu(hp1).opsize <> S_W;
  11480. taicpu(hp1).changeopsize(S_W);
  11481. end
  11482. else
  11483. InternalError(2020112701);
  11484. end;
  11485. UpdateUsedRegs(tai(p.Next));
  11486. { Check if the register is used aferwards - if not, we can
  11487. remove the movzx instruction completely }
  11488. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  11489. begin
  11490. { Hp1 is a better position than p for debugging purposes }
  11491. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  11492. RemoveCurrentp(p, hp1);
  11493. Result := True;
  11494. end;
  11495. if SizeChange then
  11496. DebugMsg(SPeepholeOptimization + PreMessage +
  11497. 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)
  11498. else
  11499. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  11500. Exit;
  11501. end;
  11502. { Change (using movzwl %ax,%eax as an example):
  11503. movzwl %ax, %eax
  11504. movb %al, (dest) (Register is smaller than read register in movz)
  11505. To:
  11506. movb %al, (dest) (Move one back to avoid a false dependency)
  11507. movzwl %ax, %eax
  11508. }
  11509. if (taicpu(hp1).opcode = A_MOV) and
  11510. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11511. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  11512. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  11513. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  11514. begin
  11515. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  11516. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  11517. asml.Remove(hp1);
  11518. asml.InsertBefore(hp1, p);
  11519. if taicpu(hp1).oper[1]^.typ = top_reg then
  11520. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  11521. { Check if the register is used aferwards - if not, we can
  11522. remove the movzx instruction completely }
  11523. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  11524. begin
  11525. { Hp1 is a better position than p for debugging purposes }
  11526. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  11527. RemoveCurrentp(p, hp1);
  11528. Result := True;
  11529. end;
  11530. Exit;
  11531. end;
  11532. end;
  11533. end;
  11534. {$ifdef x86_64}
  11535. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  11536. var
  11537. PreMessage, RegName: string;
  11538. begin
  11539. { Code size reduction by J. Gareth "Kit" Moreton }
  11540. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  11541. as this removes the REX prefix }
  11542. Result := False;
  11543. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  11544. Exit;
  11545. if taicpu(p).oper[0]^.typ <> top_reg then
  11546. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  11547. InternalError(2018011500);
  11548. case taicpu(p).opsize of
  11549. S_Q:
  11550. begin
  11551. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  11552. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  11553. { The actual optimization }
  11554. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11555. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11556. taicpu(p).changeopsize(S_L);
  11557. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  11558. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  11559. end;
  11560. else
  11561. ;
  11562. end;
  11563. end;
  11564. {$endif}
  11565. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  11566. var
  11567. XReg: TRegister;
  11568. begin
  11569. Result := False;
  11570. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  11571. Smaller encoding and slightly faster on some platforms (also works for
  11572. ZMM-sized registers) }
  11573. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  11574. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  11575. begin
  11576. XReg := taicpu(p).oper[0]^.reg;
  11577. if (taicpu(p).oper[1]^.reg = XReg) then
  11578. begin
  11579. taicpu(p).changeopsize(S_XMM);
  11580. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  11581. if (cs_opt_size in current_settings.optimizerswitches) then
  11582. begin
  11583. { Change input registers to %xmm0 to reduce size. Note that
  11584. there's a risk of a false dependency doing this, so only
  11585. optimise for size here }
  11586. XReg := NR_XMM0;
  11587. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  11588. end
  11589. else
  11590. begin
  11591. setsubreg(XReg, R_SUBMMX);
  11592. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  11593. end;
  11594. taicpu(p).oper[0]^.reg := XReg;
  11595. taicpu(p).oper[1]^.reg := XReg;
  11596. Result := True;
  11597. end;
  11598. end;
  11599. end;
  11600. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  11601. var
  11602. OperIdx: Integer;
  11603. begin
  11604. for OperIdx := 0 to p.ops - 1 do
  11605. if p.oper[OperIdx]^.typ = top_ref then
  11606. optimize_ref(p.oper[OperIdx]^.ref^, False);
  11607. end;
  11608. end.