aoptx86.pas 398 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374
  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. interface
  21. uses
  22. globtype,
  23. cpubase,
  24. aasmtai,aasmcpu,
  25. cgbase,cgutils,
  26. aopt,aoptobj;
  27. type
  28. TOptsToCheck = (
  29. aoc_MovAnd2Mov_3
  30. );
  31. TX86AsmOptimizer = class(TAsmOptimizer)
  32. { some optimizations are very expensive to check, so the
  33. pre opt pass can be used to set some flags, depending on the found
  34. instructions if it is worth to check a certain optimization }
  35. OptsToCheck : set of TOptsToCheck;
  36. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  37. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  38. function RegReadByInstruction(reg : TRegister; hp : tai) : boolean;
  39. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  40. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  41. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  42. potentially allowing further optimisation (although it might need to know if
  43. it crossed a conditional jump. }
  44. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  45. {
  46. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  47. the use of a register by allocs/dealloc, so it can ignore calls.
  48. In the following example, GetNextInstructionUsingReg will return the second movq,
  49. GetNextInstructionUsingRegTrackingUse won't.
  50. movq %rdi,%rax
  51. # Register rdi released
  52. # Register rdi allocated
  53. movq %rax,%rdi
  54. While in this example:
  55. movq %rdi,%rax
  56. call proc
  57. movq %rdi,%rax
  58. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  59. won't.
  60. }
  61. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  62. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  63. private
  64. function SkipSimpleInstructions(var hp1: tai): Boolean;
  65. protected
  66. class function IsMOVZXAcceptable: Boolean; static; inline;
  67. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  68. function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  69. { checks whether reading the value in reg1 depends on the value of reg2. This
  70. is very similar to SuperRegisterEquals, except it takes into account that
  71. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  72. depend on the value in AH). }
  73. function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  74. { Replaces all references to AOldReg in a memory reference to ANewReg }
  75. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  76. { Replaces all references to AOldReg in an operand to ANewReg }
  77. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  78. { Replaces all references to AOldReg in an instruction to ANewReg,
  79. except where the register is being written }
  80. function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  81. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  82. or writes to a global symbol }
  83. class function IsRefSafe(const ref: PReference): Boolean; static; inline;
  84. { Returns true if the given MOV instruction can be safely converted to CMOV }
  85. class function CanBeCMOV(p : tai) : boolean; static;
  86. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  87. conversion was successful }
  88. function ConvertLEA(const p : taicpu): Boolean;
  89. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  90. procedure DebugMsg(const s : string; p : tai);inline;
  91. class function IsExitCode(p : tai) : boolean; static;
  92. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  93. procedure RemoveLastDeallocForFuncRes(p : tai);
  94. function DoSubAddOpt(var p : tai) : Boolean;
  95. function PrePeepholeOptSxx(var p : tai) : boolean;
  96. function PrePeepholeOptIMUL(var p : tai) : boolean;
  97. function OptPass1Test(var p: tai): boolean;
  98. function OptPass1Add(var p: tai): boolean;
  99. function OptPass1AND(var p : tai) : boolean;
  100. function OptPass1_V_MOVAP(var p : tai) : boolean;
  101. function OptPass1VOP(var p : tai) : boolean;
  102. function OptPass1MOV(var p : tai) : boolean;
  103. function OptPass1Movx(var p : tai) : boolean;
  104. function OptPass1MOVXX(var p : tai) : boolean;
  105. function OptPass1OP(var p : tai) : boolean;
  106. function OptPass1LEA(var p : tai) : boolean;
  107. function OptPass1Sub(var p : tai) : boolean;
  108. function OptPass1SHLSAL(var p : tai) : boolean;
  109. function OptPass1FSTP(var p : tai) : boolean;
  110. function OptPass1FLD(var p : tai) : boolean;
  111. function OptPass1Cmp(var p : tai) : boolean;
  112. function OptPass1PXor(var p : tai) : boolean;
  113. function OptPass1VPXor(var p: tai): boolean;
  114. function OptPass1Imul(var p : tai) : boolean;
  115. function OptPass1Jcc(var p : tai) : boolean;
  116. function OptPass1SHXX(var p: tai): boolean;
  117. function OptPass2Movx(var p : tai): Boolean;
  118. function OptPass2MOV(var p : tai) : boolean;
  119. function OptPass2Imul(var p : tai) : boolean;
  120. function OptPass2Jmp(var p : tai) : boolean;
  121. function OptPass2Jcc(var p : tai) : boolean;
  122. function OptPass2Lea(var p: tai): Boolean;
  123. function OptPass2SUB(var p: tai): Boolean;
  124. function OptPass2ADD(var p : tai): Boolean;
  125. function OptPass2SETcc(var p : tai) : boolean;
  126. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  127. function PostPeepholeOptMov(var p : tai) : Boolean;
  128. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  129. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  130. function PostPeepholeOptXor(var p : tai) : Boolean;
  131. {$endif}
  132. function PostPeepholeOptAnd(var p : tai) : boolean;
  133. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  134. function PostPeepholeOptCmp(var p : tai) : Boolean;
  135. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  136. function PostPeepholeOptCall(var p : tai) : Boolean;
  137. function PostPeepholeOptLea(var p : tai) : Boolean;
  138. function PostPeepholeOptPush(var p: tai): Boolean;
  139. function PostPeepholeOptShr(var p : tai) : boolean;
  140. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  141. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  142. procedure SwapMovCmp(var p, hp1: tai);
  143. { Processor-dependent reference optimisation }
  144. class procedure OptimizeRefs(var p: taicpu); static;
  145. end;
  146. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  147. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  148. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  149. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  150. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  151. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  152. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  153. {$if max_operands>2}
  154. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  155. {$endif max_operands>2}
  156. function RefsEqual(const r1, r2: treference): boolean;
  157. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  158. { returns true, if ref is a reference using only the registers passed as base and index
  159. and having an offset }
  160. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  161. implementation
  162. uses
  163. cutils,verbose,
  164. systems,
  165. globals,
  166. cpuinfo,
  167. procinfo,
  168. paramgr,
  169. aasmbase,
  170. aoptbase,aoptutils,
  171. symconst,symsym,
  172. cgx86,
  173. itcpugas;
  174. {$ifdef DEBUG_AOPTCPU}
  175. const
  176. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  177. {$else DEBUG_AOPTCPU}
  178. { Empty strings help the optimizer to remove string concatenations that won't
  179. ever appear to the user on release builds. [Kit] }
  180. const
  181. SPeepholeOptimization = '';
  182. {$endif DEBUG_AOPTCPU}
  183. LIST_STEP_SIZE = 4;
  184. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  185. begin
  186. result :=
  187. (instr.typ = ait_instruction) and
  188. (taicpu(instr).opcode = op) and
  189. ((opsize = []) or (taicpu(instr).opsize in opsize));
  190. end;
  191. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  192. begin
  193. result :=
  194. (instr.typ = ait_instruction) and
  195. ((taicpu(instr).opcode = op1) or
  196. (taicpu(instr).opcode = op2)
  197. ) and
  198. ((opsize = []) or (taicpu(instr).opsize in opsize));
  199. end;
  200. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  201. begin
  202. result :=
  203. (instr.typ = ait_instruction) and
  204. ((taicpu(instr).opcode = op1) or
  205. (taicpu(instr).opcode = op2) or
  206. (taicpu(instr).opcode = op3)
  207. ) and
  208. ((opsize = []) or (taicpu(instr).opsize in opsize));
  209. end;
  210. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  211. const opsize : topsizes) : boolean;
  212. var
  213. op : TAsmOp;
  214. begin
  215. result:=false;
  216. for op in ops do
  217. begin
  218. if (instr.typ = ait_instruction) and
  219. (taicpu(instr).opcode = op) and
  220. ((opsize = []) or (taicpu(instr).opsize in opsize)) then
  221. begin
  222. result:=true;
  223. exit;
  224. end;
  225. end;
  226. end;
  227. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  228. begin
  229. result := (oper.typ = top_reg) and (oper.reg = reg);
  230. end;
  231. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  232. begin
  233. result := (oper.typ = top_const) and (oper.val = a);
  234. end;
  235. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  236. begin
  237. result := oper1.typ = oper2.typ;
  238. if result then
  239. case oper1.typ of
  240. top_const:
  241. Result:=oper1.val = oper2.val;
  242. top_reg:
  243. Result:=oper1.reg = oper2.reg;
  244. top_ref:
  245. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  246. else
  247. internalerror(2013102801);
  248. end
  249. end;
  250. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  251. begin
  252. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  253. if result then
  254. case oper1.typ of
  255. top_const:
  256. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  257. top_reg:
  258. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  259. top_ref:
  260. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  261. else
  262. internalerror(2020052401);
  263. end
  264. end;
  265. function RefsEqual(const r1, r2: treference): boolean;
  266. begin
  267. RefsEqual :=
  268. (r1.offset = r2.offset) and
  269. (r1.segment = r2.segment) and (r1.base = r2.base) and
  270. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  271. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  272. (r1.relsymbol = r2.relsymbol) and
  273. (r1.volatility=[]) and
  274. (r2.volatility=[]);
  275. end;
  276. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  277. begin
  278. Result:=(ref.offset=0) and
  279. (ref.scalefactor in [0,1]) and
  280. (ref.segment=NR_NO) and
  281. (ref.symbol=nil) and
  282. (ref.relsymbol=nil) and
  283. ((base=NR_INVALID) or
  284. (ref.base=base)) and
  285. ((index=NR_INVALID) or
  286. (ref.index=index)) and
  287. (ref.volatility=[]);
  288. end;
  289. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  290. begin
  291. Result:=(ref.scalefactor in [0,1]) and
  292. (ref.segment=NR_NO) and
  293. (ref.symbol=nil) and
  294. (ref.relsymbol=nil) and
  295. ((base=NR_INVALID) or
  296. (ref.base=base)) and
  297. ((index=NR_INVALID) or
  298. (ref.index=index)) and
  299. (ref.volatility=[]);
  300. end;
  301. function InstrReadsFlags(p: tai): boolean;
  302. begin
  303. InstrReadsFlags := true;
  304. case p.typ of
  305. ait_instruction:
  306. if InsProp[taicpu(p).opcode].Ch*
  307. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  308. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  309. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  310. exit;
  311. ait_label:
  312. exit;
  313. else
  314. ;
  315. end;
  316. InstrReadsFlags := false;
  317. end;
  318. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  319. begin
  320. Next:=Current;
  321. repeat
  322. Result:=GetNextInstruction(Next,Next);
  323. until not (Result) or
  324. not(cs_opt_level3 in current_settings.optimizerswitches) or
  325. (Next.typ<>ait_instruction) or
  326. RegInInstruction(reg,Next) or
  327. is_calljmp(taicpu(Next).opcode);
  328. end;
  329. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  330. begin
  331. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  332. Next := Current;
  333. repeat
  334. Result := GetNextInstruction(Next,Next);
  335. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  336. if is_calljmpuncond(taicpu(Next).opcode) then
  337. begin
  338. Result := False;
  339. Exit;
  340. end
  341. else
  342. CrossJump := True;
  343. until not Result or
  344. not (cs_opt_level3 in current_settings.optimizerswitches) or
  345. (Next.typ <> ait_instruction) or
  346. RegInInstruction(reg,Next);
  347. end;
  348. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  349. begin
  350. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  351. begin
  352. Result:=GetNextInstruction(Current,Next);
  353. exit;
  354. end;
  355. Next:=tai(Current.Next);
  356. Result:=false;
  357. while assigned(Next) do
  358. begin
  359. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  360. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  361. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  362. exit
  363. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  364. begin
  365. Result:=true;
  366. exit;
  367. end;
  368. Next:=tai(Next.Next);
  369. end;
  370. end;
  371. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  372. begin
  373. Result:=RegReadByInstruction(reg,hp);
  374. end;
  375. function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  376. var
  377. p: taicpu;
  378. opcount: longint;
  379. begin
  380. RegReadByInstruction := false;
  381. if hp.typ <> ait_instruction then
  382. exit;
  383. p := taicpu(hp);
  384. case p.opcode of
  385. A_CALL:
  386. regreadbyinstruction := true;
  387. A_IMUL:
  388. case p.ops of
  389. 1:
  390. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  391. (
  392. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  393. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  394. );
  395. 2,3:
  396. regReadByInstruction :=
  397. reginop(reg,p.oper[0]^) or
  398. reginop(reg,p.oper[1]^);
  399. else
  400. InternalError(2019112801);
  401. end;
  402. A_MUL:
  403. begin
  404. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  405. (
  406. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  407. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  408. );
  409. end;
  410. A_IDIV,A_DIV:
  411. begin
  412. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  413. (
  414. (getregtype(reg)=R_INTREGISTER) and
  415. (
  416. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  417. )
  418. );
  419. end;
  420. else
  421. begin
  422. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  423. begin
  424. RegReadByInstruction := false;
  425. exit;
  426. end;
  427. for opcount := 0 to p.ops-1 do
  428. if (p.oper[opCount]^.typ = top_ref) and
  429. RegInRef(reg,p.oper[opcount]^.ref^) then
  430. begin
  431. RegReadByInstruction := true;
  432. exit
  433. end;
  434. { special handling for SSE MOVSD }
  435. if (p.opcode=A_MOVSD) and (p.ops>0) then
  436. begin
  437. if p.ops<>2 then
  438. internalerror(2017042702);
  439. regReadByInstruction := reginop(reg,p.oper[0]^) or
  440. (
  441. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  442. );
  443. exit;
  444. end;
  445. with insprop[p.opcode] do
  446. begin
  447. if getregtype(reg)=R_INTREGISTER then
  448. begin
  449. case getsupreg(reg) of
  450. RS_EAX:
  451. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  452. begin
  453. RegReadByInstruction := true;
  454. exit
  455. end;
  456. RS_ECX:
  457. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  458. begin
  459. RegReadByInstruction := true;
  460. exit
  461. end;
  462. RS_EDX:
  463. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  464. begin
  465. RegReadByInstruction := true;
  466. exit
  467. end;
  468. RS_EBX:
  469. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  470. begin
  471. RegReadByInstruction := true;
  472. exit
  473. end;
  474. RS_ESP:
  475. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  476. begin
  477. RegReadByInstruction := true;
  478. exit
  479. end;
  480. RS_EBP:
  481. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  482. begin
  483. RegReadByInstruction := true;
  484. exit
  485. end;
  486. RS_ESI:
  487. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  488. begin
  489. RegReadByInstruction := true;
  490. exit
  491. end;
  492. RS_EDI:
  493. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  494. begin
  495. RegReadByInstruction := true;
  496. exit
  497. end;
  498. end;
  499. end;
  500. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  501. begin
  502. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  503. begin
  504. case p.condition of
  505. C_A,C_NBE, { CF=0 and ZF=0 }
  506. C_BE,C_NA: { CF=1 or ZF=1 }
  507. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  508. C_AE,C_NB,C_NC, { CF=0 }
  509. C_B,C_NAE,C_C: { CF=1 }
  510. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  511. C_NE,C_NZ, { ZF=0 }
  512. C_E,C_Z: { ZF=1 }
  513. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  514. C_G,C_NLE, { ZF=0 and SF=OF }
  515. C_LE,C_NG: { ZF=1 or SF<>OF }
  516. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  517. C_GE,C_NL, { SF=OF }
  518. C_L,C_NGE: { SF<>OF }
  519. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  520. C_NO, { OF=0 }
  521. C_O: { OF=1 }
  522. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  523. C_NP,C_PO, { PF=0 }
  524. C_P,C_PE: { PF=1 }
  525. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  526. C_NS, { SF=0 }
  527. C_S: { SF=1 }
  528. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  529. else
  530. internalerror(2017042701);
  531. end;
  532. if RegReadByInstruction then
  533. exit;
  534. end;
  535. case getsubreg(reg) of
  536. R_SUBW,R_SUBD,R_SUBQ:
  537. RegReadByInstruction :=
  538. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  539. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  540. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  541. R_SUBFLAGCARRY:
  542. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  543. R_SUBFLAGPARITY:
  544. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  545. R_SUBFLAGAUXILIARY:
  546. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  547. R_SUBFLAGZERO:
  548. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  549. R_SUBFLAGSIGN:
  550. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  551. R_SUBFLAGOVERFLOW:
  552. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  553. R_SUBFLAGINTERRUPT:
  554. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  555. R_SUBFLAGDIRECTION:
  556. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  557. else
  558. internalerror(2017042601);
  559. end;
  560. exit;
  561. end;
  562. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  563. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  564. (p.oper[0]^.reg=p.oper[1]^.reg) then
  565. exit;
  566. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  567. begin
  568. RegReadByInstruction := true;
  569. exit
  570. end;
  571. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  572. begin
  573. RegReadByInstruction := true;
  574. exit
  575. end;
  576. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  577. begin
  578. RegReadByInstruction := true;
  579. exit
  580. end;
  581. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  582. begin
  583. RegReadByInstruction := true;
  584. exit
  585. end;
  586. end;
  587. end;
  588. end;
  589. end;
  590. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  591. begin
  592. result:=false;
  593. if p1.typ<>ait_instruction then
  594. exit;
  595. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  596. exit(true);
  597. if (getregtype(reg)=R_INTREGISTER) and
  598. { change information for xmm movsd are not correct }
  599. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  600. begin
  601. case getsupreg(reg) of
  602. { RS_EAX = RS_RAX on x86-64 }
  603. RS_EAX:
  604. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  605. RS_ECX:
  606. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  607. RS_EDX:
  608. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  609. RS_EBX:
  610. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  611. RS_ESP:
  612. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  613. RS_EBP:
  614. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  615. RS_ESI:
  616. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  617. RS_EDI:
  618. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  619. else
  620. ;
  621. end;
  622. if result then
  623. exit;
  624. end
  625. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  626. begin
  627. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  628. exit(true);
  629. case getsubreg(reg) of
  630. R_SUBFLAGCARRY:
  631. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  632. R_SUBFLAGPARITY:
  633. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  634. R_SUBFLAGAUXILIARY:
  635. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  636. R_SUBFLAGZERO:
  637. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  638. R_SUBFLAGSIGN:
  639. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  640. R_SUBFLAGOVERFLOW:
  641. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  642. R_SUBFLAGINTERRUPT:
  643. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  644. R_SUBFLAGDIRECTION:
  645. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  646. else
  647. ;
  648. end;
  649. if result then
  650. exit;
  651. end
  652. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  653. exit(true);
  654. Result:=inherited RegInInstruction(Reg, p1);
  655. end;
  656. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  657. begin
  658. Result := False;
  659. if p1.typ <> ait_instruction then
  660. exit;
  661. with insprop[taicpu(p1).opcode] do
  662. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  663. begin
  664. case getsubreg(reg) of
  665. R_SUBW,R_SUBD,R_SUBQ:
  666. Result :=
  667. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  668. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  669. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  670. R_SUBFLAGCARRY:
  671. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  672. R_SUBFLAGPARITY:
  673. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  674. R_SUBFLAGAUXILIARY:
  675. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  676. R_SUBFLAGZERO:
  677. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  678. R_SUBFLAGSIGN:
  679. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  680. R_SUBFLAGOVERFLOW:
  681. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  682. R_SUBFLAGINTERRUPT:
  683. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  684. R_SUBFLAGDIRECTION:
  685. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  686. else
  687. internalerror(2017042602);
  688. end;
  689. exit;
  690. end;
  691. case taicpu(p1).opcode of
  692. A_CALL:
  693. { We could potentially set Result to False if the register in
  694. question is non-volatile for the subroutine's calling convention,
  695. but this would require detecting the calling convention in use and
  696. also assuming that the routine doesn't contain malformed assembly
  697. language, for example... so it could only be done under -O4 as it
  698. would be considered a side-effect. [Kit] }
  699. Result := True;
  700. A_MOVSD:
  701. { special handling for SSE MOVSD }
  702. if (taicpu(p1).ops>0) then
  703. begin
  704. if taicpu(p1).ops<>2 then
  705. internalerror(2017042703);
  706. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  707. end;
  708. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  709. so fix it here (FK)
  710. }
  711. A_VMOVSS,
  712. A_VMOVSD:
  713. begin
  714. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  715. exit;
  716. end;
  717. A_IMUL:
  718. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  719. else
  720. ;
  721. end;
  722. if Result then
  723. exit;
  724. with insprop[taicpu(p1).opcode] do
  725. begin
  726. if getregtype(reg)=R_INTREGISTER then
  727. begin
  728. case getsupreg(reg) of
  729. RS_EAX:
  730. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  731. begin
  732. Result := True;
  733. exit
  734. end;
  735. RS_ECX:
  736. if [Ch_WECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  737. begin
  738. Result := True;
  739. exit
  740. end;
  741. RS_EDX:
  742. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  743. begin
  744. Result := True;
  745. exit
  746. end;
  747. RS_EBX:
  748. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  749. begin
  750. Result := True;
  751. exit
  752. end;
  753. RS_ESP:
  754. if [Ch_WESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  755. begin
  756. Result := True;
  757. exit
  758. end;
  759. RS_EBP:
  760. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  761. begin
  762. Result := True;
  763. exit
  764. end;
  765. RS_ESI:
  766. if [Ch_WESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  767. begin
  768. Result := True;
  769. exit
  770. end;
  771. RS_EDI:
  772. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  773. begin
  774. Result := True;
  775. exit
  776. end;
  777. end;
  778. end;
  779. if ([CH_RWOP1,CH_WOP1,CH_MOP1]*Ch<>[]) and reginop(reg,taicpu(p1).oper[0]^) then
  780. begin
  781. Result := true;
  782. exit
  783. end;
  784. if ([Ch_RWOP2,Ch_WOP2,Ch_MOP2]*Ch<>[]) and reginop(reg,taicpu(p1).oper[1]^) then
  785. begin
  786. Result := true;
  787. exit
  788. end;
  789. if ([Ch_RWOP3,Ch_WOP3,Ch_MOP3]*Ch<>[]) and reginop(reg,taicpu(p1).oper[2]^) then
  790. begin
  791. Result := true;
  792. exit
  793. end;
  794. if ([Ch_RWOP4,Ch_WOP4,Ch_MOP4]*Ch<>[]) and reginop(reg,taicpu(p1).oper[3]^) then
  795. begin
  796. Result := true;
  797. exit
  798. end;
  799. end;
  800. end;
  801. {$ifdef DEBUG_AOPTCPU}
  802. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  803. begin
  804. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  805. end;
  806. function debug_tostr(i: tcgint): string; inline;
  807. begin
  808. Result := tostr(i);
  809. end;
  810. function debug_regname(r: TRegister): string; inline;
  811. begin
  812. Result := '%' + std_regname(r);
  813. end;
  814. { Debug output function - creates a string representation of an operator }
  815. function debug_operstr(oper: TOper): string;
  816. begin
  817. case oper.typ of
  818. top_const:
  819. Result := '$' + debug_tostr(oper.val);
  820. top_reg:
  821. Result := debug_regname(oper.reg);
  822. top_ref:
  823. begin
  824. if oper.ref^.offset <> 0 then
  825. Result := debug_tostr(oper.ref^.offset) + '('
  826. else
  827. Result := '(';
  828. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  829. begin
  830. Result := Result + debug_regname(oper.ref^.base);
  831. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  832. Result := Result + ',' + debug_regname(oper.ref^.index);
  833. end
  834. else
  835. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  836. Result := Result + debug_regname(oper.ref^.index);
  837. if (oper.ref^.scalefactor > 1) then
  838. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  839. else
  840. Result := Result + ')';
  841. end;
  842. else
  843. Result := '[UNKNOWN]';
  844. end;
  845. end;
  846. function debug_op2str(opcode: tasmop): string; inline;
  847. begin
  848. Result := std_op2str[opcode];
  849. end;
  850. function debug_opsize2str(opsize: topsize): string; inline;
  851. begin
  852. Result := gas_opsize2str[opsize];
  853. end;
  854. {$else DEBUG_AOPTCPU}
  855. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  856. begin
  857. end;
  858. function debug_tostr(i: tcgint): string; inline;
  859. begin
  860. Result := '';
  861. end;
  862. function debug_regname(r: TRegister): string; inline;
  863. begin
  864. Result := '';
  865. end;
  866. function debug_operstr(oper: TOper): string; inline;
  867. begin
  868. Result := '';
  869. end;
  870. function debug_op2str(opcode: tasmop): string; inline;
  871. begin
  872. Result := '';
  873. end;
  874. function debug_opsize2str(opsize: topsize): string; inline;
  875. begin
  876. Result := '';
  877. end;
  878. {$endif DEBUG_AOPTCPU}
  879. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  880. begin
  881. {$ifdef x86_64}
  882. { Always fine on x86-64 }
  883. Result := True;
  884. {$else x86_64}
  885. Result :=
  886. {$ifdef i8086}
  887. (current_settings.cputype >= cpu_386) and
  888. {$endif i8086}
  889. (
  890. { Always accept if optimising for size }
  891. (cs_opt_size in current_settings.optimizerswitches) or
  892. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  893. (current_settings.optimizecputype >= cpu_Pentium2)
  894. );
  895. {$endif x86_64}
  896. end;
  897. function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  898. begin
  899. if not SuperRegistersEqual(reg1,reg2) then
  900. exit(false);
  901. if getregtype(reg1)<>R_INTREGISTER then
  902. exit(true); {because SuperRegisterEqual is true}
  903. case getsubreg(reg1) of
  904. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  905. higher, it preserves the high bits, so the new value depends on
  906. reg2's previous value. In other words, it is equivalent to doing:
  907. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  908. R_SUBL:
  909. exit(getsubreg(reg2)=R_SUBL);
  910. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  911. higher, it actually does a:
  912. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  913. R_SUBH:
  914. exit(getsubreg(reg2)=R_SUBH);
  915. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  916. bits of reg2:
  917. reg2 := (reg2 and $ffff0000) or word(reg1); }
  918. R_SUBW:
  919. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  920. { a write to R_SUBD always overwrites every other subregister,
  921. because it clears the high 32 bits of R_SUBQ on x86_64 }
  922. R_SUBD,
  923. R_SUBQ:
  924. exit(true);
  925. else
  926. internalerror(2017042801);
  927. end;
  928. end;
  929. function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  930. begin
  931. if not SuperRegistersEqual(reg1,reg2) then
  932. exit(false);
  933. if getregtype(reg1)<>R_INTREGISTER then
  934. exit(true); {because SuperRegisterEqual is true}
  935. case getsubreg(reg1) of
  936. R_SUBL:
  937. exit(getsubreg(reg2)<>R_SUBH);
  938. R_SUBH:
  939. exit(getsubreg(reg2)<>R_SUBL);
  940. R_SUBW,
  941. R_SUBD,
  942. R_SUBQ:
  943. exit(true);
  944. else
  945. internalerror(2017042802);
  946. end;
  947. end;
  948. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  949. var
  950. hp1 : tai;
  951. l : TCGInt;
  952. begin
  953. result:=false;
  954. { changes the code sequence
  955. shr/sar const1, x
  956. shl const2, x
  957. to
  958. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  959. if GetNextInstruction(p, hp1) and
  960. MatchInstruction(hp1,A_SHL,[]) and
  961. (taicpu(p).oper[0]^.typ = top_const) and
  962. (taicpu(hp1).oper[0]^.typ = top_const) and
  963. (taicpu(hp1).opsize = taicpu(p).opsize) and
  964. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  965. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  966. begin
  967. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  968. not(cs_opt_size in current_settings.optimizerswitches) then
  969. begin
  970. { shr/sar const1, %reg
  971. shl const2, %reg
  972. with const1 > const2 }
  973. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  974. taicpu(hp1).opcode := A_AND;
  975. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  976. case taicpu(p).opsize Of
  977. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  978. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  979. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  980. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  981. else
  982. Internalerror(2017050703)
  983. end;
  984. end
  985. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  986. not(cs_opt_size in current_settings.optimizerswitches) then
  987. begin
  988. { shr/sar const1, %reg
  989. shl const2, %reg
  990. with const1 < const2 }
  991. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  992. taicpu(p).opcode := A_AND;
  993. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  994. case taicpu(p).opsize Of
  995. S_B: taicpu(p).loadConst(0,l Xor $ff);
  996. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  997. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  998. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  999. else
  1000. Internalerror(2017050702)
  1001. end;
  1002. end
  1003. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1004. begin
  1005. { shr/sar const1, %reg
  1006. shl const2, %reg
  1007. with const1 = const2 }
  1008. taicpu(p).opcode := A_AND;
  1009. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1010. case taicpu(p).opsize Of
  1011. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1012. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1013. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1014. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1015. else
  1016. Internalerror(2017050701)
  1017. end;
  1018. RemoveInstruction(hp1);
  1019. end;
  1020. end;
  1021. end;
  1022. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1023. var
  1024. opsize : topsize;
  1025. hp1 : tai;
  1026. tmpref : treference;
  1027. ShiftValue : Cardinal;
  1028. BaseValue : TCGInt;
  1029. begin
  1030. result:=false;
  1031. opsize:=taicpu(p).opsize;
  1032. { changes certain "imul const, %reg"'s to lea sequences }
  1033. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1034. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1035. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1036. if (taicpu(p).oper[0]^.val = 1) then
  1037. if (taicpu(p).ops = 2) then
  1038. { remove "imul $1, reg" }
  1039. begin
  1040. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1041. Result := RemoveCurrentP(p);
  1042. end
  1043. else
  1044. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1045. begin
  1046. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1047. InsertLLItem(p.previous, p.next, hp1);
  1048. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1049. p.free;
  1050. p := hp1;
  1051. end
  1052. else if ((taicpu(p).ops <= 2) or
  1053. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1054. not(cs_opt_size in current_settings.optimizerswitches) and
  1055. (not(GetNextInstruction(p, hp1)) or
  1056. not((tai(hp1).typ = ait_instruction) and
  1057. ((taicpu(hp1).opcode=A_Jcc) and
  1058. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1059. begin
  1060. {
  1061. imul X, reg1, reg2 to
  1062. lea (reg1,reg1,Y), reg2
  1063. shl ZZ,reg2
  1064. imul XX, reg1 to
  1065. lea (reg1,reg1,YY), reg1
  1066. shl ZZ,reg2
  1067. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1068. it does not exist as a separate optimization target in FPC though.
  1069. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1070. at most two zeros
  1071. }
  1072. reference_reset(tmpref,1,[]);
  1073. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1074. begin
  1075. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1076. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1077. TmpRef.base := taicpu(p).oper[1]^.reg;
  1078. TmpRef.index := taicpu(p).oper[1]^.reg;
  1079. if not(BaseValue in [3,5,9]) then
  1080. Internalerror(2018110101);
  1081. TmpRef.ScaleFactor := BaseValue-1;
  1082. if (taicpu(p).ops = 2) then
  1083. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1084. else
  1085. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1086. AsmL.InsertAfter(hp1,p);
  1087. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1088. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1089. RemoveCurrentP(p, hp1);
  1090. if ShiftValue>0 then
  1091. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1092. end;
  1093. end;
  1094. end;
  1095. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1096. var
  1097. p: taicpu;
  1098. begin
  1099. if not assigned(hp) or
  1100. (hp.typ <> ait_instruction) then
  1101. begin
  1102. Result := false;
  1103. exit;
  1104. end;
  1105. p := taicpu(hp);
  1106. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1107. with insprop[p.opcode] do
  1108. begin
  1109. case getsubreg(reg) of
  1110. R_SUBW,R_SUBD,R_SUBQ:
  1111. Result:=
  1112. RegLoadedWithNewValue(NR_CARRYFLAG,hp) and
  1113. RegLoadedWithNewValue(NR_PARITYFLAG,hp) and
  1114. RegLoadedWithNewValue(NR_AUXILIARYFLAG,hp) and
  1115. RegLoadedWithNewValue(NR_ZEROFLAG,hp) and
  1116. RegLoadedWithNewValue(NR_SIGNFLAG,hp) and
  1117. RegLoadedWithNewValue(NR_OVERFLOWFLAG,hp);
  1118. R_SUBFLAGCARRY:
  1119. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1120. R_SUBFLAGPARITY:
  1121. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1122. R_SUBFLAGAUXILIARY:
  1123. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1124. R_SUBFLAGZERO:
  1125. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1126. R_SUBFLAGSIGN:
  1127. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1128. R_SUBFLAGOVERFLOW:
  1129. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1130. R_SUBFLAGINTERRUPT:
  1131. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1132. R_SUBFLAGDIRECTION:
  1133. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1134. else
  1135. begin
  1136. writeln(getsubreg(reg));
  1137. internalerror(2017050501);
  1138. end;
  1139. end;
  1140. exit;
  1141. end;
  1142. Result :=
  1143. (((p.opcode = A_MOV) or
  1144. (p.opcode = A_MOVZX) or
  1145. (p.opcode = A_MOVSX) or
  1146. (p.opcode = A_LEA) or
  1147. (p.opcode = A_VMOVSS) or
  1148. (p.opcode = A_VMOVSD) or
  1149. (p.opcode = A_VMOVAPD) or
  1150. (p.opcode = A_VMOVAPS) or
  1151. (p.opcode = A_VMOVQ) or
  1152. (p.opcode = A_MOVSS) or
  1153. (p.opcode = A_MOVSD) or
  1154. (p.opcode = A_MOVQ) or
  1155. (p.opcode = A_MOVAPD) or
  1156. (p.opcode = A_MOVAPS) or
  1157. {$ifndef x86_64}
  1158. (p.opcode = A_LDS) or
  1159. (p.opcode = A_LES) or
  1160. {$endif not x86_64}
  1161. (p.opcode = A_LFS) or
  1162. (p.opcode = A_LGS) or
  1163. (p.opcode = A_LSS)) and
  1164. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1165. (p.oper[1]^.typ = top_reg) and
  1166. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1167. ((p.oper[0]^.typ = top_const) or
  1168. ((p.oper[0]^.typ = top_reg) and
  1169. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))) or
  1170. ((p.oper[0]^.typ = top_ref) and
  1171. not RegInRef(reg,p.oper[0]^.ref^)))) or
  1172. ((p.opcode = A_POP) and
  1173. (Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg))) or
  1174. ((p.opcode = A_IMUL) and
  1175. (p.ops=3) and
  1176. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1177. (((p.oper[1]^.typ=top_reg) and not(Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg))) or
  1178. ((p.oper[1]^.typ=top_ref) and not(RegInRef(reg,p.oper[1]^.ref^))))) or
  1179. ((((p.opcode = A_IMUL) or
  1180. (p.opcode = A_MUL)) and
  1181. (p.ops=1)) and
  1182. (((p.oper[0]^.typ=top_reg) and not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))) or
  1183. ((p.oper[0]^.typ=top_ref) and not(RegInRef(reg,p.oper[0]^.ref^)))) and
  1184. (((p.opsize=S_B) and Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg))) or
  1185. ((p.opsize=S_W) and Reg1WriteOverwritesReg2Entirely(NR_DX,reg)) or
  1186. ((p.opsize=S_L) and Reg1WriteOverwritesReg2Entirely(NR_EDX,reg))
  1187. {$ifdef x86_64}
  1188. or ((p.opsize=S_Q) and Reg1WriteOverwritesReg2Entirely(NR_RDX,reg))
  1189. {$endif x86_64}
  1190. )) or
  1191. ((p.opcode = A_CWD) and Reg1WriteOverwritesReg2Entirely(NR_DX,reg)) or
  1192. ((p.opcode = A_CDQ) and Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)) or
  1193. {$ifdef x86_64}
  1194. ((p.opcode = A_CQO) and Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)) or
  1195. {$endif x86_64}
  1196. ((p.opcode = A_CBW) and Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg))) or
  1197. {$ifndef x86_64}
  1198. ((p.opcode = A_LDS) and (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^))) or
  1199. ((p.opcode = A_LES) and (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^))) or
  1200. {$endif not x86_64}
  1201. ((p.opcode = A_LFS) and (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^))) or
  1202. ((p.opcode = A_LGS) and (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^))) or
  1203. ((p.opcode = A_LSS) and (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^))) or
  1204. {$ifndef x86_64}
  1205. ((p.opcode = A_AAM) and Reg1WriteOverwritesReg2Entirely(NR_AH,reg)) or
  1206. {$endif not x86_64}
  1207. ((p.opcode = A_LAHF) and Reg1WriteOverwritesReg2Entirely(NR_AH,reg)) or
  1208. ((p.opcode = A_LODSB) and Reg1WriteOverwritesReg2Entirely(NR_AL,reg)) or
  1209. ((p.opcode = A_LODSW) and Reg1WriteOverwritesReg2Entirely(NR_AX,reg)) or
  1210. ((p.opcode = A_LODSD) and Reg1WriteOverwritesReg2Entirely(NR_EAX,reg)) or
  1211. {$ifdef x86_64}
  1212. ((p.opcode = A_LODSQ) and Reg1WriteOverwritesReg2Entirely(NR_RAX,reg)) or
  1213. {$endif x86_64}
  1214. ((p.opcode = A_SETcc) and (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg)) or
  1215. (((p.opcode = A_FSTSW) or
  1216. (p.opcode = A_FNSTSW)) and
  1217. (p.oper[0]^.typ=top_reg) and
  1218. Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg)) or
  1219. (((p.opcode = A_SHRX) or (p.opcode = A_SHLX)) and
  1220. (p.ops=3) and
  1221. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1222. (((p.oper[1]^.typ=top_reg) and not(Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg))) or
  1223. ((p.oper[1]^.typ=top_ref) and not(RegInRef(reg,p.oper[1]^.ref^)))) and
  1224. (((p.oper[0]^.typ=top_reg) and not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))) or
  1225. ((p.oper[0]^.typ=top_ref) and not(RegInRef(reg,p.oper[0]^.ref^))))) or
  1226. (((p.opcode = A_XOR) or (p.opcode = A_SUB) or (p.opcode = A_SBB)) and
  1227. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  1228. (p.oper[0]^.reg=p.oper[1]^.reg) and
  1229. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg));
  1230. end;
  1231. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1232. var
  1233. hp2,hp3 : tai;
  1234. begin
  1235. { some x86-64 issue a NOP before the real exit code }
  1236. if MatchInstruction(p,A_NOP,[]) then
  1237. GetNextInstruction(p,p);
  1238. result:=assigned(p) and (p.typ=ait_instruction) and
  1239. ((taicpu(p).opcode = A_RET) or
  1240. ((taicpu(p).opcode=A_LEAVE) and
  1241. GetNextInstruction(p,hp2) and
  1242. MatchInstruction(hp2,A_RET,[S_NO])
  1243. ) or
  1244. (((taicpu(p).opcode=A_LEA) and
  1245. MatchOpType(taicpu(p),top_ref,top_reg) and
  1246. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1247. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1248. ) and
  1249. GetNextInstruction(p,hp2) and
  1250. MatchInstruction(hp2,A_RET,[S_NO])
  1251. ) or
  1252. ((((taicpu(p).opcode=A_MOV) and
  1253. MatchOpType(taicpu(p),top_reg,top_reg) and
  1254. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1255. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1256. ((taicpu(p).opcode=A_LEA) and
  1257. MatchOpType(taicpu(p),top_ref,top_reg) and
  1258. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1259. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1260. )
  1261. ) and
  1262. GetNextInstruction(p,hp2) and
  1263. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1264. MatchOpType(taicpu(hp2),top_reg) and
  1265. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1266. GetNextInstruction(hp2,hp3) and
  1267. MatchInstruction(hp3,A_RET,[S_NO])
  1268. )
  1269. );
  1270. end;
  1271. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1272. begin
  1273. isFoldableArithOp := False;
  1274. case hp1.opcode of
  1275. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1276. isFoldableArithOp :=
  1277. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1278. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1279. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1280. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1281. (taicpu(hp1).oper[1]^.reg = reg);
  1282. A_INC,A_DEC,A_NEG,A_NOT:
  1283. isFoldableArithOp :=
  1284. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1285. (taicpu(hp1).oper[0]^.reg = reg);
  1286. else
  1287. ;
  1288. end;
  1289. end;
  1290. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1291. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1292. var
  1293. hp2: tai;
  1294. begin
  1295. hp2 := p;
  1296. repeat
  1297. hp2 := tai(hp2.previous);
  1298. if assigned(hp2) and
  1299. (hp2.typ = ait_regalloc) and
  1300. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1301. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1302. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1303. begin
  1304. RemoveInstruction(hp2);
  1305. break;
  1306. end;
  1307. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1308. end;
  1309. begin
  1310. case current_procinfo.procdef.returndef.typ of
  1311. arraydef,recorddef,pointerdef,
  1312. stringdef,enumdef,procdef,objectdef,errordef,
  1313. filedef,setdef,procvardef,
  1314. classrefdef,forwarddef:
  1315. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1316. orddef:
  1317. if current_procinfo.procdef.returndef.size <> 0 then
  1318. begin
  1319. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1320. { for int64/qword }
  1321. if current_procinfo.procdef.returndef.size = 8 then
  1322. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1323. end;
  1324. else
  1325. ;
  1326. end;
  1327. end;
  1328. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1329. var
  1330. hp1,hp2 : tai;
  1331. begin
  1332. result:=false;
  1333. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1334. begin
  1335. { vmova* reg1,reg1
  1336. =>
  1337. <nop> }
  1338. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1339. begin
  1340. RemoveCurrentP(p);
  1341. result:=true;
  1342. exit;
  1343. end
  1344. else if GetNextInstruction(p,hp1) then
  1345. begin
  1346. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1347. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1348. begin
  1349. { vmova* reg1,reg2
  1350. vmova* reg2,reg3
  1351. dealloc reg2
  1352. =>
  1353. vmova* reg1,reg3 }
  1354. TransferUsedRegs(TmpUsedRegs);
  1355. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1356. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1357. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1358. begin
  1359. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1360. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1361. RemoveInstruction(hp1);
  1362. result:=true;
  1363. exit;
  1364. end
  1365. { special case:
  1366. vmova* reg1,<op>
  1367. vmova* <op>,reg1
  1368. =>
  1369. vmova* reg1,<op> }
  1370. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1371. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1372. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1373. ) then
  1374. begin
  1375. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1376. RemoveInstruction(hp1);
  1377. result:=true;
  1378. exit;
  1379. end
  1380. end
  1381. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1382. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1383. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1384. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1385. ) and
  1386. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1387. begin
  1388. { vmova* reg1,reg2
  1389. vmovs* reg2,<op>
  1390. dealloc reg2
  1391. =>
  1392. vmovs* reg1,reg3 }
  1393. TransferUsedRegs(TmpUsedRegs);
  1394. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1395. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1396. begin
  1397. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1398. taicpu(p).opcode:=taicpu(hp1).opcode;
  1399. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1400. RemoveInstruction(hp1);
  1401. result:=true;
  1402. exit;
  1403. end
  1404. end;
  1405. end;
  1406. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1407. begin
  1408. if MatchInstruction(hp1,[A_VFMADDPD,
  1409. A_VFMADD132PD,
  1410. A_VFMADD132PS,
  1411. A_VFMADD132SD,
  1412. A_VFMADD132SS,
  1413. A_VFMADD213PD,
  1414. A_VFMADD213PS,
  1415. A_VFMADD213SD,
  1416. A_VFMADD213SS,
  1417. A_VFMADD231PD,
  1418. A_VFMADD231PS,
  1419. A_VFMADD231SD,
  1420. A_VFMADD231SS,
  1421. A_VFMADDSUB132PD,
  1422. A_VFMADDSUB132PS,
  1423. A_VFMADDSUB213PD,
  1424. A_VFMADDSUB213PS,
  1425. A_VFMADDSUB231PD,
  1426. A_VFMADDSUB231PS,
  1427. A_VFMSUB132PD,
  1428. A_VFMSUB132PS,
  1429. A_VFMSUB132SD,
  1430. A_VFMSUB132SS,
  1431. A_VFMSUB213PD,
  1432. A_VFMSUB213PS,
  1433. A_VFMSUB213SD,
  1434. A_VFMSUB213SS,
  1435. A_VFMSUB231PD,
  1436. A_VFMSUB231PS,
  1437. A_VFMSUB231SD,
  1438. A_VFMSUB231SS,
  1439. A_VFMSUBADD132PD,
  1440. A_VFMSUBADD132PS,
  1441. A_VFMSUBADD213PD,
  1442. A_VFMSUBADD213PS,
  1443. A_VFMSUBADD231PD,
  1444. A_VFMSUBADD231PS,
  1445. A_VFNMADD132PD,
  1446. A_VFNMADD132PS,
  1447. A_VFNMADD132SD,
  1448. A_VFNMADD132SS,
  1449. A_VFNMADD213PD,
  1450. A_VFNMADD213PS,
  1451. A_VFNMADD213SD,
  1452. A_VFNMADD213SS,
  1453. A_VFNMADD231PD,
  1454. A_VFNMADD231PS,
  1455. A_VFNMADD231SD,
  1456. A_VFNMADD231SS,
  1457. A_VFNMSUB132PD,
  1458. A_VFNMSUB132PS,
  1459. A_VFNMSUB132SD,
  1460. A_VFNMSUB132SS,
  1461. A_VFNMSUB213PD,
  1462. A_VFNMSUB213PS,
  1463. A_VFNMSUB213SD,
  1464. A_VFNMSUB213SS,
  1465. A_VFNMSUB231PD,
  1466. A_VFNMSUB231PS,
  1467. A_VFNMSUB231SD,
  1468. A_VFNMSUB231SS],[S_NO]) and
  1469. { we mix single and double opperations here because we assume that the compiler
  1470. generates vmovapd only after double operations and vmovaps only after single operations }
  1471. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1472. GetNextInstruction(hp1,hp2) and
  1473. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1474. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1475. begin
  1476. TransferUsedRegs(TmpUsedRegs);
  1477. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1478. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1479. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1480. begin
  1481. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1482. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1483. RemoveInstruction(hp2);
  1484. end;
  1485. end
  1486. else if (hp1.typ = ait_instruction) and
  1487. GetNextInstruction(hp1, hp2) and
  1488. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1489. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1490. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1491. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1492. (((taicpu(p).opcode=A_MOVAPS) and
  1493. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1494. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1495. ((taicpu(p).opcode=A_MOVAPD) and
  1496. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1497. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1498. ) then
  1499. { change
  1500. movapX reg,reg2
  1501. addsX/subsX/... reg3, reg2
  1502. movapX reg2,reg
  1503. to
  1504. addsX/subsX/... reg3,reg
  1505. }
  1506. begin
  1507. TransferUsedRegs(TmpUsedRegs);
  1508. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1509. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1510. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1511. begin
  1512. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1513. debug_op2str(taicpu(p).opcode)+' '+
  1514. debug_op2str(taicpu(hp1).opcode)+' '+
  1515. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1516. { we cannot eliminate the first move if
  1517. the operations uses the same register for source and dest }
  1518. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1519. RemoveCurrentP(p, nil);
  1520. p:=hp1;
  1521. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1522. RemoveInstruction(hp2);
  1523. result:=true;
  1524. end;
  1525. end;
  1526. end;
  1527. end;
  1528. end;
  1529. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1530. var
  1531. hp1 : tai;
  1532. begin
  1533. result:=false;
  1534. { replace
  1535. V<Op>X %mreg1,%mreg2,%mreg3
  1536. VMovX %mreg3,%mreg4
  1537. dealloc %mreg3
  1538. by
  1539. V<Op>X %mreg1,%mreg2,%mreg4
  1540. ?
  1541. }
  1542. if GetNextInstruction(p,hp1) and
  1543. { we mix single and double operations here because we assume that the compiler
  1544. generates vmovapd only after double operations and vmovaps only after single operations }
  1545. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1546. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1547. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1548. begin
  1549. TransferUsedRegs(TmpUsedRegs);
  1550. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1551. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1552. begin
  1553. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1554. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1555. RemoveInstruction(hp1);
  1556. result:=true;
  1557. end;
  1558. end;
  1559. end;
  1560. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1561. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1562. begin
  1563. Result := False;
  1564. { For safety reasons, only check for exact register matches }
  1565. { Check base register }
  1566. if (ref.base = AOldReg) then
  1567. begin
  1568. ref.base := ANewReg;
  1569. Result := True;
  1570. end;
  1571. { Check index register }
  1572. if (ref.index = AOldReg) then
  1573. begin
  1574. ref.index := ANewReg;
  1575. Result := True;
  1576. end;
  1577. end;
  1578. { Replaces all references to AOldReg in an operand to ANewReg }
  1579. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  1580. var
  1581. OldSupReg, NewSupReg: TSuperRegister;
  1582. OldSubReg, NewSubReg: TSubRegister;
  1583. OldRegType: TRegisterType;
  1584. ThisOper: POper;
  1585. begin
  1586. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  1587. Result := False;
  1588. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  1589. InternalError(2020011801);
  1590. OldSupReg := getsupreg(AOldReg);
  1591. OldSubReg := getsubreg(AOldReg);
  1592. OldRegType := getregtype(AOldReg);
  1593. NewSupReg := getsupreg(ANewReg);
  1594. NewSubReg := getsubreg(ANewReg);
  1595. if OldRegType <> getregtype(ANewReg) then
  1596. InternalError(2020011802);
  1597. if OldSubReg <> NewSubReg then
  1598. InternalError(2020011803);
  1599. case ThisOper^.typ of
  1600. top_reg:
  1601. if (
  1602. (ThisOper^.reg = AOldReg) or
  1603. (
  1604. (OldRegType = R_INTREGISTER) and
  1605. (getsupreg(ThisOper^.reg) = OldSupReg) and
  1606. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  1607. (
  1608. (getsubreg(ThisOper^.reg) <= OldSubReg)
  1609. {$ifndef x86_64}
  1610. and (
  1611. { Under i386 and i8086, ESI, EDI, EBP and ESP
  1612. don't have an 8-bit representation }
  1613. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  1614. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  1615. )
  1616. {$endif x86_64}
  1617. )
  1618. )
  1619. ) then
  1620. begin
  1621. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  1622. Result := True;
  1623. end;
  1624. top_ref:
  1625. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  1626. Result := True;
  1627. else
  1628. ;
  1629. end;
  1630. end;
  1631. { Replaces all references to AOldReg in an instruction to ANewReg }
  1632. function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  1633. const
  1634. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  1635. var
  1636. OperIdx: Integer;
  1637. begin
  1638. Result := False;
  1639. for OperIdx := 0 to p.ops - 1 do
  1640. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) and
  1641. { The shift and rotate instructions can only use CL }
  1642. not (
  1643. (OperIdx = 0) and
  1644. { This second condition just helps to avoid unnecessarily
  1645. calling MatchInstruction for 10 different opcodes }
  1646. (p.oper[0]^.reg = NR_CL) and
  1647. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  1648. ) then
  1649. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  1650. end;
  1651. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean; inline;
  1652. begin
  1653. Result :=
  1654. (ref^.index = NR_NO) and
  1655. (
  1656. {$ifdef x86_64}
  1657. (
  1658. (ref^.base = NR_RIP) and
  1659. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  1660. ) or
  1661. {$endif x86_64}
  1662. (ref^.base = NR_STACK_POINTER_REG) or
  1663. (ref^.base = current_procinfo.framepointer)
  1664. );
  1665. end;
  1666. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  1667. var
  1668. l: asizeint;
  1669. begin
  1670. Result := False;
  1671. { Should have been checked previously }
  1672. if p.opcode <> A_LEA then
  1673. InternalError(2020072501);
  1674. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  1675. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  1676. not(cs_opt_size in current_settings.optimizerswitches) then
  1677. exit;
  1678. with p.oper[0]^.ref^ do
  1679. begin
  1680. if (base <> p.oper[1]^.reg) or
  1681. (index <> NR_NO) or
  1682. assigned(symbol) then
  1683. exit;
  1684. l:=offset;
  1685. if (l=1) and UseIncDec then
  1686. begin
  1687. p.opcode:=A_INC;
  1688. p.loadreg(0,p.oper[1]^.reg);
  1689. p.ops:=1;
  1690. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  1691. end
  1692. else if (l=-1) and UseIncDec then
  1693. begin
  1694. p.opcode:=A_DEC;
  1695. p.loadreg(0,p.oper[1]^.reg);
  1696. p.ops:=1;
  1697. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  1698. end
  1699. else
  1700. begin
  1701. if (l<0) and (l<>-2147483648) then
  1702. begin
  1703. p.opcode:=A_SUB;
  1704. p.loadConst(0,-l);
  1705. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  1706. end
  1707. else
  1708. begin
  1709. p.opcode:=A_ADD;
  1710. p.loadConst(0,l);
  1711. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  1712. end;
  1713. end;
  1714. end;
  1715. Result := True;
  1716. end;
  1717. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  1718. var
  1719. CurrentReg, ReplaceReg: TRegister;
  1720. begin
  1721. Result := False;
  1722. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  1723. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  1724. case hp.opcode of
  1725. A_FSTSW, A_FNSTSW,
  1726. A_IN, A_INS, A_OUT, A_OUTS,
  1727. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  1728. { These routines have explicit operands, but they are restricted in
  1729. what they can be (e.g. IN and OUT can only read from AL, AX or
  1730. EAX. }
  1731. Exit;
  1732. A_IMUL:
  1733. begin
  1734. { The 1-operand version writes to implicit registers
  1735. The 2-operand version reads from the first operator, and reads
  1736. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  1737. the 3-operand version reads from a register that it doesn't write to
  1738. }
  1739. case hp.ops of
  1740. 1:
  1741. if (
  1742. (
  1743. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  1744. ) or
  1745. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  1746. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  1747. begin
  1748. Result := True;
  1749. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  1750. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1751. end;
  1752. 2:
  1753. { Only modify the first parameter }
  1754. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  1755. begin
  1756. Result := True;
  1757. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  1758. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1759. end;
  1760. 3:
  1761. { Only modify the second parameter }
  1762. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  1763. begin
  1764. Result := True;
  1765. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  1766. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1767. end;
  1768. else
  1769. InternalError(2020012901);
  1770. end;
  1771. end;
  1772. else
  1773. if (hp.ops > 0) and
  1774. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  1775. begin
  1776. Result := True;
  1777. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  1778. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1779. end;
  1780. end;
  1781. end;
  1782. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  1783. var
  1784. hp1, hp2, hp3: tai;
  1785. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  1786. begin
  1787. if taicpu(hp1).opcode = signed_movop then
  1788. begin
  1789. if taicpu(p).oper[0]^.val > max_value shr 1 then
  1790. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  1791. end
  1792. else
  1793. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  1794. end;
  1795. var
  1796. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  1797. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  1798. NewSize: topsize;
  1799. CurrentReg: TRegister;
  1800. begin
  1801. Result:=false;
  1802. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  1803. { remove mov reg1,reg1? }
  1804. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  1805. then
  1806. begin
  1807. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  1808. { take care of the register (de)allocs following p }
  1809. RemoveCurrentP(p, hp1);
  1810. Result:=true;
  1811. exit;
  1812. end;
  1813. { All the next optimisations require a next instruction }
  1814. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  1815. Exit;
  1816. { Look for:
  1817. mov %reg1,%reg2
  1818. ??? %reg2,r/m
  1819. Change to:
  1820. mov %reg1,%reg2
  1821. ??? %reg1,r/m
  1822. }
  1823. if MatchOpType(taicpu(p), top_reg, top_reg) then
  1824. begin
  1825. CurrentReg := taicpu(p).oper[1]^.reg;
  1826. if RegReadByInstruction(CurrentReg, hp1) and
  1827. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  1828. begin
  1829. TransferUsedRegs(TmpUsedRegs);
  1830. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  1831. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  1832. { Just in case something didn't get modified (e.g. an
  1833. implicit register) }
  1834. not RegReadByInstruction(CurrentReg, hp1) then
  1835. begin
  1836. { We can remove the original MOV }
  1837. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  1838. RemoveCurrentp(p, hp1);
  1839. { UsedRegs got updated by RemoveCurrentp }
  1840. Result := True;
  1841. Exit;
  1842. end;
  1843. { If we know a MOV instruction has become a null operation, we might as well
  1844. get rid of it now to save time. }
  1845. if (taicpu(hp1).opcode = A_MOV) and
  1846. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1847. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  1848. { Just being a register is enough to confirm it's a null operation }
  1849. (taicpu(hp1).oper[0]^.typ = top_reg) then
  1850. begin
  1851. Result := True;
  1852. { Speed-up to reduce a pipeline stall... if we had something like...
  1853. movl %eax,%edx
  1854. movw %dx,%ax
  1855. ... the second instruction would change to movw %ax,%ax, but
  1856. given that it is now %ax that's active rather than %eax,
  1857. penalties might occur due to a partial register write, so instead,
  1858. change it to a MOVZX instruction when optimising for speed.
  1859. }
  1860. if not (cs_opt_size in current_settings.optimizerswitches) and
  1861. IsMOVZXAcceptable and
  1862. (taicpu(hp1).opsize < taicpu(p).opsize)
  1863. {$ifdef x86_64}
  1864. { operations already implicitly set the upper 64 bits to zero }
  1865. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  1866. {$endif x86_64}
  1867. then
  1868. begin
  1869. CurrentReg := taicpu(hp1).oper[1]^.reg;
  1870. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  1871. case taicpu(p).opsize of
  1872. S_W:
  1873. if taicpu(hp1).opsize = S_B then
  1874. taicpu(hp1).opsize := S_BL
  1875. else
  1876. InternalError(2020012911);
  1877. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  1878. case taicpu(hp1).opsize of
  1879. S_B:
  1880. taicpu(hp1).opsize := S_BL;
  1881. S_W:
  1882. taicpu(hp1).opsize := S_WL;
  1883. else
  1884. InternalError(2020012912);
  1885. end;
  1886. else
  1887. InternalError(2020012910);
  1888. end;
  1889. taicpu(hp1).opcode := A_MOVZX;
  1890. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  1891. end
  1892. else
  1893. begin
  1894. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  1895. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  1896. RemoveInstruction(hp1);
  1897. { The instruction after what was hp1 is now the immediate next instruction,
  1898. so we can continue to make optimisations if it's present }
  1899. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  1900. Exit;
  1901. hp1 := hp2;
  1902. end;
  1903. end;
  1904. end;
  1905. end;
  1906. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  1907. overwrites the original destination register. e.g.
  1908. movl ###,%reg2d
  1909. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  1910. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  1911. }
  1912. if (taicpu(p).oper[1]^.typ = top_reg) and
  1913. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  1914. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1915. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  1916. begin
  1917. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  1918. begin
  1919. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  1920. case taicpu(p).oper[0]^.typ of
  1921. top_const:
  1922. { We have something like:
  1923. movb $x, %regb
  1924. movzbl %regb,%regd
  1925. Change to:
  1926. movl $x, %regd
  1927. }
  1928. begin
  1929. case taicpu(hp1).opsize of
  1930. S_BW:
  1931. begin
  1932. convert_mov_value(A_MOVSX, $FF);
  1933. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  1934. taicpu(p).opsize := S_W;
  1935. end;
  1936. S_BL:
  1937. begin
  1938. convert_mov_value(A_MOVSX, $FF);
  1939. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  1940. taicpu(p).opsize := S_L;
  1941. end;
  1942. S_WL:
  1943. begin
  1944. convert_mov_value(A_MOVSX, $FFFF);
  1945. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  1946. taicpu(p).opsize := S_L;
  1947. end;
  1948. {$ifdef x86_64}
  1949. S_BQ:
  1950. begin
  1951. convert_mov_value(A_MOVSX, $FF);
  1952. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  1953. taicpu(p).opsize := S_Q;
  1954. end;
  1955. S_WQ:
  1956. begin
  1957. convert_mov_value(A_MOVSX, $FFFF);
  1958. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  1959. taicpu(p).opsize := S_Q;
  1960. end;
  1961. S_LQ:
  1962. begin
  1963. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  1964. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  1965. taicpu(p).opsize := S_Q;
  1966. end;
  1967. {$endif x86_64}
  1968. else
  1969. { If hp1 was a MOV instruction, it should have been
  1970. optimised already }
  1971. InternalError(2020021001);
  1972. end;
  1973. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  1974. RemoveInstruction(hp1);
  1975. Result := True;
  1976. Exit;
  1977. end;
  1978. top_ref:
  1979. { We have something like:
  1980. movb mem, %regb
  1981. movzbl %regb,%regd
  1982. Change to:
  1983. movzbl mem, %regd
  1984. }
  1985. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  1986. begin
  1987. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  1988. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  1989. RemoveCurrentP(p, hp1);
  1990. Result:=True;
  1991. Exit;
  1992. end;
  1993. else
  1994. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  1995. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  1996. Exit;
  1997. end;
  1998. end
  1999. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2000. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2001. optimised }
  2002. else
  2003. begin
  2004. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2005. RemoveCurrentP(p, hp1);
  2006. Result := True;
  2007. Exit;
  2008. end;
  2009. end;
  2010. if (taicpu(hp1).opcode = A_AND) and
  2011. (taicpu(p).oper[1]^.typ = top_reg) and
  2012. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2013. begin
  2014. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2015. begin
  2016. case taicpu(p).opsize of
  2017. S_L:
  2018. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2019. begin
  2020. { Optimize out:
  2021. mov x, %reg
  2022. and ffffffffh, %reg
  2023. }
  2024. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2025. RemoveInstruction(hp1);
  2026. Result:=true;
  2027. exit;
  2028. end;
  2029. S_Q: { TODO: Confirm if this is even possible }
  2030. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2031. begin
  2032. { Optimize out:
  2033. mov x, %reg
  2034. and ffffffffffffffffh, %reg
  2035. }
  2036. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2037. RemoveInstruction(hp1);
  2038. Result:=true;
  2039. exit;
  2040. end;
  2041. else
  2042. ;
  2043. end;
  2044. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2045. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2046. GetNextInstruction(hp1,hp2) and
  2047. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2048. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2049. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) and
  2050. GetNextInstruction(hp2,hp3) and
  2051. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2052. (taicpu(hp3).condition in [C_E,C_NE]) then
  2053. begin
  2054. TransferUsedRegs(TmpUsedRegs);
  2055. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2056. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2057. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2058. begin
  2059. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2060. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2061. taicpu(hp1).opcode:=A_TEST;
  2062. RemoveInstruction(hp2);
  2063. RemoveCurrentP(p, hp1);
  2064. Result:=true;
  2065. exit;
  2066. end;
  2067. end;
  2068. end
  2069. else if IsMOVZXAcceptable and
  2070. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2071. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2072. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2073. then
  2074. begin
  2075. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2076. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2077. case taicpu(p).opsize of
  2078. S_B:
  2079. if (taicpu(hp1).oper[0]^.val = $ff) then
  2080. begin
  2081. { Convert:
  2082. movb x, %regl movb x, %regl
  2083. andw ffh, %regw andl ffh, %regd
  2084. To:
  2085. movzbw x, %regd movzbl x, %regd
  2086. (Identical registers, just different sizes)
  2087. }
  2088. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2089. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2090. case taicpu(hp1).opsize of
  2091. S_W: NewSize := S_BW;
  2092. S_L: NewSize := S_BL;
  2093. {$ifdef x86_64}
  2094. S_Q: NewSize := S_BQ;
  2095. {$endif x86_64}
  2096. else
  2097. InternalError(2018011510);
  2098. end;
  2099. end
  2100. else
  2101. NewSize := S_NO;
  2102. S_W:
  2103. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2104. begin
  2105. { Convert:
  2106. movw x, %regw
  2107. andl ffffh, %regd
  2108. To:
  2109. movzwl x, %regd
  2110. (Identical registers, just different sizes)
  2111. }
  2112. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2113. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2114. case taicpu(hp1).opsize of
  2115. S_L: NewSize := S_WL;
  2116. {$ifdef x86_64}
  2117. S_Q: NewSize := S_WQ;
  2118. {$endif x86_64}
  2119. else
  2120. InternalError(2018011511);
  2121. end;
  2122. end
  2123. else
  2124. NewSize := S_NO;
  2125. else
  2126. NewSize := S_NO;
  2127. end;
  2128. if NewSize <> S_NO then
  2129. begin
  2130. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2131. { The actual optimization }
  2132. taicpu(p).opcode := A_MOVZX;
  2133. taicpu(p).changeopsize(NewSize);
  2134. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2135. { Safeguard if "and" is followed by a conditional command }
  2136. TransferUsedRegs(TmpUsedRegs);
  2137. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2138. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2139. begin
  2140. { At this point, the "and" command is effectively equivalent to
  2141. "test %reg,%reg". This will be handled separately by the
  2142. Peephole Optimizer. [Kit] }
  2143. DebugMsg(SPeepholeOptimization + PreMessage +
  2144. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2145. end
  2146. else
  2147. begin
  2148. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2149. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2150. RemoveInstruction(hp1);
  2151. end;
  2152. Result := True;
  2153. Exit;
  2154. end;
  2155. end;
  2156. end;
  2157. { Next instruction is also a MOV ? }
  2158. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2159. begin
  2160. if (taicpu(p).oper[1]^.typ = top_reg) and
  2161. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2162. begin
  2163. CurrentReg := taicpu(p).oper[1]^.reg;
  2164. TransferUsedRegs(TmpUsedRegs);
  2165. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2166. { we have
  2167. mov x, %treg
  2168. mov %treg, y
  2169. }
  2170. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2171. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2172. { we've got
  2173. mov x, %treg
  2174. mov %treg, y
  2175. with %treg is not used after }
  2176. case taicpu(p).oper[0]^.typ Of
  2177. { top_reg is covered by DeepMOVOpt }
  2178. top_const:
  2179. begin
  2180. { change
  2181. mov const, %treg
  2182. mov %treg, y
  2183. to
  2184. mov const, y
  2185. }
  2186. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2187. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2188. begin
  2189. if taicpu(hp1).oper[1]^.typ=top_reg then
  2190. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2191. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2192. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2193. RemoveInstruction(hp1);
  2194. Result:=true;
  2195. Exit;
  2196. end;
  2197. end;
  2198. top_ref:
  2199. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2200. begin
  2201. { change
  2202. mov mem, %treg
  2203. mov %treg, %reg
  2204. to
  2205. mov mem, %reg"
  2206. }
  2207. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2208. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2209. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2210. RemoveInstruction(hp1);
  2211. Result:=true;
  2212. Exit;
  2213. end;
  2214. else
  2215. ;
  2216. end
  2217. else
  2218. { %treg is used afterwards, but all eventualities
  2219. other than the first MOV instruction being a constant
  2220. are covered by DeepMOVOpt, so only check for that }
  2221. if (taicpu(p).oper[0]^.typ = top_const) and
  2222. (
  2223. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  2224. not (cs_opt_size in current_settings.optimizerswitches) or
  2225. (taicpu(hp1).opsize = S_B)
  2226. ) and
  2227. (
  2228. (taicpu(hp1).oper[1]^.typ = top_reg) or
  2229. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  2230. ) then
  2231. begin
  2232. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  2233. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  2234. end;
  2235. end;
  2236. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  2237. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  2238. { mov reg1, mem1 or mov mem1, reg1
  2239. mov mem2, reg2 mov reg2, mem2}
  2240. begin
  2241. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  2242. { mov reg1, mem1 or mov mem1, reg1
  2243. mov mem2, reg1 mov reg2, mem1}
  2244. begin
  2245. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2246. { Removes the second statement from
  2247. mov reg1, mem1/reg2
  2248. mov mem1/reg2, reg1 }
  2249. begin
  2250. if taicpu(p).oper[0]^.typ=top_reg then
  2251. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2252. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  2253. RemoveInstruction(hp1);
  2254. Result:=true;
  2255. exit;
  2256. end
  2257. else
  2258. begin
  2259. TransferUsedRegs(TmpUsedRegs);
  2260. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2261. if (taicpu(p).oper[1]^.typ = top_ref) and
  2262. { mov reg1, mem1
  2263. mov mem2, reg1 }
  2264. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  2265. GetNextInstruction(hp1, hp2) and
  2266. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  2267. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  2268. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  2269. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  2270. { change to
  2271. mov reg1, mem1 mov reg1, mem1
  2272. mov mem2, reg1 cmp reg1, mem2
  2273. cmp mem1, reg1
  2274. }
  2275. begin
  2276. RemoveInstruction(hp2);
  2277. taicpu(hp1).opcode := A_CMP;
  2278. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  2279. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2280. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2281. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  2282. end;
  2283. end;
  2284. end
  2285. else if (taicpu(p).oper[1]^.typ=top_ref) and
  2286. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2287. begin
  2288. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2289. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2290. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  2291. end
  2292. else
  2293. begin
  2294. TransferUsedRegs(TmpUsedRegs);
  2295. if GetNextInstruction(hp1, hp2) and
  2296. MatchOpType(taicpu(p),top_ref,top_reg) and
  2297. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  2298. (taicpu(hp1).oper[1]^.typ = top_ref) and
  2299. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  2300. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  2301. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  2302. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  2303. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  2304. { mov mem1, %reg1
  2305. mov %reg1, mem2
  2306. mov mem2, reg2
  2307. to:
  2308. mov mem1, reg2
  2309. mov reg2, mem2}
  2310. begin
  2311. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  2312. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  2313. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  2314. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  2315. RemoveInstruction(hp2);
  2316. end
  2317. {$ifdef i386}
  2318. { this is enabled for i386 only, as the rules to create the reg sets below
  2319. are too complicated for x86-64, so this makes this code too error prone
  2320. on x86-64
  2321. }
  2322. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  2323. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  2324. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  2325. { mov mem1, reg1 mov mem1, reg1
  2326. mov reg1, mem2 mov reg1, mem2
  2327. mov mem2, reg2 mov mem2, reg1
  2328. to: to:
  2329. mov mem1, reg1 mov mem1, reg1
  2330. mov mem1, reg2 mov reg1, mem2
  2331. mov reg1, mem2
  2332. or (if mem1 depends on reg1
  2333. and/or if mem2 depends on reg2)
  2334. to:
  2335. mov mem1, reg1
  2336. mov reg1, mem2
  2337. mov reg1, reg2
  2338. }
  2339. begin
  2340. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  2341. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  2342. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  2343. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  2344. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2345. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  2346. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2347. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  2348. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  2349. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2350. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  2351. end
  2352. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  2353. begin
  2354. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  2355. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2356. end
  2357. else
  2358. begin
  2359. RemoveInstruction(hp2);
  2360. end
  2361. {$endif i386}
  2362. ;
  2363. end;
  2364. end
  2365. { movl [mem1],reg1
  2366. movl [mem1],reg2
  2367. to
  2368. movl [mem1],reg1
  2369. movl reg1,reg2
  2370. }
  2371. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  2372. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2373. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2374. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2375. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2376. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2377. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2378. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2379. begin
  2380. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2381. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2382. end;
  2383. { movl const1,[mem1]
  2384. movl [mem1],reg1
  2385. to
  2386. movl const1,reg1
  2387. movl reg1,[mem1]
  2388. }
  2389. if MatchOpType(Taicpu(p),top_const,top_ref) and
  2390. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  2391. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2392. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  2393. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  2394. begin
  2395. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2396. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  2397. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  2398. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  2399. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  2400. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  2401. Result:=true;
  2402. exit;
  2403. end;
  2404. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  2405. end;
  2406. { search further than the next instruction for a mov }
  2407. if
  2408. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  2409. (taicpu(p).oper[1]^.typ = top_reg) and
  2410. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  2411. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  2412. begin
  2413. { we work with hp2 here, so hp1 can be still used later on when
  2414. checking for GetNextInstruction_p }
  2415. hp3 := hp1;
  2416. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  2417. CrossJump := False;
  2418. while GetNextInstructionUsingRegCond(hp3,hp2,taicpu(p).oper[1]^.reg,CrossJump) and
  2419. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  2420. (hp2.typ=ait_instruction) do
  2421. begin
  2422. case taicpu(hp2).opcode of
  2423. A_MOV:
  2424. if MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^.reg) and
  2425. ((taicpu(p).oper[0]^.typ=top_const) or
  2426. ((taicpu(p).oper[0]^.typ=top_reg) and
  2427. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  2428. )
  2429. ) then
  2430. begin
  2431. { we have
  2432. mov x, %treg
  2433. mov %treg, y
  2434. }
  2435. TransferUsedRegs(TmpUsedRegs);
  2436. TmpUsedRegs[R_INTREGISTER].Update(tai(p.Next));
  2437. { We don't need to call UpdateUsedRegs for every instruction between
  2438. p and hp2 because the register we're concerned about will not
  2439. become deallocated (otherwise GetNextInstructionUsingReg would
  2440. have stopped at an earlier instruction). [Kit] }
  2441. TempRegUsed :=
  2442. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  2443. RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) or
  2444. RegReadByInstruction(taicpu(p).oper[1]^.reg, hp1);
  2445. case taicpu(p).oper[0]^.typ Of
  2446. top_reg:
  2447. begin
  2448. { change
  2449. mov %reg, %treg
  2450. mov %treg, y
  2451. to
  2452. mov %reg, y
  2453. }
  2454. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  2455. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  2456. if taicpu(hp2).oper[1]^.reg = CurrentReg then
  2457. begin
  2458. { %reg = y - remove hp2 completely (doing it here instead of relying on
  2459. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  2460. if TempRegUsed then
  2461. begin
  2462. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  2463. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  2464. { Set the start of the next GetNextInstructionUsingRegCond search
  2465. to start at the entry right before hp2 (which is about to be removed) }
  2466. hp3 := tai(hp2.Previous);
  2467. RemoveInstruction(hp2);
  2468. { See if there's more we can optimise }
  2469. Continue;
  2470. end
  2471. else
  2472. begin
  2473. RemoveInstruction(hp2);
  2474. { We can remove the original MOV too }
  2475. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  2476. RemoveCurrentP(p, hp1);
  2477. Result:=true;
  2478. Exit;
  2479. end;
  2480. end
  2481. else
  2482. begin
  2483. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  2484. taicpu(hp2).loadReg(0, CurrentReg);
  2485. if TempRegUsed then
  2486. begin
  2487. { Don't remove the first instruction if the temporary register is in use }
  2488. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  2489. { No need to set Result to True. If there's another instruction later on
  2490. that can be optimised, it will be detected when the main Pass 1 loop
  2491. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  2492. end
  2493. else
  2494. begin
  2495. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  2496. RemoveCurrentP(p, hp1);
  2497. Result:=true;
  2498. Exit;
  2499. end;
  2500. end;
  2501. end;
  2502. top_const:
  2503. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  2504. begin
  2505. { change
  2506. mov const, %treg
  2507. mov %treg, y
  2508. to
  2509. mov const, y
  2510. }
  2511. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  2512. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2513. begin
  2514. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  2515. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  2516. if TempRegUsed then
  2517. begin
  2518. { Don't remove the first instruction if the temporary register is in use }
  2519. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  2520. { No need to set Result to True. If there's another instruction later on
  2521. that can be optimised, it will be detected when the main Pass 1 loop
  2522. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  2523. end
  2524. else
  2525. begin
  2526. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  2527. RemoveCurrentP(p, hp1);
  2528. Result:=true;
  2529. Exit;
  2530. end;
  2531. end;
  2532. end;
  2533. else
  2534. Internalerror(2019103001);
  2535. end;
  2536. end;
  2537. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  2538. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  2539. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  2540. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2541. begin
  2542. {
  2543. Change from:
  2544. mov ###, %reg
  2545. ...
  2546. movs/z %reg,%reg (Same register, just different sizes)
  2547. To:
  2548. movs/z ###, %reg (Longer version)
  2549. ...
  2550. (remove)
  2551. }
  2552. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  2553. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  2554. { Keep the first instruction as mov if ### is a constant }
  2555. if taicpu(p).oper[0]^.typ = top_const then
  2556. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  2557. else
  2558. begin
  2559. taicpu(p).opcode := taicpu(hp2).opcode;
  2560. taicpu(p).opsize := taicpu(hp2).opsize;
  2561. end;
  2562. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  2563. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  2564. RemoveInstruction(hp2);
  2565. Result := True;
  2566. Exit;
  2567. end;
  2568. else
  2569. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2570. begin
  2571. CurrentReg := taicpu(p).oper[1]^.reg;
  2572. TransferUsedRegs(TmpUsedRegs);
  2573. TmpUsedRegs[R_INTREGISTER].Update(tai(p.Next));
  2574. if
  2575. not RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) and
  2576. not RegModifiedBetween(taicpu(p).oper[0]^.reg, hp1, hp2) and
  2577. { if we replace taicpu(p).oper[1]^.reg by taicpu(p).oper[0]^.reg,
  2578. taicpu(p).oper[1]^.reg might not be modified in between }
  2579. not RegModifiedBetween(CurrentReg, p, hp2) and
  2580. DeepMovOpt(taicpu(p), taicpu(hp2)) then
  2581. begin
  2582. { Just in case something didn't get modified (e.g. an
  2583. implicit register) }
  2584. if not RegReadByInstruction(CurrentReg, hp2) and
  2585. { If a conditional jump was crossed, do not delete
  2586. the original MOV no matter what }
  2587. not CrossJump then
  2588. begin
  2589. TransferUsedRegs(TmpUsedRegs);
  2590. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2591. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2592. if not RegUsedAfterInstruction(CurrentReg, hp2, TmpUsedRegs) then
  2593. begin
  2594. { We can remove the original MOV }
  2595. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  2596. RemoveCurrentp(p, hp1);
  2597. Result := True;
  2598. Exit;
  2599. end
  2600. else
  2601. begin
  2602. { See if there's more we can optimise }
  2603. hp3 := hp2;
  2604. Continue;
  2605. end;
  2606. end;
  2607. end;
  2608. end;
  2609. end;
  2610. { Break out of the while loop under normal circumstances }
  2611. Break;
  2612. end;
  2613. end;
  2614. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  2615. (taicpu(p).oper[1]^.typ = top_reg) and
  2616. (taicpu(p).opsize = S_L) and
  2617. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  2618. (taicpu(hp2).opcode = A_AND) and
  2619. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  2620. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2621. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  2622. ) then
  2623. begin
  2624. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  2625. begin
  2626. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  2627. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  2628. begin
  2629. { Optimize out:
  2630. mov x, %reg
  2631. and ffffffffh, %reg
  2632. }
  2633. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  2634. RemoveInstruction(hp2);
  2635. Result:=true;
  2636. exit;
  2637. end;
  2638. end;
  2639. end;
  2640. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  2641. x >= RetOffset) as it doesn't do anything (it writes either to a
  2642. parameter or to the temporary storage room for the function
  2643. result)
  2644. }
  2645. if IsExitCode(hp1) and
  2646. (taicpu(p).oper[1]^.typ = top_ref) and
  2647. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  2648. (
  2649. (
  2650. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  2651. not (
  2652. assigned(current_procinfo.procdef.funcretsym) and
  2653. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  2654. )
  2655. ) or
  2656. { Also discard writes to the stack that are below the base pointer,
  2657. as this is temporary storage rather than a function result on the
  2658. stack, say. }
  2659. (
  2660. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  2661. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  2662. )
  2663. ) then
  2664. begin
  2665. RemoveCurrentp(p, hp1);
  2666. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  2667. RemoveLastDeallocForFuncRes(p);
  2668. Result:=true;
  2669. exit;
  2670. end;
  2671. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  2672. begin
  2673. if MatchOpType(taicpu(p),top_reg,top_ref) and
  2674. (taicpu(hp1).oper[1]^.typ = top_ref) and
  2675. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  2676. begin
  2677. { change
  2678. mov reg1, mem1
  2679. test/cmp x, mem1
  2680. to
  2681. mov reg1, mem1
  2682. test/cmp x, reg1
  2683. }
  2684. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  2685. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  2686. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2687. Result := True;
  2688. Exit;
  2689. end;
  2690. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2691. { The x86 assemblers have difficulty comparing values against absolute addresses }
  2692. (taicpu(p).oper[0]^.ref^.refaddr in [addr_no, addr_pic, addr_pic_no_got]) and
  2693. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  2694. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  2695. (
  2696. (
  2697. (taicpu(hp1).opcode = A_TEST)
  2698. ) or (
  2699. (taicpu(hp1).opcode = A_CMP) and
  2700. { A sanity check more than anything }
  2701. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  2702. )
  2703. ) then
  2704. begin
  2705. { change
  2706. mov mem, %reg
  2707. cmp/test x, %reg / test %reg,%reg
  2708. (reg deallocated)
  2709. to
  2710. cmp/test x, mem / cmp 0, mem
  2711. }
  2712. TransferUsedRegs(TmpUsedRegs);
  2713. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2714. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2715. begin
  2716. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  2717. if (taicpu(hp1).opcode = A_TEST) and
  2718. (
  2719. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  2720. MatchOperand(taicpu(hp1).oper[0]^, -1)
  2721. ) then
  2722. begin
  2723. taicpu(hp1).opcode := A_CMP;
  2724. taicpu(hp1).loadconst(0, 0);
  2725. end;
  2726. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  2727. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  2728. RemoveCurrentP(p, hp1);
  2729. Result := True;
  2730. Exit;
  2731. end;
  2732. end;
  2733. end;
  2734. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  2735. { If the flags register is in use, don't change the instruction to an
  2736. ADD otherwise this will scramble the flags. [Kit] }
  2737. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  2738. begin
  2739. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  2740. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  2741. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  2742. ) or
  2743. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  2744. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  2745. )
  2746. ) then
  2747. { mov reg1,ref
  2748. lea reg2,[reg1,reg2]
  2749. to
  2750. add reg2,ref}
  2751. begin
  2752. TransferUsedRegs(TmpUsedRegs);
  2753. { reg1 may not be used afterwards }
  2754. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  2755. begin
  2756. Taicpu(hp1).opcode:=A_ADD;
  2757. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  2758. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  2759. RemoveCurrentp(p, hp1);
  2760. result:=true;
  2761. exit;
  2762. end;
  2763. end;
  2764. { If the LEA instruction can be converted into an arithmetic instruction,
  2765. it may be possible to then fold it in the next optimisation, otherwise
  2766. there's nothing more that can be optimised here. }
  2767. if not ConvertLEA(taicpu(hp1)) then
  2768. Exit;
  2769. end;
  2770. if (taicpu(p).oper[1]^.typ = top_reg) and
  2771. (hp1.typ = ait_instruction) and
  2772. GetNextInstruction(hp1, hp2) and
  2773. MatchInstruction(hp2,A_MOV,[]) and
  2774. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  2775. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  2776. (
  2777. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  2778. {$ifdef x86_64}
  2779. or
  2780. (
  2781. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  2782. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  2783. )
  2784. {$endif x86_64}
  2785. ) then
  2786. begin
  2787. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2788. (taicpu(hp2).oper[0]^.typ=top_reg) then
  2789. { change movsX/movzX reg/ref, reg2
  2790. add/sub/or/... reg3/$const, reg2
  2791. mov reg2 reg/ref
  2792. dealloc reg2
  2793. to
  2794. add/sub/or/... reg3/$const, reg/ref }
  2795. begin
  2796. TransferUsedRegs(TmpUsedRegs);
  2797. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2798. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2799. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2800. begin
  2801. { by example:
  2802. movswl %si,%eax movswl %si,%eax p
  2803. decl %eax addl %edx,%eax hp1
  2804. movw %ax,%si movw %ax,%si hp2
  2805. ->
  2806. movswl %si,%eax movswl %si,%eax p
  2807. decw %eax addw %edx,%eax hp1
  2808. movw %ax,%si movw %ax,%si hp2
  2809. }
  2810. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  2811. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  2812. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  2813. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  2814. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  2815. {
  2816. ->
  2817. movswl %si,%eax movswl %si,%eax p
  2818. decw %si addw %dx,%si hp1
  2819. movw %ax,%si movw %ax,%si hp2
  2820. }
  2821. case taicpu(hp1).ops of
  2822. 1:
  2823. begin
  2824. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  2825. if taicpu(hp1).oper[0]^.typ=top_reg then
  2826. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  2827. end;
  2828. 2:
  2829. begin
  2830. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2831. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  2832. (taicpu(hp1).opcode<>A_SHL) and
  2833. (taicpu(hp1).opcode<>A_SHR) and
  2834. (taicpu(hp1).opcode<>A_SAR) then
  2835. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  2836. end;
  2837. else
  2838. internalerror(2008042701);
  2839. end;
  2840. {
  2841. ->
  2842. decw %si addw %dx,%si p
  2843. }
  2844. RemoveInstruction(hp2);
  2845. RemoveCurrentP(p, hp1);
  2846. Result:=True;
  2847. Exit;
  2848. end;
  2849. end;
  2850. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2851. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  2852. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  2853. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  2854. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  2855. )
  2856. {$ifdef i386}
  2857. { byte registers of esi, edi, ebp, esp are not available on i386 }
  2858. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  2859. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  2860. {$endif i386}
  2861. then
  2862. { change movsX/movzX reg/ref, reg2
  2863. add/sub/or/... regX/$const, reg2
  2864. mov reg2, reg3
  2865. dealloc reg2
  2866. to
  2867. movsX/movzX reg/ref, reg3
  2868. add/sub/or/... reg3/$const, reg3
  2869. }
  2870. begin
  2871. TransferUsedRegs(TmpUsedRegs);
  2872. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2873. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2874. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2875. begin
  2876. { by example:
  2877. movswl %si,%eax movswl %si,%eax p
  2878. decl %eax addl %edx,%eax hp1
  2879. movw %ax,%si movw %ax,%si hp2
  2880. ->
  2881. movswl %si,%eax movswl %si,%eax p
  2882. decw %eax addw %edx,%eax hp1
  2883. movw %ax,%si movw %ax,%si hp2
  2884. }
  2885. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  2886. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  2887. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  2888. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  2889. { limit size of constants as well to avoid assembler errors, but
  2890. check opsize to avoid overflow when left shifting the 1 }
  2891. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  2892. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  2893. {$ifdef x86_64}
  2894. { Be careful of, for example:
  2895. movl %reg1,%reg2
  2896. addl %reg3,%reg2
  2897. movq %reg2,%reg4
  2898. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  2899. }
  2900. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  2901. begin
  2902. taicpu(hp2).changeopsize(S_L);
  2903. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  2904. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  2905. end;
  2906. {$endif x86_64}
  2907. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  2908. taicpu(p).changeopsize(taicpu(hp2).opsize);
  2909. if taicpu(p).oper[0]^.typ=top_reg then
  2910. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  2911. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  2912. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  2913. {
  2914. ->
  2915. movswl %si,%eax movswl %si,%eax p
  2916. decw %si addw %dx,%si hp1
  2917. movw %ax,%si movw %ax,%si hp2
  2918. }
  2919. case taicpu(hp1).ops of
  2920. 1:
  2921. begin
  2922. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  2923. if taicpu(hp1).oper[0]^.typ=top_reg then
  2924. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  2925. end;
  2926. 2:
  2927. begin
  2928. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2929. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  2930. (taicpu(hp1).opcode<>A_SHL) and
  2931. (taicpu(hp1).opcode<>A_SHR) and
  2932. (taicpu(hp1).opcode<>A_SAR) then
  2933. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  2934. end;
  2935. else
  2936. internalerror(2018111801);
  2937. end;
  2938. {
  2939. ->
  2940. decw %si addw %dx,%si p
  2941. }
  2942. RemoveInstruction(hp2);
  2943. end;
  2944. end;
  2945. end;
  2946. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  2947. GetNextInstruction(hp1, hp2) and
  2948. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  2949. MatchOperand(Taicpu(p).oper[0]^,0) and
  2950. (Taicpu(p).oper[1]^.typ = top_reg) and
  2951. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  2952. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  2953. { mov reg1,0
  2954. bts reg1,operand1 --> mov reg1,operand2
  2955. or reg1,operand2 bts reg1,operand1}
  2956. begin
  2957. Taicpu(hp2).opcode:=A_MOV;
  2958. asml.remove(hp1);
  2959. insertllitem(hp2,hp2.next,hp1);
  2960. RemoveCurrentp(p, hp1);
  2961. Result:=true;
  2962. exit;
  2963. end;
  2964. {$ifdef x86_64}
  2965. { Convert:
  2966. movq x(ref),%reg64
  2967. shrq y,%reg64
  2968. To:
  2969. movq x+4(ref),%reg32
  2970. shrq y-32,%reg32 (Remove if y = 32)
  2971. }
  2972. if (taicpu(p).opsize = S_Q) and
  2973. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  2974. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  2975. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  2976. MatchOpType(taicpu(hp1), top_const, top_reg) and
  2977. (taicpu(hp1).oper[0]^.val >= 32) and
  2978. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  2979. begin
  2980. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  2981. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  2982. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  2983. { Convert to 32-bit }
  2984. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2985. taicpu(p).opsize := S_L;
  2986. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  2987. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  2988. if (taicpu(hp1).oper[0]^.val = 32) then
  2989. begin
  2990. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  2991. RemoveInstruction(hp1);
  2992. end
  2993. else
  2994. begin
  2995. { This will potentially open up more arithmetic operations since
  2996. the peephole optimizer now has a big hint that only the lower
  2997. 32 bits are currently in use (and opcodes are smaller in size) }
  2998. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2999. taicpu(hp1).opsize := S_L;
  3000. Dec(taicpu(hp1).oper[0]^.val, 32);
  3001. DebugMsg(SPeepholeOptimization + PreMessage +
  3002. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3003. end;
  3004. Result := True;
  3005. Exit;
  3006. end;
  3007. {$endif x86_64}
  3008. end;
  3009. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  3010. var
  3011. hp1 : tai;
  3012. begin
  3013. Result:=false;
  3014. if taicpu(p).ops <> 2 then
  3015. exit;
  3016. if GetNextInstruction(p,hp1) and
  3017. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  3018. (taicpu(hp1).ops = 2) then
  3019. begin
  3020. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3021. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3022. { movXX reg1, mem1 or movXX mem1, reg1
  3023. movXX mem2, reg2 movXX reg2, mem2}
  3024. begin
  3025. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3026. { movXX reg1, mem1 or movXX mem1, reg1
  3027. movXX mem2, reg1 movXX reg2, mem1}
  3028. begin
  3029. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3030. begin
  3031. { Removes the second statement from
  3032. movXX reg1, mem1/reg2
  3033. movXX mem1/reg2, reg1
  3034. }
  3035. if taicpu(p).oper[0]^.typ=top_reg then
  3036. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3037. { Removes the second statement from
  3038. movXX mem1/reg1, reg2
  3039. movXX reg2, mem1/reg1
  3040. }
  3041. if (taicpu(p).oper[1]^.typ=top_reg) and
  3042. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  3043. begin
  3044. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  3045. RemoveInstruction(hp1);
  3046. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  3047. end
  3048. else
  3049. begin
  3050. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  3051. RemoveInstruction(hp1);
  3052. end;
  3053. Result:=true;
  3054. exit;
  3055. end
  3056. end;
  3057. end;
  3058. end;
  3059. end;
  3060. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  3061. var
  3062. hp1 : tai;
  3063. begin
  3064. result:=false;
  3065. { replace
  3066. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  3067. MovX %mreg2,%mreg1
  3068. dealloc %mreg2
  3069. by
  3070. <Op>X %mreg2,%mreg1
  3071. ?
  3072. }
  3073. if GetNextInstruction(p,hp1) and
  3074. { we mix single and double opperations here because we assume that the compiler
  3075. generates vmovapd only after double operations and vmovaps only after single operations }
  3076. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  3077. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3078. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  3079. (taicpu(p).oper[0]^.typ=top_reg) then
  3080. begin
  3081. TransferUsedRegs(TmpUsedRegs);
  3082. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3083. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3084. begin
  3085. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  3086. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3087. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  3088. RemoveInstruction(hp1);
  3089. result:=true;
  3090. end;
  3091. end;
  3092. end;
  3093. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  3094. var
  3095. hp1, p_label, p_dist, hp1_dist: tai;
  3096. JumpLabel, JumpLabel_dist: TAsmLabel;
  3097. begin
  3098. Result := False;
  3099. if (taicpu(p).oper[1]^.typ = top_reg) then
  3100. begin
  3101. if GetNextInstruction(p, hp1) and
  3102. MatchInstruction(hp1,A_MOV,[]) and
  3103. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  3104. (
  3105. (taicpu(p).oper[0]^.typ <> top_reg) or
  3106. not RegInInstruction(taicpu(p).oper[0]^.reg, hp1)
  3107. ) then
  3108. begin
  3109. { If we have something like:
  3110. test %reg1,%reg1
  3111. mov 0,%reg2
  3112. And no registers are shared (the two %reg1's can be different, as
  3113. long as neither of them are also %reg2), move the MOV command to
  3114. before the comparison as this means it can be optimised without
  3115. worrying about the FLAGS register. (This combination is generated
  3116. by "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  3117. }
  3118. SwapMovCmp(p, hp1);
  3119. Result := True;
  3120. Exit;
  3121. end;
  3122. { Search for:
  3123. test %reg,%reg
  3124. j(c1) @lbl1
  3125. ...
  3126. @lbl:
  3127. test %reg,%reg (same register)
  3128. j(c2) @lbl2
  3129. If c2 is a subset of c1, change to:
  3130. test %reg,%reg
  3131. j(c1) @lbl2
  3132. (@lbl1 may become a dead label as a result)
  3133. }
  3134. if (taicpu(p).oper[0]^.typ = top_reg) and
  3135. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  3136. MatchInstruction(hp1, A_JCC, []) and
  3137. IsJumpToLabel(taicpu(hp1)) then
  3138. begin
  3139. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  3140. p_label := nil;
  3141. if Assigned(JumpLabel) then
  3142. p_label := getlabelwithsym(JumpLabel);
  3143. if Assigned(p_label) and
  3144. GetNextInstruction(p_label, p_dist) and
  3145. MatchInstruction(p_dist, A_TEST, []) and
  3146. { It's fine if the second test uses smaller sub-registers }
  3147. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  3148. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  3149. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  3150. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  3151. GetNextInstruction(p_dist, hp1_dist) and
  3152. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  3153. begin
  3154. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  3155. if JumpLabel = JumpLabel_dist then
  3156. { This is an infinite loop }
  3157. Exit;
  3158. { Best optimisation when the first condition is a subset (or equal) of the second }
  3159. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  3160. begin
  3161. { Any registers used here will already be allocated }
  3162. if Assigned(JumpLabel_dist) then
  3163. JumpLabel_dist.IncRefs;
  3164. if Assigned(JumpLabel) then
  3165. JumpLabel.DecRefs;
  3166. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  3167. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  3168. Result := True;
  3169. Exit;
  3170. end;
  3171. end;
  3172. end;
  3173. end;
  3174. end;
  3175. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  3176. var
  3177. hp1 : tai;
  3178. begin
  3179. result:=false;
  3180. { replace
  3181. addX const,%reg1
  3182. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  3183. dealloc %reg1
  3184. by
  3185. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  3186. }
  3187. if MatchOpType(taicpu(p),top_const,top_reg) and
  3188. GetNextInstruction(p,hp1) and
  3189. MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  3190. ((taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.base) or
  3191. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index)) then
  3192. begin
  3193. TransferUsedRegs(TmpUsedRegs);
  3194. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3195. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3196. begin
  3197. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  3198. if taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.base then
  3199. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  3200. if taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index then
  3201. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  3202. RemoveCurrentP(p);
  3203. result:=true;
  3204. end;
  3205. end;
  3206. end;
  3207. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  3208. var
  3209. hp1: tai;
  3210. ref: Integer;
  3211. saveref: treference;
  3212. TempReg: TRegister;
  3213. Multiple: TCGInt;
  3214. begin
  3215. Result:=false;
  3216. { removes seg register prefixes from LEA operations, as they
  3217. don't do anything}
  3218. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  3219. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  3220. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3221. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  3222. { do not mess with leas acessing the stack pointer }
  3223. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  3224. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  3225. begin
  3226. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  3227. begin
  3228. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  3229. begin
  3230. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  3231. taicpu(p).oper[1]^.reg);
  3232. InsertLLItem(p.previous,p.next, hp1);
  3233. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  3234. p.free;
  3235. p:=hp1;
  3236. end
  3237. else
  3238. begin
  3239. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  3240. RemoveCurrentP(p);
  3241. end;
  3242. Result:=true;
  3243. exit;
  3244. end
  3245. else if (
  3246. { continue to use lea to adjust the stack pointer,
  3247. it is the recommended way, but only if not optimizing for size }
  3248. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  3249. (cs_opt_size in current_settings.optimizerswitches)
  3250. ) and
  3251. { If the flags register is in use, don't change the instruction
  3252. to an ADD otherwise this will scramble the flags. [Kit] }
  3253. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  3254. ConvertLEA(taicpu(p)) then
  3255. begin
  3256. Result:=true;
  3257. exit;
  3258. end;
  3259. end;
  3260. if GetNextInstruction(p,hp1) and
  3261. (hp1.typ=ait_instruction) then
  3262. begin
  3263. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  3264. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3265. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  3266. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  3267. begin
  3268. TransferUsedRegs(TmpUsedRegs);
  3269. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3270. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3271. begin
  3272. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3273. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  3274. RemoveInstruction(hp1);
  3275. result:=true;
  3276. exit;
  3277. end;
  3278. end;
  3279. { changes
  3280. lea <ref1>, reg1
  3281. <op> ...,<ref. with reg1>,...
  3282. to
  3283. <op> ...,<ref1>,... }
  3284. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  3285. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  3286. not(MatchInstruction(hp1,A_LEA,[])) then
  3287. begin
  3288. { find a reference which uses reg1 }
  3289. 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
  3290. ref:=0
  3291. 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
  3292. ref:=1
  3293. else
  3294. ref:=-1;
  3295. if (ref<>-1) and
  3296. { reg1 must be either the base or the index }
  3297. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  3298. begin
  3299. { reg1 can be removed from the reference }
  3300. saveref:=taicpu(hp1).oper[ref]^.ref^;
  3301. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  3302. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  3303. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  3304. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  3305. else
  3306. Internalerror(2019111201);
  3307. { check if the can insert all data of the lea into the second instruction }
  3308. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  3309. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  3310. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  3311. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  3312. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  3313. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  3314. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  3315. {$ifdef x86_64}
  3316. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  3317. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  3318. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  3319. )
  3320. {$endif x86_64}
  3321. then
  3322. begin
  3323. { reg1 might not used by the second instruction after it is remove from the reference }
  3324. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  3325. begin
  3326. TransferUsedRegs(TmpUsedRegs);
  3327. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3328. { reg1 is not updated so it might not be used afterwards }
  3329. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3330. begin
  3331. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  3332. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  3333. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3334. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  3335. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  3336. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  3337. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  3338. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  3339. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  3340. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  3341. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  3342. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3343. RemoveCurrentP(p, hp1);
  3344. result:=true;
  3345. exit;
  3346. end
  3347. end;
  3348. end;
  3349. { recover }
  3350. taicpu(hp1).oper[ref]^.ref^:=saveref;
  3351. end;
  3352. end;
  3353. end;
  3354. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  3355. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  3356. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  3357. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  3358. begin
  3359. { Check common LEA/LEA conditions }
  3360. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  3361. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  3362. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  3363. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  3364. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  3365. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  3366. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  3367. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  3368. (
  3369. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  3370. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  3371. ) and (
  3372. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  3373. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3374. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  3375. ) then
  3376. begin
  3377. { changes
  3378. lea (regX,scale), reg1
  3379. lea offset(reg1,reg1), reg1
  3380. to
  3381. lea offset(regX,scale*2), reg1
  3382. and
  3383. lea (regX,scale1), reg1
  3384. lea offset(reg1,scale2), reg1
  3385. to
  3386. lea offset(regX,scale1*scale2), reg1
  3387. ... so long as the final scale does not exceed 8
  3388. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  3389. }
  3390. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  3391. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  3392. (
  3393. (
  3394. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  3395. ) or (
  3396. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  3397. (
  3398. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  3399. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  3400. )
  3401. )
  3402. ) and (
  3403. (
  3404. { lea (reg1,scale2), reg1 variant }
  3405. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  3406. (
  3407. (
  3408. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  3409. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  3410. ) or (
  3411. { lea (regX,regX), reg1 variant }
  3412. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3413. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  3414. )
  3415. )
  3416. ) or (
  3417. { lea (reg1,reg1), reg1 variant }
  3418. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  3419. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  3420. )
  3421. ) then
  3422. begin
  3423. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  3424. { Make everything homogeneous to make calculations easier }
  3425. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  3426. begin
  3427. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  3428. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  3429. taicpu(p).oper[0]^.ref^.scalefactor := 2
  3430. else
  3431. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  3432. taicpu(p).oper[0]^.ref^.base := NR_NO;
  3433. end;
  3434. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  3435. begin
  3436. { Just to prevent miscalculations }
  3437. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  3438. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  3439. else
  3440. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  3441. end
  3442. else
  3443. begin
  3444. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  3445. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  3446. end;
  3447. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  3448. RemoveCurrentP(p);
  3449. result:=true;
  3450. exit;
  3451. end
  3452. { changes
  3453. lea offset1(regX), reg1
  3454. lea offset2(reg1), reg1
  3455. to
  3456. lea offset1+offset2(regX), reg1 }
  3457. else if
  3458. (
  3459. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  3460. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  3461. ) or (
  3462. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  3463. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  3464. (
  3465. (
  3466. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3467. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  3468. ) or (
  3469. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  3470. (
  3471. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3472. (
  3473. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  3474. (
  3475. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  3476. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  3477. )
  3478. )
  3479. )
  3480. )
  3481. )
  3482. ) then
  3483. begin
  3484. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  3485. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  3486. begin
  3487. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  3488. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  3489. { if the register is used as index and base, we have to increase for base as well
  3490. and adapt base }
  3491. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  3492. begin
  3493. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3494. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3495. end;
  3496. end
  3497. else
  3498. begin
  3499. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3500. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3501. end;
  3502. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  3503. begin
  3504. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  3505. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  3506. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  3507. end;
  3508. RemoveCurrentP(p);
  3509. result:=true;
  3510. exit;
  3511. end;
  3512. end;
  3513. { Change:
  3514. leal/q $x(%reg1),%reg2
  3515. ...
  3516. shll/q $y,%reg2
  3517. To:
  3518. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  3519. }
  3520. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  3521. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3522. (taicpu(hp1).oper[0]^.val <= 3) then
  3523. begin
  3524. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  3525. TransferUsedRegs(TmpUsedRegs);
  3526. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3527. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  3528. if
  3529. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  3530. (this works even if scalefactor is zero) }
  3531. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  3532. { Ensure offset doesn't go out of bounds }
  3533. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  3534. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  3535. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  3536. (
  3537. (
  3538. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  3539. (
  3540. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3541. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  3542. (
  3543. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  3544. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  3545. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  3546. )
  3547. )
  3548. ) or (
  3549. (
  3550. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  3551. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  3552. ) and
  3553. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  3554. )
  3555. ) then
  3556. begin
  3557. repeat
  3558. with taicpu(p).oper[0]^.ref^ do
  3559. begin
  3560. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  3561. if index = base then
  3562. begin
  3563. if Multiple > 4 then
  3564. { Optimisation will no longer work because resultant
  3565. scale factor will exceed 8 }
  3566. Break;
  3567. base := NR_NO;
  3568. scalefactor := 2;
  3569. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  3570. end
  3571. else if (base <> NR_NO) and (base <> NR_INVALID) then
  3572. begin
  3573. { Scale factor only works on the index register }
  3574. index := base;
  3575. base := NR_NO;
  3576. end;
  3577. { For safety }
  3578. if scalefactor <= 1 then
  3579. begin
  3580. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  3581. scalefactor := Multiple;
  3582. end
  3583. else
  3584. begin
  3585. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  3586. scalefactor := scalefactor * Multiple;
  3587. end;
  3588. offset := offset * Multiple;
  3589. end;
  3590. RemoveInstruction(hp1);
  3591. Result := True;
  3592. Exit;
  3593. { This repeat..until loop exists for the benefit of Break }
  3594. until True;
  3595. end;
  3596. end;
  3597. end;
  3598. end;
  3599. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  3600. var
  3601. hp1 : tai;
  3602. begin
  3603. DoSubAddOpt := False;
  3604. if GetLastInstruction(p, hp1) and
  3605. (hp1.typ = ait_instruction) and
  3606. (taicpu(hp1).opsize = taicpu(p).opsize) then
  3607. case taicpu(hp1).opcode Of
  3608. A_DEC:
  3609. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  3610. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3611. begin
  3612. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  3613. RemoveInstruction(hp1);
  3614. end;
  3615. A_SUB:
  3616. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  3617. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  3618. begin
  3619. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  3620. RemoveInstruction(hp1);
  3621. end;
  3622. A_ADD:
  3623. begin
  3624. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  3625. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  3626. begin
  3627. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  3628. RemoveInstruction(hp1);
  3629. if (taicpu(p).oper[0]^.val = 0) then
  3630. begin
  3631. hp1 := tai(p.next);
  3632. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  3633. if not GetLastInstruction(hp1, p) then
  3634. p := hp1;
  3635. DoSubAddOpt := True;
  3636. end
  3637. end;
  3638. end;
  3639. else
  3640. ;
  3641. end;
  3642. end;
  3643. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  3644. {$ifdef i386}
  3645. var
  3646. hp1 : tai;
  3647. {$endif i386}
  3648. begin
  3649. Result:=false;
  3650. { * change "subl $2, %esp; pushw x" to "pushl x"}
  3651. { * change "sub/add const1, reg" or "dec reg" followed by
  3652. "sub const2, reg" to one "sub ..., reg" }
  3653. if MatchOpType(taicpu(p),top_const,top_reg) then
  3654. begin
  3655. {$ifdef i386}
  3656. if (taicpu(p).oper[0]^.val = 2) and
  3657. (taicpu(p).oper[1]^.reg = NR_ESP) and
  3658. { Don't do the sub/push optimization if the sub }
  3659. { comes from setting up the stack frame (JM) }
  3660. (not(GetLastInstruction(p,hp1)) or
  3661. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  3662. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  3663. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  3664. begin
  3665. hp1 := tai(p.next);
  3666. while Assigned(hp1) and
  3667. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  3668. not RegReadByInstruction(NR_ESP,hp1) and
  3669. not RegModifiedByInstruction(NR_ESP,hp1) do
  3670. hp1 := tai(hp1.next);
  3671. if Assigned(hp1) and
  3672. MatchInstruction(hp1,A_PUSH,[S_W]) then
  3673. begin
  3674. taicpu(hp1).changeopsize(S_L);
  3675. if taicpu(hp1).oper[0]^.typ=top_reg then
  3676. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  3677. hp1 := tai(p.next);
  3678. RemoveCurrentp(p, hp1);
  3679. Result:=true;
  3680. exit;
  3681. end;
  3682. end;
  3683. {$endif i386}
  3684. if DoSubAddOpt(p) then
  3685. Result:=true;
  3686. end;
  3687. end;
  3688. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  3689. var
  3690. TmpBool1,TmpBool2 : Boolean;
  3691. tmpref : treference;
  3692. hp1,hp2: tai;
  3693. mask: tcgint;
  3694. begin
  3695. Result:=false;
  3696. { All these optimisations work on "shl/sal const,%reg" }
  3697. if not MatchOpType(taicpu(p),top_const,top_reg) then
  3698. Exit;
  3699. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3700. (taicpu(p).oper[0]^.val <= 3) then
  3701. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  3702. begin
  3703. { should we check the next instruction? }
  3704. TmpBool1 := True;
  3705. { have we found an add/sub which could be
  3706. integrated in the lea? }
  3707. TmpBool2 := False;
  3708. reference_reset(tmpref,2,[]);
  3709. TmpRef.index := taicpu(p).oper[1]^.reg;
  3710. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  3711. while TmpBool1 and
  3712. GetNextInstruction(p, hp1) and
  3713. (tai(hp1).typ = ait_instruction) and
  3714. ((((taicpu(hp1).opcode = A_ADD) or
  3715. (taicpu(hp1).opcode = A_SUB)) and
  3716. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  3717. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  3718. (((taicpu(hp1).opcode = A_INC) or
  3719. (taicpu(hp1).opcode = A_DEC)) and
  3720. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  3721. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  3722. ((taicpu(hp1).opcode = A_LEA) and
  3723. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  3724. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  3725. (not GetNextInstruction(hp1,hp2) or
  3726. not instrReadsFlags(hp2)) Do
  3727. begin
  3728. TmpBool1 := False;
  3729. if taicpu(hp1).opcode=A_LEA then
  3730. begin
  3731. if (TmpRef.base = NR_NO) and
  3732. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  3733. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  3734. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  3735. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  3736. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  3737. begin
  3738. TmpBool1 := True;
  3739. TmpBool2 := True;
  3740. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  3741. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  3742. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  3743. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  3744. RemoveInstruction(hp1);
  3745. end
  3746. end
  3747. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  3748. begin
  3749. TmpBool1 := True;
  3750. TmpBool2 := True;
  3751. case taicpu(hp1).opcode of
  3752. A_ADD:
  3753. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  3754. A_SUB:
  3755. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  3756. else
  3757. internalerror(2019050536);
  3758. end;
  3759. RemoveInstruction(hp1);
  3760. end
  3761. else
  3762. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  3763. (((taicpu(hp1).opcode = A_ADD) and
  3764. (TmpRef.base = NR_NO)) or
  3765. (taicpu(hp1).opcode = A_INC) or
  3766. (taicpu(hp1).opcode = A_DEC)) then
  3767. begin
  3768. TmpBool1 := True;
  3769. TmpBool2 := True;
  3770. case taicpu(hp1).opcode of
  3771. A_ADD:
  3772. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  3773. A_INC:
  3774. inc(TmpRef.offset);
  3775. A_DEC:
  3776. dec(TmpRef.offset);
  3777. else
  3778. internalerror(2019050535);
  3779. end;
  3780. RemoveInstruction(hp1);
  3781. end;
  3782. end;
  3783. if TmpBool2
  3784. {$ifndef x86_64}
  3785. or
  3786. ((current_settings.optimizecputype < cpu_Pentium2) and
  3787. (taicpu(p).oper[0]^.val <= 3) and
  3788. not(cs_opt_size in current_settings.optimizerswitches))
  3789. {$endif x86_64}
  3790. then
  3791. begin
  3792. if not(TmpBool2) and
  3793. (taicpu(p).oper[0]^.val=1) then
  3794. begin
  3795. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  3796. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  3797. end
  3798. else
  3799. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  3800. taicpu(p).oper[1]^.reg);
  3801. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  3802. InsertLLItem(p.previous, p.next, hp1);
  3803. p.free;
  3804. p := hp1;
  3805. end;
  3806. end
  3807. {$ifndef x86_64}
  3808. else if (current_settings.optimizecputype < cpu_Pentium2) then
  3809. begin
  3810. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  3811. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  3812. (unlike shl, which is only Tairable in the U pipe) }
  3813. if taicpu(p).oper[0]^.val=1 then
  3814. begin
  3815. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  3816. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  3817. InsertLLItem(p.previous, p.next, hp1);
  3818. p.free;
  3819. p := hp1;
  3820. end
  3821. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  3822. "shl $3, %reg" to "lea (,%reg,8), %reg }
  3823. else if (taicpu(p).opsize = S_L) and
  3824. (taicpu(p).oper[0]^.val<= 3) then
  3825. begin
  3826. reference_reset(tmpref,2,[]);
  3827. TmpRef.index := taicpu(p).oper[1]^.reg;
  3828. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  3829. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  3830. InsertLLItem(p.previous, p.next, hp1);
  3831. p.free;
  3832. p := hp1;
  3833. end;
  3834. end
  3835. {$endif x86_64}
  3836. else if
  3837. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  3838. (
  3839. (
  3840. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  3841. SetAndTest(hp1, hp2)
  3842. {$ifdef x86_64}
  3843. ) or
  3844. (
  3845. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  3846. GetNextInstruction(hp1, hp2) and
  3847. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  3848. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3849. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  3850. {$endif x86_64}
  3851. )
  3852. ) and
  3853. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  3854. begin
  3855. { Change:
  3856. shl x, %reg1
  3857. mov -(1<<x), %reg2
  3858. and %reg2, %reg1
  3859. Or:
  3860. shl x, %reg1
  3861. and -(1<<x), %reg1
  3862. To just:
  3863. shl x, %reg1
  3864. Since the and operation only zeroes bits that are already zero from the shl operation
  3865. }
  3866. case taicpu(p).oper[0]^.val of
  3867. 8:
  3868. mask:=$FFFFFFFFFFFFFF00;
  3869. 16:
  3870. mask:=$FFFFFFFFFFFF0000;
  3871. 32:
  3872. mask:=$FFFFFFFF00000000;
  3873. 63:
  3874. { Constant pre-calculated to prevent overflow errors with Int64 }
  3875. mask:=$8000000000000000;
  3876. else
  3877. begin
  3878. if taicpu(p).oper[0]^.val >= 64 then
  3879. { Shouldn't happen realistically, since the register
  3880. is guaranteed to be set to zero at this point }
  3881. mask := 0
  3882. else
  3883. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  3884. end;
  3885. end;
  3886. if taicpu(hp1).oper[0]^.val = mask then
  3887. begin
  3888. { Everything checks out, perform the optimisation, as long as
  3889. the FLAGS register isn't being used}
  3890. TransferUsedRegs(TmpUsedRegs);
  3891. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3892. {$ifdef x86_64}
  3893. if (hp1 <> hp2) then
  3894. begin
  3895. { "shl/mov/and" version }
  3896. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3897. { Don't do the optimisation if the FLAGS register is in use }
  3898. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  3899. begin
  3900. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  3901. { Don't remove the 'mov' instruction if its register is used elsewhere }
  3902. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3903. begin
  3904. RemoveInstruction(hp1);
  3905. Result := True;
  3906. end;
  3907. { Only set Result to True if the 'mov' instruction was removed }
  3908. RemoveInstruction(hp2);
  3909. end;
  3910. end
  3911. else
  3912. {$endif x86_64}
  3913. begin
  3914. { "shl/and" version }
  3915. { Don't do the optimisation if the FLAGS register is in use }
  3916. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3917. begin
  3918. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  3919. RemoveInstruction(hp1);
  3920. Result := True;
  3921. end;
  3922. end;
  3923. Exit;
  3924. end
  3925. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  3926. begin
  3927. { Even if the mask doesn't allow for its removal, we might be
  3928. able to optimise the mask for the "shl/and" version, which
  3929. may permit other peephole optimisations }
  3930. {$ifdef DEBUG_AOPTCPU}
  3931. mask := taicpu(hp1).oper[0]^.val and mask;
  3932. if taicpu(hp1).oper[0]^.val <> mask then
  3933. begin
  3934. DebugMsg(
  3935. SPeepholeOptimization +
  3936. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  3937. ' to $' + debug_tostr(mask) +
  3938. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  3939. taicpu(hp1).oper[0]^.val := mask;
  3940. end;
  3941. {$else DEBUG_AOPTCPU}
  3942. { If debugging is off, just set the operand even if it's the same }
  3943. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  3944. {$endif DEBUG_AOPTCPU}
  3945. end;
  3946. end;
  3947. end;
  3948. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  3949. var
  3950. CurrentRef: TReference;
  3951. FullReg: TRegister;
  3952. hp1, hp2: tai;
  3953. begin
  3954. Result := False;
  3955. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  3956. Exit;
  3957. { We assume you've checked if the operand is actually a reference by
  3958. this point. If it isn't, you'll most likely get an access violation }
  3959. CurrentRef := first_mov.oper[1]^.ref^;
  3960. { Memory must be aligned }
  3961. if (CurrentRef.offset mod 4) <> 0 then
  3962. Exit;
  3963. Inc(CurrentRef.offset);
  3964. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  3965. if MatchOperand(second_mov.oper[0]^, 0) and
  3966. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  3967. GetNextInstruction(second_mov, hp1) and
  3968. (hp1.typ = ait_instruction) and
  3969. (taicpu(hp1).opcode = A_MOV) and
  3970. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3971. (taicpu(hp1).oper[0]^.val = 0) then
  3972. begin
  3973. Inc(CurrentRef.offset);
  3974. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  3975. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  3976. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  3977. begin
  3978. case taicpu(hp1).opsize of
  3979. S_B:
  3980. if GetNextInstruction(hp1, hp2) and
  3981. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  3982. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3983. (taicpu(hp2).oper[0]^.val = 0) then
  3984. begin
  3985. Inc(CurrentRef.offset);
  3986. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  3987. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  3988. (taicpu(hp2).opsize = S_B) then
  3989. begin
  3990. RemoveInstruction(hp1);
  3991. RemoveInstruction(hp2);
  3992. first_mov.opsize := S_L;
  3993. if first_mov.oper[0]^.typ = top_reg then
  3994. begin
  3995. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  3996. { Reuse second_mov as a MOVZX instruction }
  3997. second_mov.opcode := A_MOVZX;
  3998. second_mov.opsize := S_BL;
  3999. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4000. second_mov.loadreg(1, FullReg);
  4001. first_mov.oper[0]^.reg := FullReg;
  4002. asml.Remove(second_mov);
  4003. asml.InsertBefore(second_mov, first_mov);
  4004. end
  4005. else
  4006. { It's a value }
  4007. begin
  4008. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  4009. RemoveInstruction(second_mov);
  4010. end;
  4011. Result := True;
  4012. Exit;
  4013. end;
  4014. end;
  4015. S_W:
  4016. begin
  4017. RemoveInstruction(hp1);
  4018. first_mov.opsize := S_L;
  4019. if first_mov.oper[0]^.typ = top_reg then
  4020. begin
  4021. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  4022. { Reuse second_mov as a MOVZX instruction }
  4023. second_mov.opcode := A_MOVZX;
  4024. second_mov.opsize := S_BL;
  4025. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4026. second_mov.loadreg(1, FullReg);
  4027. first_mov.oper[0]^.reg := FullReg;
  4028. asml.Remove(second_mov);
  4029. asml.InsertBefore(second_mov, first_mov);
  4030. end
  4031. else
  4032. { It's a value }
  4033. begin
  4034. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  4035. RemoveInstruction(second_mov);
  4036. end;
  4037. Result := True;
  4038. Exit;
  4039. end;
  4040. else
  4041. ;
  4042. end;
  4043. end;
  4044. end;
  4045. end;
  4046. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  4047. { returns true if a "continue" should be done after this optimization }
  4048. var
  4049. hp1, hp2: tai;
  4050. begin
  4051. Result := false;
  4052. if MatchOpType(taicpu(p),top_ref) and
  4053. GetNextInstruction(p, hp1) and
  4054. (hp1.typ = ait_instruction) and
  4055. (((taicpu(hp1).opcode = A_FLD) and
  4056. (taicpu(p).opcode = A_FSTP)) or
  4057. ((taicpu(p).opcode = A_FISTP) and
  4058. (taicpu(hp1).opcode = A_FILD))) and
  4059. MatchOpType(taicpu(hp1),top_ref) and
  4060. (taicpu(hp1).opsize = taicpu(p).opsize) and
  4061. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  4062. begin
  4063. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  4064. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  4065. GetNextInstruction(hp1, hp2) and
  4066. (hp2.typ = ait_instruction) and
  4067. IsExitCode(hp2) and
  4068. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  4069. not(assigned(current_procinfo.procdef.funcretsym) and
  4070. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  4071. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  4072. begin
  4073. RemoveInstruction(hp1);
  4074. RemoveCurrentP(p, hp2);
  4075. RemoveLastDeallocForFuncRes(p);
  4076. Result := true;
  4077. end
  4078. else
  4079. { we can do this only in fast math mode as fstp is rounding ...
  4080. ... still disabled as it breaks the compiler and/or rtl }
  4081. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  4082. { ... or if another fstp equal to the first one follows }
  4083. (GetNextInstruction(hp1,hp2) and
  4084. (hp2.typ = ait_instruction) and
  4085. (taicpu(p).opcode=taicpu(hp2).opcode) and
  4086. (taicpu(p).opsize=taicpu(hp2).opsize))
  4087. ) and
  4088. { fst can't store an extended/comp value }
  4089. (taicpu(p).opsize <> S_FX) and
  4090. (taicpu(p).opsize <> S_IQ) then
  4091. begin
  4092. if (taicpu(p).opcode = A_FSTP) then
  4093. taicpu(p).opcode := A_FST
  4094. else
  4095. taicpu(p).opcode := A_FIST;
  4096. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  4097. RemoveInstruction(hp1);
  4098. end;
  4099. end;
  4100. end;
  4101. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  4102. var
  4103. hp1, hp2: tai;
  4104. begin
  4105. result:=false;
  4106. if MatchOpType(taicpu(p),top_reg) and
  4107. GetNextInstruction(p, hp1) and
  4108. (hp1.typ = Ait_Instruction) and
  4109. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4110. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  4111. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  4112. { change to
  4113. fld reg fxxx reg,st
  4114. fxxxp st, st1 (hp1)
  4115. Remark: non commutative operations must be reversed!
  4116. }
  4117. begin
  4118. case taicpu(hp1).opcode Of
  4119. A_FMULP,A_FADDP,
  4120. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  4121. begin
  4122. case taicpu(hp1).opcode Of
  4123. A_FADDP: taicpu(hp1).opcode := A_FADD;
  4124. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  4125. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  4126. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  4127. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  4128. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  4129. else
  4130. internalerror(2019050534);
  4131. end;
  4132. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  4133. taicpu(hp1).oper[1]^.reg := NR_ST;
  4134. RemoveCurrentP(p, hp1);
  4135. Result:=true;
  4136. exit;
  4137. end;
  4138. else
  4139. ;
  4140. end;
  4141. end
  4142. else
  4143. if MatchOpType(taicpu(p),top_ref) and
  4144. GetNextInstruction(p, hp2) and
  4145. (hp2.typ = Ait_Instruction) and
  4146. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4147. (taicpu(p).opsize in [S_FS, S_FL]) and
  4148. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  4149. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  4150. if GetLastInstruction(p, hp1) and
  4151. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  4152. MatchOpType(taicpu(hp1),top_ref) and
  4153. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  4154. if ((taicpu(hp2).opcode = A_FMULP) or
  4155. (taicpu(hp2).opcode = A_FADDP)) then
  4156. { change to
  4157. fld/fst mem1 (hp1) fld/fst mem1
  4158. fld mem1 (p) fadd/
  4159. faddp/ fmul st, st
  4160. fmulp st, st1 (hp2) }
  4161. begin
  4162. RemoveCurrentP(p, hp1);
  4163. if (taicpu(hp2).opcode = A_FADDP) then
  4164. taicpu(hp2).opcode := A_FADD
  4165. else
  4166. taicpu(hp2).opcode := A_FMUL;
  4167. taicpu(hp2).oper[1]^.reg := NR_ST;
  4168. end
  4169. else
  4170. { change to
  4171. fld/fst mem1 (hp1) fld/fst mem1
  4172. fld mem1 (p) fld st}
  4173. begin
  4174. taicpu(p).changeopsize(S_FL);
  4175. taicpu(p).loadreg(0,NR_ST);
  4176. end
  4177. else
  4178. begin
  4179. case taicpu(hp2).opcode Of
  4180. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  4181. { change to
  4182. fld/fst mem1 (hp1) fld/fst mem1
  4183. fld mem2 (p) fxxx mem2
  4184. fxxxp st, st1 (hp2) }
  4185. begin
  4186. case taicpu(hp2).opcode Of
  4187. A_FADDP: taicpu(p).opcode := A_FADD;
  4188. A_FMULP: taicpu(p).opcode := A_FMUL;
  4189. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  4190. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  4191. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  4192. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  4193. else
  4194. internalerror(2019050533);
  4195. end;
  4196. RemoveInstruction(hp2);
  4197. end
  4198. else
  4199. ;
  4200. end
  4201. end
  4202. end;
  4203. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  4204. var
  4205. v: TCGInt;
  4206. hp1, hp2: tai;
  4207. FirstMatch: Boolean;
  4208. begin
  4209. Result:=false;
  4210. if taicpu(p).oper[0]^.typ = top_const then
  4211. begin
  4212. { Though GetNextInstruction can be factored out, it is an expensive
  4213. call, so delay calling it until we have first checked cheaper
  4214. conditions that are independent of it. }
  4215. if (taicpu(p).oper[0]^.val = 0) and
  4216. (taicpu(p).oper[1]^.typ = top_reg) and
  4217. GetNextInstruction(p, hp1) and
  4218. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  4219. begin
  4220. hp2 := p;
  4221. FirstMatch := True;
  4222. { When dealing with "cmp $0,%reg", only ZF and SF contain
  4223. anything meaningful once it's converted to "test %reg,%reg";
  4224. additionally, some jumps will always (or never) branch, so
  4225. evaluate every jump immediately following the
  4226. comparison, optimising the conditions if possible.
  4227. Similarly with SETcc... those that are always set to 0 or 1
  4228. are changed to MOV instructions }
  4229. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  4230. (
  4231. GetNextInstruction(hp2, hp1) and
  4232. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  4233. ) do
  4234. begin
  4235. FirstMatch := False;
  4236. case taicpu(hp1).condition of
  4237. C_B, C_C, C_NAE, C_O:
  4238. { For B/NAE:
  4239. Will never branch since an unsigned integer can never be below zero
  4240. For C/O:
  4241. Result cannot overflow because 0 is being subtracted
  4242. }
  4243. begin
  4244. if taicpu(hp1).opcode = A_Jcc then
  4245. begin
  4246. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  4247. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  4248. RemoveInstruction(hp1);
  4249. { Since hp1 was deleted, hp2 must not be updated }
  4250. Continue;
  4251. end
  4252. else
  4253. begin
  4254. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  4255. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  4256. taicpu(hp1).opcode := A_MOV;
  4257. taicpu(hp1).ops := 2;
  4258. taicpu(hp1).condition := C_None;
  4259. taicpu(hp1).opsize := S_B;
  4260. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  4261. taicpu(hp1).loadconst(0, 0);
  4262. end;
  4263. end;
  4264. C_BE, C_NA:
  4265. begin
  4266. { Will only branch if equal to zero }
  4267. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  4268. taicpu(hp1).condition := C_E;
  4269. end;
  4270. C_A, C_NBE:
  4271. begin
  4272. { Will only branch if not equal to zero }
  4273. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  4274. taicpu(hp1).condition := C_NE;
  4275. end;
  4276. C_AE, C_NB, C_NC, C_NO:
  4277. begin
  4278. { Will always branch }
  4279. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  4280. if taicpu(hp1).opcode = A_Jcc then
  4281. begin
  4282. MakeUnconditional(taicpu(hp1));
  4283. { Any jumps/set that follow will now be dead code }
  4284. RemoveDeadCodeAfterJump(taicpu(hp1));
  4285. Break;
  4286. end
  4287. else
  4288. begin
  4289. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  4290. taicpu(hp1).opcode := A_MOV;
  4291. taicpu(hp1).ops := 2;
  4292. taicpu(hp1).condition := C_None;
  4293. taicpu(hp1).opsize := S_B;
  4294. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  4295. taicpu(hp1).loadconst(0, 1);
  4296. end;
  4297. end;
  4298. C_None:
  4299. InternalError(2020012201);
  4300. C_P, C_PE, C_NP, C_PO:
  4301. { We can't handle parity checks and they should never be generated
  4302. after a general-purpose CMP (it's used in some floating-point
  4303. comparisons that don't use CMP) }
  4304. InternalError(2020012202);
  4305. else
  4306. { Zero/Equality, Sign, their complements and all of the
  4307. signed comparisons do not need to be converted };
  4308. end;
  4309. hp2 := hp1;
  4310. end;
  4311. { Convert the instruction to a TEST }
  4312. taicpu(p).opcode := A_TEST;
  4313. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  4314. Result := True;
  4315. Exit;
  4316. end
  4317. else if (taicpu(p).oper[0]^.val = 1) and
  4318. GetNextInstruction(p, hp1) and
  4319. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  4320. (taicpu(hp1).condition in [C_L, C_NGE]) then
  4321. begin
  4322. { Convert; To:
  4323. cmp $1,r/m cmp $0,r/m
  4324. jl @lbl jle @lbl
  4325. }
  4326. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  4327. taicpu(p).oper[0]^.val := 0;
  4328. taicpu(hp1).condition := C_LE;
  4329. { If the instruction is now "cmp $0,%reg", convert it to a
  4330. TEST (and effectively do the work of the "cmp $0,%reg" in
  4331. the block above)
  4332. If it's a reference, we can get away with not setting
  4333. Result to True because he haven't evaluated the jump
  4334. in this pass yet.
  4335. }
  4336. if (taicpu(p).oper[1]^.typ = top_reg) then
  4337. begin
  4338. taicpu(p).opcode := A_TEST;
  4339. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  4340. Result := True;
  4341. end;
  4342. Exit;
  4343. end
  4344. else if (taicpu(p).oper[1]^.typ = top_reg) then
  4345. begin
  4346. { cmp register,$8000 neg register
  4347. je target --> jo target
  4348. .... only if register is deallocated before jump.}
  4349. case Taicpu(p).opsize of
  4350. S_B: v:=$80;
  4351. S_W: v:=$8000;
  4352. S_L: v:=qword($80000000);
  4353. { S_Q will never happen: cmp with 64 bit constants is not possible }
  4354. S_Q:
  4355. Exit;
  4356. else
  4357. internalerror(2013112905);
  4358. end;
  4359. if (taicpu(p).oper[0]^.val=v) and
  4360. GetNextInstruction(p, hp1) and
  4361. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  4362. (Taicpu(hp1).condition in [C_E,C_NE]) then
  4363. begin
  4364. TransferUsedRegs(TmpUsedRegs);
  4365. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  4366. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  4367. begin
  4368. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  4369. Taicpu(p).opcode:=A_NEG;
  4370. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  4371. Taicpu(p).clearop(1);
  4372. Taicpu(p).ops:=1;
  4373. if Taicpu(hp1).condition=C_E then
  4374. Taicpu(hp1).condition:=C_O
  4375. else
  4376. Taicpu(hp1).condition:=C_NO;
  4377. Result:=true;
  4378. exit;
  4379. end;
  4380. end;
  4381. end;
  4382. end;
  4383. if (taicpu(p).oper[1]^.typ = top_reg) and
  4384. GetNextInstruction(p, hp1) and
  4385. MatchInstruction(hp1,A_MOV,[]) and
  4386. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  4387. (
  4388. (taicpu(p).oper[0]^.typ <> top_reg) or
  4389. not RegInInstruction(taicpu(p).oper[0]^.reg, hp1)
  4390. ) then
  4391. begin
  4392. { If we have something like:
  4393. cmp ###,%reg1
  4394. mov 0,%reg2
  4395. And no registers are shared, move the MOV command to before the
  4396. comparison as this means it can be optimised without worrying
  4397. about the FLAGS register. (This combination is generated by
  4398. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  4399. }
  4400. SwapMovCmp(p, hp1);
  4401. Result := True;
  4402. Exit;
  4403. end;
  4404. end;
  4405. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  4406. var
  4407. hp1: tai;
  4408. begin
  4409. {
  4410. remove the second (v)pxor from
  4411. pxor reg,reg
  4412. ...
  4413. pxor reg,reg
  4414. }
  4415. Result:=false;
  4416. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  4417. MatchOpType(taicpu(p),top_reg,top_reg) and
  4418. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  4419. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4420. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  4421. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  4422. begin
  4423. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  4424. RemoveInstruction(hp1);
  4425. Result:=true;
  4426. Exit;
  4427. end
  4428. {
  4429. replace
  4430. pxor reg1,reg1
  4431. movapd/s reg1,reg2
  4432. dealloc reg1
  4433. by
  4434. pxor reg2,reg2
  4435. }
  4436. else if GetNextInstruction(p,hp1) and
  4437. { we mix single and double opperations here because we assume that the compiler
  4438. generates vmovapd only after double operations and vmovaps only after single operations }
  4439. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4440. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  4441. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4442. (taicpu(p).oper[0]^.typ=top_reg) then
  4443. begin
  4444. TransferUsedRegs(TmpUsedRegs);
  4445. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4446. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4447. begin
  4448. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  4449. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4450. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  4451. RemoveInstruction(hp1);
  4452. result:=true;
  4453. end;
  4454. end;
  4455. end;
  4456. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  4457. var
  4458. hp1: tai;
  4459. begin
  4460. {
  4461. remove the second (v)pxor from
  4462. (v)pxor reg,reg
  4463. ...
  4464. (v)pxor reg,reg
  4465. }
  4466. Result:=false;
  4467. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  4468. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  4469. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  4470. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4471. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  4472. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  4473. begin
  4474. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  4475. RemoveInstruction(hp1);
  4476. Result:=true;
  4477. Exit;
  4478. end
  4479. else
  4480. Result:=OptPass1VOP(p);
  4481. end;
  4482. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  4483. var
  4484. hp1 : tai;
  4485. begin
  4486. result:=false;
  4487. { replace
  4488. IMul const,%mreg1,%mreg2
  4489. Mov %reg2,%mreg3
  4490. dealloc %mreg3
  4491. by
  4492. Imul const,%mreg1,%mreg23
  4493. }
  4494. if (taicpu(p).ops=3) and
  4495. GetNextInstruction(p,hp1) and
  4496. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4497. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  4498. (taicpu(hp1).oper[1]^.typ=top_reg) then
  4499. begin
  4500. TransferUsedRegs(TmpUsedRegs);
  4501. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4502. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  4503. begin
  4504. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  4505. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  4506. RemoveInstruction(hp1);
  4507. result:=true;
  4508. end;
  4509. end;
  4510. end;
  4511. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  4512. var
  4513. hp1 : tai;
  4514. begin
  4515. result:=false;
  4516. { replace
  4517. IMul %reg0,%reg1,%reg2
  4518. Mov %reg2,%reg3
  4519. dealloc %reg2
  4520. by
  4521. Imul %reg0,%reg1,%reg3
  4522. }
  4523. if GetNextInstruction(p,hp1) and
  4524. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4525. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  4526. (taicpu(hp1).oper[1]^.typ=top_reg) then
  4527. begin
  4528. TransferUsedRegs(TmpUsedRegs);
  4529. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4530. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  4531. begin
  4532. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  4533. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  4534. RemoveInstruction(hp1);
  4535. result:=true;
  4536. end;
  4537. end;
  4538. end;
  4539. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  4540. var
  4541. hp1, hp2, hp3, hp4, hp5: tai;
  4542. ThisReg: TRegister;
  4543. begin
  4544. Result := False;
  4545. if not GetNextInstruction(p,hp1) or (hp1.typ <> ait_instruction) then
  4546. Exit;
  4547. {
  4548. convert
  4549. j<c> .L1
  4550. mov 1,reg
  4551. jmp .L2
  4552. .L1
  4553. mov 0,reg
  4554. .L2
  4555. into
  4556. mov 0,reg
  4557. set<not(c)> reg
  4558. take care of alignment and that the mov 0,reg is not converted into a xor as this
  4559. would destroy the flag contents
  4560. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  4561. executed at the same time as a previous comparison.
  4562. set<not(c)> reg
  4563. movzx reg, reg
  4564. }
  4565. if MatchInstruction(hp1,A_MOV,[]) and
  4566. (taicpu(hp1).oper[0]^.typ = top_const) and
  4567. (
  4568. (
  4569. (taicpu(hp1).oper[1]^.typ = top_reg)
  4570. {$ifdef i386}
  4571. { Under i386, ESI, EDI, EBP and ESP
  4572. don't have an 8-bit representation }
  4573. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  4574. {$endif i386}
  4575. ) or (
  4576. {$ifdef i386}
  4577. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  4578. {$endif i386}
  4579. (taicpu(hp1).opsize = S_B)
  4580. )
  4581. ) and
  4582. GetNextInstruction(hp1,hp2) and
  4583. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  4584. GetNextInstruction(hp2,hp3) and
  4585. SkipAligns(hp3, hp3) and
  4586. (hp3.typ=ait_label) and
  4587. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  4588. GetNextInstruction(hp3,hp4) and
  4589. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  4590. (taicpu(hp4).oper[0]^.typ = top_const) and
  4591. (
  4592. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  4593. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  4594. ) and
  4595. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  4596. GetNextInstruction(hp4,hp5) and
  4597. SkipAligns(hp5, hp5) and
  4598. (hp5.typ=ait_label) and
  4599. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  4600. begin
  4601. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  4602. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  4603. tai_label(hp3).labsym.DecRefs;
  4604. { If this isn't the only reference to the middle label, we can
  4605. still make a saving - only that the first jump and everything
  4606. that follows will remain. }
  4607. if (tai_label(hp3).labsym.getrefs = 0) then
  4608. begin
  4609. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  4610. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  4611. else
  4612. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  4613. { remove jump, first label and second MOV (also catching any aligns) }
  4614. repeat
  4615. if not GetNextInstruction(hp2, hp3) then
  4616. InternalError(2021040810);
  4617. RemoveInstruction(hp2);
  4618. hp2 := hp3;
  4619. until hp2 = hp5;
  4620. { Don't decrement reference count before the removal loop
  4621. above, otherwise GetNextInstruction won't stop on the
  4622. the label }
  4623. tai_label(hp5).labsym.DecRefs;
  4624. end
  4625. else
  4626. begin
  4627. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  4628. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  4629. else
  4630. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  4631. end;
  4632. taicpu(p).opcode:=A_SETcc;
  4633. taicpu(p).opsize:=S_B;
  4634. taicpu(p).is_jmp:=False;
  4635. if taicpu(hp1).opsize=S_B then
  4636. begin
  4637. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  4638. RemoveInstruction(hp1);
  4639. end
  4640. else
  4641. begin
  4642. { Will be a register because the size can't be S_B otherwise }
  4643. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  4644. taicpu(p).loadreg(0, ThisReg);
  4645. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  4646. begin
  4647. case taicpu(hp1).opsize of
  4648. S_W:
  4649. taicpu(hp1).opsize := S_BW;
  4650. S_L:
  4651. taicpu(hp1).opsize := S_BL;
  4652. {$ifdef x86_64}
  4653. S_Q:
  4654. begin
  4655. taicpu(hp1).opsize := S_BL;
  4656. { Change the destination register to 32-bit }
  4657. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  4658. end;
  4659. {$endif x86_64}
  4660. else
  4661. InternalError(2021040820);
  4662. end;
  4663. taicpu(hp1).opcode := A_MOVZX;
  4664. taicpu(hp1).loadreg(0, ThisReg);
  4665. end
  4666. else
  4667. begin
  4668. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  4669. { hp1 is already a MOV instruction with the correct register }
  4670. taicpu(hp1).loadconst(0, 0);
  4671. { Inserting it right before p will guarantee that the flags are also tracked }
  4672. asml.Remove(hp1);
  4673. asml.InsertBefore(hp1, p);
  4674. end;
  4675. end;
  4676. Result:=true;
  4677. exit;
  4678. end
  4679. end;
  4680. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  4681. var
  4682. hp2, hp3, first_assignment: tai;
  4683. IncCount, OperIdx: Integer;
  4684. OrigLabel: TAsmLabel;
  4685. begin
  4686. Count := 0;
  4687. Result := False;
  4688. first_assignment := nil;
  4689. if (LoopCount >= 20) then
  4690. begin
  4691. { Guard against infinite loops }
  4692. Exit;
  4693. end;
  4694. if (taicpu(p).oper[0]^.typ <> top_ref) or
  4695. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  4696. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  4697. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  4698. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  4699. Exit;
  4700. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  4701. {
  4702. change
  4703. jmp .L1
  4704. ...
  4705. .L1:
  4706. mov ##, ## ( multiple movs possible )
  4707. jmp/ret
  4708. into
  4709. mov ##, ##
  4710. jmp/ret
  4711. }
  4712. if not Assigned(hp1) then
  4713. begin
  4714. hp1 := GetLabelWithSym(OrigLabel);
  4715. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  4716. Exit;
  4717. end;
  4718. hp2 := hp1;
  4719. while Assigned(hp2) do
  4720. begin
  4721. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  4722. SkipLabels(hp2,hp2);
  4723. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  4724. Break;
  4725. case taicpu(hp2).opcode of
  4726. A_MOVSS:
  4727. begin
  4728. if taicpu(hp2).ops = 0 then
  4729. { Wrong MOVSS }
  4730. Break;
  4731. Inc(Count);
  4732. if Count >= 5 then
  4733. { Too many to be worthwhile }
  4734. Break;
  4735. GetNextInstruction(hp2, hp2);
  4736. Continue;
  4737. end;
  4738. A_MOV,
  4739. A_MOVD,
  4740. A_MOVQ,
  4741. A_MOVSX,
  4742. {$ifdef x86_64}
  4743. A_MOVSXD,
  4744. {$endif x86_64}
  4745. A_MOVZX,
  4746. A_MOVAPS,
  4747. A_MOVUPS,
  4748. A_MOVSD,
  4749. A_MOVAPD,
  4750. A_MOVUPD,
  4751. A_MOVDQA,
  4752. A_MOVDQU,
  4753. A_VMOVSS,
  4754. A_VMOVAPS,
  4755. A_VMOVUPS,
  4756. A_VMOVSD,
  4757. A_VMOVAPD,
  4758. A_VMOVUPD,
  4759. A_VMOVDQA,
  4760. A_VMOVDQU:
  4761. begin
  4762. Inc(Count);
  4763. if Count >= 5 then
  4764. { Too many to be worthwhile }
  4765. Break;
  4766. GetNextInstruction(hp2, hp2);
  4767. Continue;
  4768. end;
  4769. A_JMP:
  4770. begin
  4771. { Guard against infinite loops }
  4772. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  4773. Exit;
  4774. { Analyse this jump first in case it also duplicates assignments }
  4775. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  4776. begin
  4777. { Something did change! }
  4778. Result := True;
  4779. Inc(Count, IncCount);
  4780. if Count >= 5 then
  4781. begin
  4782. { Too many to be worthwhile }
  4783. Exit;
  4784. end;
  4785. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  4786. Break;
  4787. end;
  4788. Result := True;
  4789. Break;
  4790. end;
  4791. A_RET:
  4792. begin
  4793. Result := True;
  4794. Break;
  4795. end;
  4796. else
  4797. Break;
  4798. end;
  4799. end;
  4800. if Result then
  4801. begin
  4802. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  4803. if Count = 0 then
  4804. begin
  4805. Result := False;
  4806. Exit;
  4807. end;
  4808. hp3 := p;
  4809. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  4810. while True do
  4811. begin
  4812. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  4813. SkipLabels(hp1,hp1);
  4814. if (hp1.typ <> ait_instruction) then
  4815. InternalError(2021040720);
  4816. case taicpu(hp1).opcode of
  4817. A_JMP:
  4818. begin
  4819. { Change the original jump to the new destination }
  4820. OrigLabel.decrefs;
  4821. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  4822. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  4823. { Set p to the first duplicated assignment so it can get optimised if needs be }
  4824. if not Assigned(first_assignment) then
  4825. InternalError(2021040810)
  4826. else
  4827. p := first_assignment;
  4828. Exit;
  4829. end;
  4830. A_RET:
  4831. begin
  4832. { Now change the jump into a RET instruction }
  4833. ConvertJumpToRET(p, hp1);
  4834. { Set p to the first duplicated assignment so it can get optimised if needs be }
  4835. if not Assigned(first_assignment) then
  4836. InternalError(2021040811)
  4837. else
  4838. p := first_assignment;
  4839. Exit;
  4840. end;
  4841. else
  4842. begin
  4843. { Duplicate the MOV instruction }
  4844. hp3:=tai(hp1.getcopy);
  4845. if first_assignment = nil then
  4846. first_assignment := hp3;
  4847. asml.InsertBefore(hp3, p);
  4848. { Make sure the compiler knows about any final registers written here }
  4849. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  4850. with taicpu(hp3).oper[OperIdx]^ do
  4851. begin
  4852. case typ of
  4853. top_ref:
  4854. begin
  4855. if (ref^.base <> NR_NO) and
  4856. (getsupreg(ref^.base) <> RS_ESP) and
  4857. (getsupreg(ref^.base) <> RS_EBP)
  4858. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  4859. then
  4860. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  4861. if (ref^.index <> NR_NO) and
  4862. (getsupreg(ref^.index) <> RS_ESP) and
  4863. (getsupreg(ref^.index) <> RS_EBP)
  4864. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  4865. (ref^.index <> ref^.base) then
  4866. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  4867. end;
  4868. top_reg:
  4869. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  4870. else
  4871. ;
  4872. end;
  4873. end;
  4874. end;
  4875. end;
  4876. if not GetNextInstruction(hp1, hp1) then
  4877. { Should have dropped out earlier }
  4878. InternalError(2021040710);
  4879. end;
  4880. end;
  4881. end;
  4882. procedure TX86AsmOptimizer.SwapMovCmp(var p, hp1: tai);
  4883. var
  4884. hp2: tai;
  4885. X: Integer;
  4886. begin
  4887. asml.Remove(hp1);
  4888. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  4889. if not GetLastInstruction(p, hp2) then
  4890. asml.InsertBefore(hp1, p)
  4891. else
  4892. asml.InsertAfter(hp1, hp2);
  4893. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and mov instructions to improve optimisation potential', hp1);
  4894. for X := 0 to 1 do
  4895. case taicpu(hp1).oper[X]^.typ of
  4896. top_reg:
  4897. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  4898. top_ref:
  4899. begin
  4900. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  4901. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  4902. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  4903. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  4904. end;
  4905. else
  4906. ;
  4907. end;
  4908. end;
  4909. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  4910. function IsXCHGAcceptable: Boolean; inline;
  4911. begin
  4912. { Always accept if optimising for size }
  4913. Result := (cs_opt_size in current_settings.optimizerswitches) or
  4914. (
  4915. {$ifdef x86_64}
  4916. { XCHG takes 3 cycles on AMD Athlon64 }
  4917. (current_settings.optimizecputype >= cpu_core_i)
  4918. {$else x86_64}
  4919. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  4920. than 3, so it becomes a saving compared to three MOVs with two of
  4921. them able to execute simultaneously. [Kit] }
  4922. (current_settings.optimizecputype >= cpu_PentiumM)
  4923. {$endif x86_64}
  4924. );
  4925. end;
  4926. var
  4927. NewRef: TReference;
  4928. hp1, hp2, hp3, hp4: Tai;
  4929. {$ifndef x86_64}
  4930. OperIdx: Integer;
  4931. {$endif x86_64}
  4932. NewInstr : Taicpu;
  4933. NewAligh : Tai_align;
  4934. DestLabel: TAsmLabel;
  4935. begin
  4936. Result:=false;
  4937. { This optimisation adds an instruction, so only do it for speed }
  4938. if not (cs_opt_size in current_settings.optimizerswitches) and
  4939. MatchOpType(taicpu(p), top_const, top_reg) and
  4940. (taicpu(p).oper[0]^.val = 0) then
  4941. begin
  4942. { To avoid compiler warning }
  4943. DestLabel := nil;
  4944. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  4945. InternalError(2021040750);
  4946. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  4947. Exit;
  4948. case hp1.typ of
  4949. ait_label:
  4950. begin
  4951. { Change:
  4952. mov $0,%reg mov $0,%reg
  4953. @Lbl1: @Lbl1:
  4954. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  4955. je @Lbl2 jne @Lbl2
  4956. To: To:
  4957. mov $0,%reg mov $0,%reg
  4958. jmp @Lbl2 jmp @Lbl3
  4959. (align) (align)
  4960. @Lbl1: @Lbl1:
  4961. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  4962. je @Lbl2 je @Lbl2
  4963. @Lbl3: <-- Only if label exists
  4964. (Not if it's optimised for size)
  4965. }
  4966. if not GetNextInstruction(hp1, hp2) then
  4967. Exit;
  4968. if not (cs_opt_size in current_settings.optimizerswitches) and
  4969. (hp2.typ = ait_instruction) and
  4970. (
  4971. { Register sizes must exactly match }
  4972. (
  4973. (taicpu(hp2).opcode = A_CMP) and
  4974. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  4975. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  4976. ) or (
  4977. (taicpu(hp2).opcode = A_TEST) and
  4978. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  4979. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  4980. )
  4981. ) and GetNextInstruction(hp2, hp3) and
  4982. (hp3.typ = ait_instruction) and
  4983. (taicpu(hp3).opcode = A_JCC) and
  4984. (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
  4985. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  4986. begin
  4987. { Check condition of jump }
  4988. { Always true? }
  4989. if condition_in(C_E, taicpu(hp3).condition) then
  4990. begin
  4991. { Copy label symbol and obtain matching label entry for the
  4992. conditional jump, as this will be our destination}
  4993. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  4994. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  4995. Result := True;
  4996. end
  4997. { Always false? }
  4998. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  4999. begin
  5000. { This is only worth it if there's a jump to take }
  5001. case hp2.typ of
  5002. ait_instruction:
  5003. begin
  5004. if taicpu(hp2).opcode = A_JMP then
  5005. begin
  5006. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  5007. { An unconditional jump follows the conditional jump which will always be false,
  5008. so use this jump's destination for the new jump }
  5009. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  5010. Result := True;
  5011. end
  5012. else if taicpu(hp2).opcode = A_JCC then
  5013. begin
  5014. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  5015. if condition_in(C_E, taicpu(hp2).condition) then
  5016. begin
  5017. { A second conditional jump follows the conditional jump which will always be false,
  5018. while the second jump is always True, so use this jump's destination for the new jump }
  5019. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  5020. Result := True;
  5021. end;
  5022. { Don't risk it if the jump isn't always true (Result remains False) }
  5023. end;
  5024. end;
  5025. else
  5026. { If anything else don't optimise };
  5027. end;
  5028. end;
  5029. if Result then
  5030. begin
  5031. { Just so we have something to insert as a paremeter}
  5032. reference_reset(NewRef, 1, []);
  5033. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  5034. { Now actually load the correct parameter }
  5035. NewInstr.loadsymbol(0, DestLabel, 0);
  5036. { Get instruction before original label (may not be p under -O3) }
  5037. if not GetLastInstruction(hp1, hp2) then
  5038. { Shouldn't fail here }
  5039. InternalError(2021040701);
  5040. DestLabel.increfs;
  5041. AsmL.InsertAfter(NewInstr, hp2);
  5042. { Add new alignment field }
  5043. (* AsmL.InsertAfter(
  5044. cai_align.create_max(
  5045. current_settings.alignment.jumpalign,
  5046. current_settings.alignment.jumpalignskipmax
  5047. ),
  5048. NewInstr
  5049. ); *)
  5050. end;
  5051. Exit;
  5052. end;
  5053. end;
  5054. else
  5055. ;
  5056. end;
  5057. end;
  5058. if not GetNextInstruction(p, hp1) then
  5059. Exit;
  5060. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  5061. begin
  5062. { Sometimes the MOVs that OptPass2JMP produces can be improved
  5063. further, but we can't just put this jump optimisation in pass 1
  5064. because it tends to perform worse when conditional jumps are
  5065. nearby (e.g. when converting CMOV instructions). [Kit] }
  5066. if OptPass2JMP(hp1) then
  5067. { call OptPass1MOV once to potentially merge any MOVs that were created }
  5068. Result := OptPass1MOV(p)
  5069. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  5070. returned True and the instruction is still a MOV, thus checking
  5071. the optimisations below }
  5072. { If OptPass2JMP returned False, no optimisations were done to
  5073. the jump and there are no further optimisations that can be done
  5074. to the MOV instruction on this pass }
  5075. end
  5076. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5077. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  5078. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5079. MatchOpType(taicpu(hp1),top_const,top_reg) and
  5080. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5081. { be lazy, checking separately for sub would be slightly better }
  5082. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  5083. begin
  5084. { Change:
  5085. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  5086. addl/q $x,%reg2 subl/q $x,%reg2
  5087. To:
  5088. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  5089. }
  5090. TransferUsedRegs(TmpUsedRegs);
  5091. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5092. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5093. if not GetNextInstruction(hp1, hp2) or
  5094. (
  5095. { The FLAGS register isn't always tracked properly, so do not
  5096. perform this optimisation if a conditional statement follows }
  5097. not RegReadByInstruction(NR_DEFAULTFLAGS, hp2) and
  5098. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)
  5099. ) then
  5100. begin
  5101. reference_reset(NewRef, 1, []);
  5102. NewRef.base := taicpu(p).oper[0]^.reg;
  5103. NewRef.scalefactor := 1;
  5104. if taicpu(hp1).opcode = A_ADD then
  5105. begin
  5106. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  5107. NewRef.offset := taicpu(hp1).oper[0]^.val;
  5108. end
  5109. else
  5110. begin
  5111. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  5112. NewRef.offset := -taicpu(hp1).oper[0]^.val;
  5113. end;
  5114. taicpu(p).opcode := A_LEA;
  5115. taicpu(p).loadref(0, NewRef);
  5116. RemoveInstruction(hp1);
  5117. Result := True;
  5118. Exit;
  5119. end;
  5120. end
  5121. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5122. {$ifdef x86_64}
  5123. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  5124. {$else x86_64}
  5125. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  5126. {$endif x86_64}
  5127. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5128. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  5129. { mov reg1, reg2 mov reg1, reg2
  5130. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  5131. begin
  5132. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5133. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  5134. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  5135. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  5136. TransferUsedRegs(TmpUsedRegs);
  5137. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5138. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  5139. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  5140. then
  5141. begin
  5142. RemoveCurrentP(p, hp1);
  5143. Result:=true;
  5144. end;
  5145. exit;
  5146. end
  5147. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5148. IsXCHGAcceptable and
  5149. { XCHG doesn't support 8-byte registers }
  5150. (taicpu(p).opsize <> S_B) and
  5151. MatchInstruction(hp1, A_MOV, []) and
  5152. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5153. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  5154. GetNextInstruction(hp1, hp2) and
  5155. MatchInstruction(hp2, A_MOV, []) and
  5156. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  5157. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  5158. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  5159. begin
  5160. { mov %reg1,%reg2
  5161. mov %reg3,%reg1 -> xchg %reg3,%reg1
  5162. mov %reg2,%reg3
  5163. (%reg2 not used afterwards)
  5164. Note that xchg takes 3 cycles to execute, and generally mov's take
  5165. only one cycle apiece, but the first two mov's can be executed in
  5166. parallel, only taking 2 cycles overall. Older processors should
  5167. therefore only optimise for size. [Kit]
  5168. }
  5169. TransferUsedRegs(TmpUsedRegs);
  5170. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5171. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5172. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  5173. begin
  5174. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  5175. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  5176. taicpu(hp1).opcode := A_XCHG;
  5177. RemoveCurrentP(p, hp1);
  5178. RemoveInstruction(hp2);
  5179. Result := True;
  5180. Exit;
  5181. end;
  5182. end
  5183. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5184. MatchInstruction(hp1, A_SAR, []) then
  5185. begin
  5186. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  5187. begin
  5188. { the use of %edx also covers the opsize being S_L }
  5189. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  5190. begin
  5191. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  5192. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  5193. (taicpu(p).oper[1]^.reg = NR_EDX) then
  5194. begin
  5195. { Change:
  5196. movl %eax,%edx
  5197. sarl $31,%edx
  5198. To:
  5199. cltd
  5200. }
  5201. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  5202. RemoveInstruction(hp1);
  5203. taicpu(p).opcode := A_CDQ;
  5204. taicpu(p).opsize := S_NO;
  5205. taicpu(p).clearop(1);
  5206. taicpu(p).clearop(0);
  5207. taicpu(p).ops:=0;
  5208. Result := True;
  5209. end
  5210. else if (cs_opt_size in current_settings.optimizerswitches) and
  5211. (taicpu(p).oper[0]^.reg = NR_EDX) and
  5212. (taicpu(p).oper[1]^.reg = NR_EAX) then
  5213. begin
  5214. { Change:
  5215. movl %edx,%eax
  5216. sarl $31,%edx
  5217. To:
  5218. movl %edx,%eax
  5219. cltd
  5220. Note that this creates a dependency between the two instructions,
  5221. so only perform if optimising for size.
  5222. }
  5223. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  5224. taicpu(hp1).opcode := A_CDQ;
  5225. taicpu(hp1).opsize := S_NO;
  5226. taicpu(hp1).clearop(1);
  5227. taicpu(hp1).clearop(0);
  5228. taicpu(hp1).ops:=0;
  5229. end;
  5230. {$ifndef x86_64}
  5231. end
  5232. { Don't bother if CMOV is supported, because a more optimal
  5233. sequence would have been generated for the Abs() intrinsic }
  5234. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  5235. { the use of %eax also covers the opsize being S_L }
  5236. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  5237. (taicpu(p).oper[0]^.reg = NR_EAX) and
  5238. (taicpu(p).oper[1]^.reg = NR_EDX) and
  5239. GetNextInstruction(hp1, hp2) and
  5240. MatchInstruction(hp2, A_XOR, [S_L]) and
  5241. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  5242. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  5243. GetNextInstruction(hp2, hp3) and
  5244. MatchInstruction(hp3, A_SUB, [S_L]) and
  5245. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  5246. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  5247. begin
  5248. { Change:
  5249. movl %eax,%edx
  5250. sarl $31,%eax
  5251. xorl %eax,%edx
  5252. subl %eax,%edx
  5253. (Instruction that uses %edx)
  5254. (%eax deallocated)
  5255. (%edx deallocated)
  5256. To:
  5257. cltd
  5258. xorl %edx,%eax <-- Note the registers have swapped
  5259. subl %edx,%eax
  5260. (Instruction that uses %eax) <-- %eax rather than %edx
  5261. }
  5262. TransferUsedRegs(TmpUsedRegs);
  5263. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5264. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5265. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5266. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  5267. begin
  5268. if GetNextInstruction(hp3, hp4) and
  5269. not RegModifiedByInstruction(NR_EDX, hp4) and
  5270. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  5271. begin
  5272. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  5273. taicpu(p).opcode := A_CDQ;
  5274. taicpu(p).clearop(1);
  5275. taicpu(p).clearop(0);
  5276. taicpu(p).ops:=0;
  5277. RemoveInstruction(hp1);
  5278. taicpu(hp2).loadreg(0, NR_EDX);
  5279. taicpu(hp2).loadreg(1, NR_EAX);
  5280. taicpu(hp3).loadreg(0, NR_EDX);
  5281. taicpu(hp3).loadreg(1, NR_EAX);
  5282. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  5283. { Convert references in the following instruction (hp4) from %edx to %eax }
  5284. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  5285. with taicpu(hp4).oper[OperIdx]^ do
  5286. case typ of
  5287. top_reg:
  5288. if getsupreg(reg) = RS_EDX then
  5289. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  5290. top_ref:
  5291. begin
  5292. if getsupreg(reg) = RS_EDX then
  5293. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  5294. if getsupreg(reg) = RS_EDX then
  5295. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  5296. end;
  5297. else
  5298. ;
  5299. end;
  5300. end;
  5301. end;
  5302. {$else x86_64}
  5303. end;
  5304. end
  5305. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  5306. { the use of %rdx also covers the opsize being S_Q }
  5307. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  5308. begin
  5309. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  5310. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  5311. (taicpu(p).oper[1]^.reg = NR_RDX) then
  5312. begin
  5313. { Change:
  5314. movq %rax,%rdx
  5315. sarq $63,%rdx
  5316. To:
  5317. cqto
  5318. }
  5319. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  5320. RemoveInstruction(hp1);
  5321. taicpu(p).opcode := A_CQO;
  5322. taicpu(p).opsize := S_NO;
  5323. taicpu(p).clearop(1);
  5324. taicpu(p).clearop(0);
  5325. taicpu(p).ops:=0;
  5326. Result := True;
  5327. end
  5328. else if (cs_opt_size in current_settings.optimizerswitches) and
  5329. (taicpu(p).oper[0]^.reg = NR_RDX) and
  5330. (taicpu(p).oper[1]^.reg = NR_RAX) then
  5331. begin
  5332. { Change:
  5333. movq %rdx,%rax
  5334. sarq $63,%rdx
  5335. To:
  5336. movq %rdx,%rax
  5337. cqto
  5338. Note that this creates a dependency between the two instructions,
  5339. so only perform if optimising for size.
  5340. }
  5341. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  5342. taicpu(hp1).opcode := A_CQO;
  5343. taicpu(hp1).opsize := S_NO;
  5344. taicpu(hp1).clearop(1);
  5345. taicpu(hp1).clearop(0);
  5346. taicpu(hp1).ops:=0;
  5347. {$endif x86_64}
  5348. end;
  5349. end;
  5350. end
  5351. else if MatchInstruction(hp1, A_MOV, []) and
  5352. (taicpu(hp1).oper[1]^.typ = top_reg) then
  5353. { Though "GetNextInstruction" could be factored out, along with
  5354. the instructions that depend on hp2, it is an expensive call that
  5355. should be delayed for as long as possible, hence we do cheaper
  5356. checks first that are likely to be False. [Kit] }
  5357. begin
  5358. if MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  5359. (
  5360. (
  5361. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  5362. (
  5363. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5364. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  5365. )
  5366. ) or
  5367. (
  5368. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  5369. (
  5370. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5371. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  5372. )
  5373. )
  5374. ) and
  5375. GetNextInstruction(hp1, hp2) and
  5376. MatchInstruction(hp2, A_SAR, []) and
  5377. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  5378. begin
  5379. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  5380. begin
  5381. { Change:
  5382. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  5383. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  5384. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  5385. To:
  5386. movl r/m,%eax <- Note the change in register
  5387. cltd
  5388. }
  5389. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  5390. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  5391. taicpu(p).loadreg(1, NR_EAX);
  5392. taicpu(hp1).opcode := A_CDQ;
  5393. taicpu(hp1).clearop(1);
  5394. taicpu(hp1).clearop(0);
  5395. taicpu(hp1).ops:=0;
  5396. RemoveInstruction(hp2);
  5397. (*
  5398. {$ifdef x86_64}
  5399. end
  5400. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  5401. { This code sequence does not get generated - however it might become useful
  5402. if and when 128-bit signed integer types make an appearance, so the code
  5403. is kept here for when it is eventually needed. [Kit] }
  5404. (
  5405. (
  5406. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  5407. (
  5408. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5409. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  5410. )
  5411. ) or
  5412. (
  5413. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  5414. (
  5415. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5416. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  5417. )
  5418. )
  5419. ) and
  5420. GetNextInstruction(hp1, hp2) and
  5421. MatchInstruction(hp2, A_SAR, [S_Q]) and
  5422. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  5423. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  5424. begin
  5425. { Change:
  5426. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  5427. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  5428. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  5429. To:
  5430. movq r/m,%rax <- Note the change in register
  5431. cqto
  5432. }
  5433. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  5434. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  5435. taicpu(p).loadreg(1, NR_RAX);
  5436. taicpu(hp1).opcode := A_CQO;
  5437. taicpu(hp1).clearop(1);
  5438. taicpu(hp1).clearop(0);
  5439. taicpu(hp1).ops:=0;
  5440. RemoveInstruction(hp2);
  5441. {$endif x86_64}
  5442. *)
  5443. end;
  5444. end;
  5445. {$ifdef x86_64}
  5446. end
  5447. else if (taicpu(p).opsize = S_L) and
  5448. (taicpu(p).oper[1]^.typ = top_reg) and
  5449. (
  5450. MatchInstruction(hp1, A_MOV,[]) and
  5451. (taicpu(hp1).opsize = S_L) and
  5452. (taicpu(hp1).oper[1]^.typ = top_reg)
  5453. ) and (
  5454. GetNextInstruction(hp1, hp2) and
  5455. (tai(hp2).typ=ait_instruction) and
  5456. (taicpu(hp2).opsize = S_Q) and
  5457. (
  5458. (
  5459. MatchInstruction(hp2, A_ADD,[]) and
  5460. (taicpu(hp2).opsize = S_Q) and
  5461. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  5462. (
  5463. (
  5464. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  5465. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  5466. ) or (
  5467. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5468. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  5469. )
  5470. )
  5471. ) or (
  5472. MatchInstruction(hp2, A_LEA,[]) and
  5473. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  5474. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  5475. (
  5476. (
  5477. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  5478. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  5479. ) or (
  5480. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5481. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  5482. )
  5483. ) and (
  5484. (
  5485. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  5486. ) or (
  5487. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  5488. )
  5489. )
  5490. )
  5491. )
  5492. ) and (
  5493. GetNextInstruction(hp2, hp3) and
  5494. MatchInstruction(hp3, A_SHR,[]) and
  5495. (taicpu(hp3).opsize = S_Q) and
  5496. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  5497. (taicpu(hp3).oper[0]^.val = 1) and
  5498. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  5499. ) then
  5500. begin
  5501. { Change movl x, reg1d movl x, reg1d
  5502. movl y, reg2d movl y, reg2d
  5503. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  5504. shrq $1, reg1q shrq $1, reg1q
  5505. ( reg1d and reg2d can be switched around in the first two instructions )
  5506. To movl x, reg1d
  5507. addl y, reg1d
  5508. rcrl $1, reg1d
  5509. This corresponds to the common expression (x + y) shr 1, where
  5510. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  5511. smaller code, but won't account for x + y causing an overflow). [Kit]
  5512. }
  5513. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  5514. { Change first MOV command to have the same register as the final output }
  5515. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  5516. else
  5517. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  5518. { Change second MOV command to an ADD command. This is easier than
  5519. converting the existing command because it means we don't have to
  5520. touch 'y', which might be a complicated reference, and also the
  5521. fact that the third command might either be ADD or LEA. [Kit] }
  5522. taicpu(hp1).opcode := A_ADD;
  5523. { Delete old ADD/LEA instruction }
  5524. RemoveInstruction(hp2);
  5525. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  5526. taicpu(hp3).opcode := A_RCR;
  5527. taicpu(hp3).changeopsize(S_L);
  5528. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  5529. {$endif x86_64}
  5530. end;
  5531. end;
  5532. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  5533. var
  5534. ThisReg: TRegister;
  5535. MinSize, MaxSize, TrySmaller, TargetSize: TOpSize;
  5536. TargetSubReg: TSubRegister;
  5537. hp1, hp2: tai;
  5538. RegInUse, RegChanged, p_removed: Boolean;
  5539. { Store list of found instructions so we don't have to call
  5540. GetNextInstructionUsingReg multiple times }
  5541. InstrList: array of taicpu;
  5542. InstrMax, Index: Integer;
  5543. UpperLimit, TrySmallerLimit: TCgInt;
  5544. PreMessage: string;
  5545. { Data flow analysis }
  5546. TestValMin, TestValMax: TCgInt;
  5547. SmallerOverflow: Boolean;
  5548. begin
  5549. Result := False;
  5550. p_removed := False;
  5551. { This is anything but quick! }
  5552. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  5553. Exit;
  5554. SetLength(InstrList, 0);
  5555. InstrMax := -1;
  5556. ThisReg := taicpu(p).oper[1]^.reg;
  5557. case taicpu(p).opsize of
  5558. S_BW, S_BL:
  5559. begin
  5560. {$if defined(i386) or defined(i8086)}
  5561. { If the target size is 8-bit, make sure we can actually encode it }
  5562. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  5563. Exit;
  5564. {$endif i386 or i8086}
  5565. UpperLimit := $FF;
  5566. MinSize := S_B;
  5567. if taicpu(p).opsize = S_BW then
  5568. MaxSize := S_W
  5569. else
  5570. MaxSize := S_L;
  5571. end;
  5572. S_WL:
  5573. begin
  5574. UpperLimit := $FFFF;
  5575. MinSize := S_W;
  5576. MaxSize := S_L;
  5577. end
  5578. else
  5579. InternalError(2020112301);
  5580. end;
  5581. TestValMin := 0;
  5582. TestValMax := UpperLimit;
  5583. TrySmallerLimit := UpperLimit;
  5584. TrySmaller := S_NO;
  5585. SmallerOverflow := False;
  5586. RegChanged := False;
  5587. hp1 := p;
  5588. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  5589. (hp1.typ = ait_instruction) and
  5590. (
  5591. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  5592. instruction that doesn't actually contain ThisReg }
  5593. (cs_opt_level3 in current_settings.optimizerswitches) or
  5594. RegInInstruction(ThisReg, hp1)
  5595. ) do
  5596. begin
  5597. case taicpu(hp1).opcode of
  5598. A_INC,A_DEC:
  5599. begin
  5600. { Has to be an exact match on the register }
  5601. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  5602. Break;
  5603. if taicpu(hp1).opcode = A_INC then
  5604. begin
  5605. Inc(TestValMin);
  5606. Inc(TestValMax);
  5607. end
  5608. else
  5609. begin
  5610. Dec(TestValMin);
  5611. Dec(TestValMax);
  5612. end;
  5613. end;
  5614. A_CMP:
  5615. begin
  5616. if (taicpu(hp1).oper[1]^.typ <> top_reg) or
  5617. { Has to be an exact match on the register }
  5618. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  5619. (taicpu(hp1).oper[0]^.typ <> top_const) or
  5620. { Make sure the comparison value is not smaller than the
  5621. smallest allowed signed value for the minimum size (e.g.
  5622. -128 for 8-bit) }
  5623. not (
  5624. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  5625. { Is it in the negative range? }
  5626. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  5627. ) then
  5628. Break;
  5629. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  5630. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  5631. if (TestValMin < TrySmallerLimit) or (TestValMax < TrySmallerLimit) or
  5632. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  5633. { Overflow }
  5634. Break;
  5635. { Check to see if the active register is used afterwards }
  5636. TransferUsedRegs(TmpUsedRegs);
  5637. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  5638. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  5639. begin
  5640. case MinSize of
  5641. S_B:
  5642. TargetSubReg := R_SUBL;
  5643. S_W:
  5644. TargetSubReg := R_SUBW;
  5645. else
  5646. InternalError(2021051002);
  5647. end;
  5648. { Update the register to its new size }
  5649. setsubreg(ThisReg, TargetSubReg);
  5650. taicpu(hp1).oper[1]^.reg := ThisReg;
  5651. taicpu(hp1).opsize := MinSize;
  5652. { Convert the input MOVZX to a MOV }
  5653. if (taicpu(p).oper[0]^.typ = top_reg) and
  5654. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  5655. begin
  5656. { Or remove it completely! }
  5657. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  5658. RemoveCurrentP(p);
  5659. p_removed := True;
  5660. end
  5661. else
  5662. begin
  5663. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  5664. taicpu(p).opcode := A_MOV;
  5665. taicpu(p).oper[1]^.reg := ThisReg;
  5666. taicpu(p).opsize := MinSize;
  5667. end;
  5668. if (InstrMax >= 0) then
  5669. begin
  5670. for Index := 0 to InstrMax do
  5671. begin
  5672. { If p_removed is true, then the original MOV/Z was removed
  5673. and removing the AND instruction may not be safe if it
  5674. appears first }
  5675. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  5676. InternalError(2020112311);
  5677. if InstrList[Index].oper[0]^.typ = top_reg then
  5678. InstrList[Index].oper[0]^.reg := ThisReg;
  5679. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  5680. InstrList[Index].opsize := MinSize;
  5681. end;
  5682. end;
  5683. Result := True;
  5684. Exit;
  5685. end;
  5686. end;
  5687. { OR and XOR are not included because they can too easily fool
  5688. the data flow analysis (they can cause non-linear behaviour) }
  5689. A_ADD,A_SUB,A_AND,A_SHL,A_SHR:
  5690. begin
  5691. if
  5692. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  5693. { Has to be an exact match on the register }
  5694. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  5695. (
  5696. (
  5697. (taicpu(hp1).oper[0]^.typ = top_const) and
  5698. (
  5699. (
  5700. (taicpu(hp1).opcode = A_SHL) and
  5701. (
  5702. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  5703. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  5704. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  5705. )
  5706. ) or (
  5707. (taicpu(hp1).opcode <> A_SHL) and
  5708. (
  5709. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  5710. { Is it in the negative range? }
  5711. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  5712. )
  5713. )
  5714. )
  5715. ) or (
  5716. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  5717. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  5718. )
  5719. ) then
  5720. Break;
  5721. case taicpu(hp1).opcode of
  5722. A_ADD:
  5723. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  5724. begin
  5725. TestValMin := TestValMin * 2;
  5726. TestValMax := TestValMax * 2;
  5727. end
  5728. else
  5729. begin
  5730. TestValMin := TestValMin + taicpu(hp1).oper[0]^.val;
  5731. TestValMax := TestValMax + taicpu(hp1).oper[0]^.val;
  5732. end;
  5733. A_SUB:
  5734. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  5735. begin
  5736. TestValMin := 0;
  5737. TestValMax := 0;
  5738. end
  5739. else
  5740. begin
  5741. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  5742. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  5743. end;
  5744. A_AND:
  5745. if (taicpu(hp1).oper[0]^.typ = top_const) then
  5746. begin
  5747. { we might be able to go smaller if AND appears first }
  5748. if InstrMax = -1 then
  5749. case MinSize of
  5750. S_B:
  5751. ;
  5752. S_W:
  5753. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  5754. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  5755. begin
  5756. TrySmaller := S_B;
  5757. TrySmallerLimit := $FF;
  5758. end;
  5759. S_L:
  5760. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  5761. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  5762. begin
  5763. TrySmaller := S_B;
  5764. TrySmallerLimit := $FF;
  5765. end
  5766. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  5767. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  5768. begin
  5769. TrySmaller := S_W;
  5770. TrySmallerLimit := $FFFF;
  5771. end;
  5772. else
  5773. InternalError(2020112320);
  5774. end;
  5775. TestValMin := TestValMin and taicpu(hp1).oper[0]^.val;
  5776. TestValMax := TestValMax and taicpu(hp1).oper[0]^.val;
  5777. end;
  5778. A_SHL:
  5779. begin
  5780. TestValMin := TestValMin shl taicpu(hp1).oper[0]^.val;
  5781. TestValMax := TestValMax shl taicpu(hp1).oper[0]^.val;
  5782. end;
  5783. A_SHR:
  5784. begin
  5785. { we might be able to go smaller if SHR appears first }
  5786. if InstrMax = -1 then
  5787. case MinSize of
  5788. S_B:
  5789. ;
  5790. S_W:
  5791. if (taicpu(hp1).oper[0]^.val >= 8) then
  5792. begin
  5793. TrySmaller := S_B;
  5794. TrySmallerLimit := $FF;
  5795. end;
  5796. S_L:
  5797. if (taicpu(hp1).oper[0]^.val >= 24) then
  5798. begin
  5799. TrySmaller := S_B;
  5800. TrySmallerLimit := $FF;
  5801. end
  5802. else if (taicpu(hp1).oper[0]^.val >= 16) then
  5803. begin
  5804. TrySmaller := S_W;
  5805. TrySmallerLimit := $FFFF;
  5806. end;
  5807. else
  5808. InternalError(2020112321);
  5809. end;
  5810. TestValMin := TestValMin shr taicpu(hp1).oper[0]^.val;
  5811. TestValMax := TestValMax shr taicpu(hp1).oper[0]^.val;
  5812. end;
  5813. else
  5814. InternalError(2020112303);
  5815. end;
  5816. end;
  5817. (*
  5818. A_IMUL:
  5819. case taicpu(hp1).ops of
  5820. 2:
  5821. begin
  5822. if not MatchOpType(hp1, top_reg, top_reg) or
  5823. { Has to be an exact match on the register }
  5824. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  5825. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  5826. Break;
  5827. TestValMin := TestValMin * TestValMin;
  5828. TestValMax := TestValMax * TestValMax;
  5829. end;
  5830. 3:
  5831. begin
  5832. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  5833. { Has to be an exact match on the register }
  5834. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  5835. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  5836. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  5837. { Is it in the negative range? }
  5838. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  5839. Break;
  5840. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  5841. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  5842. end;
  5843. else
  5844. Break;
  5845. end;
  5846. A_IDIV:
  5847. case taicpu(hp1).ops of
  5848. 3:
  5849. begin
  5850. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  5851. { Has to be an exact match on the register }
  5852. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  5853. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  5854. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  5855. { Is it in the negative range? }
  5856. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  5857. Break;
  5858. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  5859. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  5860. end;
  5861. else
  5862. Break;
  5863. end;
  5864. *)
  5865. A_MOVZX:
  5866. begin
  5867. if not MatchOpType(taicpu(hp1), top_reg, top_reg) then
  5868. Break;
  5869. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  5870. begin
  5871. { Because hp1 was obtained via GetNextInstructionUsingReg
  5872. and ThisReg doesn't appear in the first operand, it
  5873. must appear in the second operand and hence gets
  5874. overwritten }
  5875. if (InstrMax = -1) and
  5876. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  5877. begin
  5878. { The two MOVZX instructions are adjacent, so remove the first one }
  5879. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  5880. RemoveCurrentP(p);
  5881. Result := True;
  5882. Exit;
  5883. end;
  5884. Break;
  5885. end;
  5886. { The objective here is to try to find a combination that
  5887. removes one of the MOV/Z instructions. }
  5888. case taicpu(hp1).opsize of
  5889. S_WL:
  5890. if (MinSize in [S_B, S_W]) then
  5891. begin
  5892. TargetSize := S_L;
  5893. TargetSubReg := R_SUBD;
  5894. end
  5895. else if ((TrySmaller in [S_B, S_W]) and not SmallerOverflow) then
  5896. begin
  5897. TargetSize := TrySmaller;
  5898. if TrySmaller = S_B then
  5899. TargetSubReg := R_SUBL
  5900. else
  5901. TargetSubReg := R_SUBW;
  5902. end
  5903. else
  5904. Break;
  5905. S_BW:
  5906. if (MinSize in [S_B, S_W]) then
  5907. begin
  5908. TargetSize := S_W;
  5909. TargetSubReg := R_SUBW;
  5910. end
  5911. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  5912. begin
  5913. TargetSize := S_B;
  5914. TargetSubReg := R_SUBL;
  5915. end
  5916. else
  5917. Break;
  5918. S_BL:
  5919. if (MinSize in [S_B, S_W]) then
  5920. begin
  5921. TargetSize := S_L;
  5922. TargetSubReg := R_SUBD;
  5923. end
  5924. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  5925. begin
  5926. TargetSize := S_B;
  5927. TargetSubReg := R_SUBL;
  5928. end
  5929. else
  5930. Break;
  5931. else
  5932. InternalError(2020112302);
  5933. end;
  5934. { Update the register to its new size }
  5935. setsubreg(ThisReg, TargetSubReg);
  5936. if TargetSize = MinSize then
  5937. begin
  5938. { Convert the input MOVZX to a MOV }
  5939. if (taicpu(p).oper[0]^.typ = top_reg) and
  5940. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  5941. begin
  5942. { Or remove it completely! }
  5943. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  5944. RemoveCurrentP(p);
  5945. p_removed := True;
  5946. end
  5947. else
  5948. begin
  5949. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  5950. taicpu(p).opcode := A_MOV;
  5951. taicpu(p).oper[1]^.reg := ThisReg;
  5952. taicpu(p).opsize := TargetSize;
  5953. end;
  5954. Result := True;
  5955. end
  5956. else if TargetSize <> MaxSize then
  5957. begin
  5958. case MaxSize of
  5959. S_L:
  5960. if TargetSize = S_W then
  5961. begin
  5962. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  5963. taicpu(p).opsize := S_BW;
  5964. taicpu(p).oper[1]^.reg := ThisReg;
  5965. Result := True;
  5966. end
  5967. else
  5968. InternalError(2020112341);
  5969. S_W:
  5970. if TargetSize = S_L then
  5971. begin
  5972. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  5973. taicpu(p).opsize := S_BL;
  5974. taicpu(p).oper[1]^.reg := ThisReg;
  5975. Result := True;
  5976. end
  5977. else
  5978. InternalError(2020112342);
  5979. else
  5980. ;
  5981. end;
  5982. end;
  5983. if (MaxSize = TargetSize) or
  5984. ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  5985. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  5986. begin
  5987. { Convert the output MOVZX to a MOV }
  5988. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  5989. begin
  5990. { Or remove it completely! }
  5991. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  5992. { Be careful; if p = hp1 and p was also removed, p
  5993. will become a dangling pointer }
  5994. if p = hp1 then
  5995. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  5996. else
  5997. RemoveInstruction(hp1);
  5998. end
  5999. else
  6000. begin
  6001. taicpu(hp1).opcode := A_MOV;
  6002. taicpu(hp1).oper[0]^.reg := ThisReg;
  6003. taicpu(hp1).opsize := TargetSize;
  6004. { Check to see if the active register is used afterwards;
  6005. if not, we can change it and make a saving. }
  6006. RegInUse := False;
  6007. TransferUsedRegs(TmpUsedRegs);
  6008. { The target register may be marked as in use to cross
  6009. a jump to a distant label, so exclude it }
  6010. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  6011. hp2 := p;
  6012. repeat
  6013. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6014. { Explicitly check for the excluded register (don't include the first
  6015. instruction as it may be reading from here }
  6016. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  6017. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  6018. begin
  6019. RegInUse := True;
  6020. Break;
  6021. end;
  6022. if not GetNextInstruction(hp2, hp2) then
  6023. InternalError(2020112340);
  6024. until (hp2 = hp1);
  6025. if not RegInUse and not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  6026. begin
  6027. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  6028. ThisReg := taicpu(hp1).oper[1]^.reg;
  6029. RegChanged := True;
  6030. TransferUsedRegs(TmpUsedRegs);
  6031. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  6032. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  6033. if p = hp1 then
  6034. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  6035. else
  6036. RemoveInstruction(hp1);
  6037. { Instruction will become "mov %reg,%reg" }
  6038. if not p_removed and (taicpu(p).opcode = A_MOV) and
  6039. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  6040. begin
  6041. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  6042. RemoveCurrentP(p);
  6043. p_removed := True;
  6044. end
  6045. else
  6046. taicpu(p).oper[1]^.reg := ThisReg;
  6047. Result := True;
  6048. end
  6049. else
  6050. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  6051. end;
  6052. end
  6053. else
  6054. InternalError(2020112330);
  6055. { Now go through every instruction we found and change the
  6056. size. If TargetSize = MaxSize, then almost no changes are
  6057. needed and Result can remain False if it hasn't been set
  6058. yet.
  6059. If RegChanged is True, then the register requires changing
  6060. and so the point about TargetSize = MaxSize doesn't apply. }
  6061. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  6062. begin
  6063. for Index := 0 to InstrMax do
  6064. begin
  6065. { If p_removed is true, then the original MOV/Z was removed
  6066. and removing the AND instruction may not be safe if it
  6067. appears first }
  6068. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  6069. InternalError(2020112310);
  6070. if InstrList[Index].oper[0]^.typ = top_reg then
  6071. InstrList[Index].oper[0]^.reg := ThisReg;
  6072. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  6073. InstrList[Index].opsize := TargetSize;
  6074. end;
  6075. Result := True;
  6076. end;
  6077. Exit;
  6078. end;
  6079. else
  6080. { This includes ADC, SBB, IDIV and SAR }
  6081. Break;
  6082. end;
  6083. if (TestValMin < 0) or (TestValMax < 0) or
  6084. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  6085. { Overflow }
  6086. Break
  6087. else if not SmallerOverflow and (TrySmaller <> S_NO) and
  6088. ((TestValMin > TrySmallerLimit) or (TestValMax > TrySmallerLimit)) then
  6089. SmallerOverflow := True;
  6090. { Contains highest index (so instruction count - 1) }
  6091. Inc(InstrMax);
  6092. if InstrMax > High(InstrList) then
  6093. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  6094. InstrList[InstrMax] := taicpu(hp1);
  6095. end;
  6096. end;
  6097. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  6098. var
  6099. hp1 : tai;
  6100. begin
  6101. Result:=false;
  6102. if (taicpu(p).ops >= 2) and
  6103. ((taicpu(p).oper[0]^.typ = top_const) or
  6104. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  6105. (taicpu(p).oper[1]^.typ = top_reg) and
  6106. ((taicpu(p).ops = 2) or
  6107. ((taicpu(p).oper[2]^.typ = top_reg) and
  6108. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  6109. GetLastInstruction(p,hp1) and
  6110. MatchInstruction(hp1,A_MOV,[]) and
  6111. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6112. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  6113. begin
  6114. TransferUsedRegs(TmpUsedRegs);
  6115. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  6116. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  6117. { change
  6118. mov reg1,reg2
  6119. imul y,reg2 to imul y,reg1,reg2 }
  6120. begin
  6121. taicpu(p).ops := 3;
  6122. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  6123. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6124. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  6125. RemoveInstruction(hp1);
  6126. result:=true;
  6127. end;
  6128. end;
  6129. end;
  6130. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  6131. var
  6132. ThisLabel: TAsmLabel;
  6133. begin
  6134. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  6135. ThisLabel.decrefs;
  6136. taicpu(p).opcode := A_RET;
  6137. taicpu(p).is_jmp := false;
  6138. taicpu(p).ops := taicpu(ret_p).ops;
  6139. case taicpu(ret_p).ops of
  6140. 0:
  6141. taicpu(p).clearop(0);
  6142. 1:
  6143. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  6144. else
  6145. internalerror(2016041301);
  6146. end;
  6147. { If the original label is now dead, it might turn out that the label
  6148. immediately follows p. As a result, everything beyond it, which will
  6149. be just some final register configuration and a RET instruction, is
  6150. now dead code. [Kit] }
  6151. { NOTE: This is much faster than introducing a OptPass2RET routine and
  6152. running RemoveDeadCodeAfterJump for each RET instruction, because
  6153. this optimisation rarely happens and most RETs appear at the end of
  6154. routines where there is nothing that can be stripped. [Kit] }
  6155. if not ThisLabel.is_used then
  6156. RemoveDeadCodeAfterJump(p);
  6157. end;
  6158. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  6159. var
  6160. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  6161. Unconditional, PotentialModified: Boolean;
  6162. OperPtr: POper;
  6163. NewRef: TReference;
  6164. InstrList: array of taicpu;
  6165. InstrMax, Index: Integer;
  6166. const
  6167. {$ifdef DEBUG_AOPTCPU}
  6168. SNoFlags: shortstring = ' so the flags aren''t modified';
  6169. {$else DEBUG_AOPTCPU}
  6170. SNoFlags = '';
  6171. {$endif DEBUG_AOPTCPU}
  6172. begin
  6173. Result:=false;
  6174. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  6175. begin
  6176. if MatchInstruction(hp1, A_TEST, [S_B]) and
  6177. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6178. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  6179. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  6180. GetNextInstruction(hp1, hp2) and
  6181. MatchInstruction(hp2, A_Jcc, []) then
  6182. { Change from: To:
  6183. set(C) %reg j(~C) label
  6184. test %reg,%reg/cmp $0,%reg
  6185. je label
  6186. set(C) %reg j(C) label
  6187. test %reg,%reg/cmp $0,%reg
  6188. jne label
  6189. }
  6190. begin
  6191. { Before we do anything else, we need to check the instructions
  6192. in between SETcc and TEST to make sure they don't modify the
  6193. FLAGS register - if -O2 or under, there won't be any
  6194. instructions between SET and TEST }
  6195. TransferUsedRegs(TmpUsedRegs);
  6196. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6197. if (cs_opt_level3 in current_settings.optimizerswitches) then
  6198. begin
  6199. next := p;
  6200. SetLength(InstrList, 0);
  6201. InstrMax := -1;
  6202. PotentialModified := False;
  6203. { Make a note of every instruction that modifies the FLAGS
  6204. register }
  6205. while GetNextInstruction(next, next) and (next <> hp1) do
  6206. begin
  6207. if next.typ <> ait_instruction then
  6208. { GetNextInstructionUsingReg should have returned False }
  6209. InternalError(2021051701);
  6210. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  6211. begin
  6212. case taicpu(next).opcode of
  6213. A_SETcc,
  6214. A_CMOVcc,
  6215. A_Jcc:
  6216. begin
  6217. if PotentialModified then
  6218. { Not safe because the flags were modified earlier }
  6219. Exit
  6220. else
  6221. { Condition is the same as the initial SETcc, so this is safe
  6222. (don't add to instruction list though) }
  6223. Continue;
  6224. end;
  6225. A_ADD:
  6226. begin
  6227. if (taicpu(next).opsize = S_B) or
  6228. { LEA doesn't support 8-bit operands }
  6229. (taicpu(next).oper[1]^.typ <> top_reg) or
  6230. { Must write to a register }
  6231. (taicpu(next).oper[0]^.typ = top_ref) then
  6232. { Require a constant or a register }
  6233. Exit;
  6234. PotentialModified := True;
  6235. end;
  6236. A_SUB:
  6237. begin
  6238. if (taicpu(next).opsize = S_B) or
  6239. { LEA doesn't support 8-bit operands }
  6240. (taicpu(next).oper[1]^.typ <> top_reg) or
  6241. { Must write to a register }
  6242. (taicpu(next).oper[0]^.typ <> top_const) or
  6243. (taicpu(next).oper[0]^.val = $80000000) then
  6244. { Can't subtract a register with LEA - also
  6245. check that the value isn't -2^31, as this
  6246. can't be negated }
  6247. Exit;
  6248. PotentialModified := True;
  6249. end;
  6250. A_SAL,
  6251. A_SHL:
  6252. begin
  6253. if (taicpu(next).opsize = S_B) or
  6254. { LEA doesn't support 8-bit operands }
  6255. (taicpu(next).oper[1]^.typ <> top_reg) or
  6256. { Must write to a register }
  6257. (taicpu(next).oper[0]^.typ <> top_const) or
  6258. (taicpu(next).oper[0]^.val < 0) or
  6259. (taicpu(next).oper[0]^.val > 3) then
  6260. Exit;
  6261. PotentialModified := True;
  6262. end;
  6263. A_IMUL:
  6264. begin
  6265. if (taicpu(next).ops <> 3) or
  6266. (taicpu(next).oper[1]^.typ <> top_reg) or
  6267. { Must write to a register }
  6268. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  6269. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  6270. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  6271. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  6272. Exit
  6273. else
  6274. PotentialModified := True;
  6275. end;
  6276. else
  6277. { Don't know how to change this, so abort }
  6278. Exit;
  6279. end;
  6280. { Contains highest index (so instruction count - 1) }
  6281. Inc(InstrMax);
  6282. if InstrMax > High(InstrList) then
  6283. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  6284. InstrList[InstrMax] := taicpu(next);
  6285. end;
  6286. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  6287. end;
  6288. if not Assigned(next) or (next <> hp1) then
  6289. { It should be equal to hp1 }
  6290. InternalError(2021051702);
  6291. { Cycle through each instruction and check to see if we can
  6292. change them to versions that don't modify the flags }
  6293. if (InstrMax >= 0) then
  6294. begin
  6295. for Index := 0 to InstrMax do
  6296. case InstrList[Index].opcode of
  6297. A_ADD:
  6298. begin
  6299. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  6300. InstrList[Index].opcode := A_LEA;
  6301. reference_reset(NewRef, 1, []);
  6302. NewRef.base := InstrList[Index].oper[1]^.reg;
  6303. if InstrList[Index].oper[0]^.typ = top_reg then
  6304. begin
  6305. NewRef.index := InstrList[Index].oper[0]^.reg;
  6306. NewRef.scalefactor := 1;
  6307. end
  6308. else
  6309. NewRef.offset := InstrList[Index].oper[0]^.val;
  6310. InstrList[Index].loadref(0, NewRef);
  6311. end;
  6312. A_SUB:
  6313. begin
  6314. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  6315. InstrList[Index].opcode := A_LEA;
  6316. reference_reset(NewRef, 1, []);
  6317. NewRef.base := InstrList[Index].oper[1]^.reg;
  6318. NewRef.offset := -InstrList[Index].oper[0]^.val;
  6319. InstrList[Index].loadref(0, NewRef);
  6320. end;
  6321. A_SHL,
  6322. A_SAL:
  6323. begin
  6324. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  6325. InstrList[Index].opcode := A_LEA;
  6326. reference_reset(NewRef, 1, []);
  6327. NewRef.index := InstrList[Index].oper[1]^.reg;
  6328. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  6329. InstrList[Index].loadref(0, NewRef);
  6330. end;
  6331. A_IMUL:
  6332. begin
  6333. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  6334. InstrList[Index].opcode := A_LEA;
  6335. reference_reset(NewRef, 1, []);
  6336. NewRef.index := InstrList[Index].oper[1]^.reg;
  6337. case InstrList[Index].oper[0]^.val of
  6338. 2, 4, 8:
  6339. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  6340. else {3, 5 and 9}
  6341. begin
  6342. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  6343. NewRef.base := InstrList[Index].oper[1]^.reg;
  6344. end;
  6345. end;
  6346. InstrList[Index].loadref(0, NewRef);
  6347. end;
  6348. else
  6349. InternalError(2021051710);
  6350. end;
  6351. end;
  6352. { Mark the FLAGS register as used across this whole block }
  6353. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  6354. end;
  6355. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6356. JumpC := taicpu(hp2).condition;
  6357. Unconditional := False;
  6358. if conditions_equal(JumpC, C_E) then
  6359. SetC := inverse_cond(taicpu(p).condition)
  6360. else if conditions_equal(JumpC, C_NE) then
  6361. SetC := taicpu(p).condition
  6362. else
  6363. { We've got something weird here (and inefficent) }
  6364. begin
  6365. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  6366. SetC := C_NONE;
  6367. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  6368. if condition_in(C_AE, JumpC) then
  6369. Unconditional := True
  6370. else
  6371. { Not sure what to do with this jump - drop out }
  6372. Exit;
  6373. end;
  6374. RemoveInstruction(hp1);
  6375. if Unconditional then
  6376. MakeUnconditional(taicpu(hp2))
  6377. else
  6378. begin
  6379. if SetC = C_NONE then
  6380. InternalError(2018061402);
  6381. taicpu(hp2).SetCondition(SetC);
  6382. end;
  6383. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  6384. TmpUsedRegs }
  6385. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  6386. begin
  6387. RemoveCurrentp(p, hp2);
  6388. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  6389. end
  6390. else
  6391. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  6392. Result := True;
  6393. end
  6394. else if
  6395. { Make sure the instructions are adjacent }
  6396. (
  6397. not (cs_opt_level3 in current_settings.optimizerswitches) or
  6398. GetNextInstruction(p, hp1)
  6399. ) and
  6400. MatchInstruction(hp1, A_MOV, [S_B]) and
  6401. { Writing to memory is allowed }
  6402. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  6403. begin
  6404. {
  6405. Watch out for sequences such as:
  6406. set(c)b %regb
  6407. movb %regb,(ref)
  6408. movb $0,1(ref)
  6409. movb $0,2(ref)
  6410. movb $0,3(ref)
  6411. Much more efficient to turn it into:
  6412. movl $0,%regl
  6413. set(c)b %regb
  6414. movl %regl,(ref)
  6415. Or:
  6416. set(c)b %regb
  6417. movzbl %regb,%regl
  6418. movl %regl,(ref)
  6419. }
  6420. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  6421. GetNextInstruction(hp1, hp2) and
  6422. MatchInstruction(hp2, A_MOV, [S_B]) and
  6423. (taicpu(hp2).oper[1]^.typ = top_ref) and
  6424. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  6425. begin
  6426. { Don't do anything else except set Result to True }
  6427. end
  6428. else
  6429. begin
  6430. if taicpu(p).oper[0]^.typ = top_reg then
  6431. begin
  6432. TransferUsedRegs(TmpUsedRegs);
  6433. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6434. end;
  6435. { If it's not a register, it's a memory address }
  6436. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  6437. begin
  6438. { Even if the register is still in use, we can minimise the
  6439. pipeline stall by changing the MOV into another SETcc. }
  6440. taicpu(hp1).opcode := A_SETcc;
  6441. taicpu(hp1).condition := taicpu(p).condition;
  6442. if taicpu(hp1).oper[1]^.typ = top_ref then
  6443. begin
  6444. { Swapping the operand pointers like this is probably a
  6445. bit naughty, but it is far faster than using loadoper
  6446. to transfer the reference from oper[1] to oper[0] if
  6447. you take into account the extra procedure calls and
  6448. the memory allocation and deallocation required }
  6449. OperPtr := taicpu(hp1).oper[1];
  6450. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  6451. taicpu(hp1).oper[0] := OperPtr;
  6452. end
  6453. else
  6454. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  6455. taicpu(hp1).clearop(1);
  6456. taicpu(hp1).ops := 1;
  6457. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  6458. end
  6459. else
  6460. begin
  6461. if taicpu(hp1).oper[1]^.typ = top_reg then
  6462. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  6463. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6464. RemoveInstruction(hp1);
  6465. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  6466. end
  6467. end;
  6468. Result := True;
  6469. end;
  6470. end;
  6471. end;
  6472. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  6473. var
  6474. hp1: tai;
  6475. Count: Integer;
  6476. OrigLabel: TAsmLabel;
  6477. begin
  6478. result := False;
  6479. { Sometimes, the optimisations below can permit this }
  6480. RemoveDeadCodeAfterJump(p);
  6481. 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
  6482. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  6483. begin
  6484. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6485. { Also a side-effect of optimisations }
  6486. if CollapseZeroDistJump(p, OrigLabel) then
  6487. begin
  6488. Result := True;
  6489. Exit;
  6490. end;
  6491. hp1 := GetLabelWithSym(OrigLabel);
  6492. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  6493. begin
  6494. case taicpu(hp1).opcode of
  6495. A_RET:
  6496. {
  6497. change
  6498. jmp .L1
  6499. ...
  6500. .L1:
  6501. ret
  6502. into
  6503. ret
  6504. }
  6505. begin
  6506. ConvertJumpToRET(p, hp1);
  6507. result:=true;
  6508. end;
  6509. { Check any kind of direct assignment instruction }
  6510. A_MOV,
  6511. A_MOVD,
  6512. A_MOVQ,
  6513. A_MOVSX,
  6514. {$ifdef x86_64}
  6515. A_MOVSXD,
  6516. {$endif x86_64}
  6517. A_MOVZX,
  6518. A_MOVAPS,
  6519. A_MOVUPS,
  6520. A_MOVSD,
  6521. A_MOVAPD,
  6522. A_MOVUPD,
  6523. A_MOVDQA,
  6524. A_MOVDQU,
  6525. A_VMOVSS,
  6526. A_VMOVAPS,
  6527. A_VMOVUPS,
  6528. A_VMOVSD,
  6529. A_VMOVAPD,
  6530. A_VMOVUPD,
  6531. A_VMOVDQA,
  6532. A_VMOVDQU:
  6533. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  6534. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  6535. begin
  6536. Result := True;
  6537. Exit;
  6538. end;
  6539. else
  6540. ;
  6541. end;
  6542. end;
  6543. end;
  6544. end;
  6545. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  6546. begin
  6547. CanBeCMOV:=assigned(p) and
  6548. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  6549. { we can't use cmov ref,reg because
  6550. ref could be nil and cmov still throws an exception
  6551. if ref=nil but the mov isn't done (FK)
  6552. or ((taicpu(p).oper[0]^.typ = top_ref) and
  6553. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  6554. }
  6555. (taicpu(p).oper[1]^.typ = top_reg) and
  6556. (
  6557. (taicpu(p).oper[0]^.typ = top_reg) or
  6558. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  6559. it is not expected that this can cause a seg. violation }
  6560. (
  6561. (taicpu(p).oper[0]^.typ = top_ref) and
  6562. IsRefSafe(taicpu(p).oper[0]^.ref)
  6563. )
  6564. );
  6565. end;
  6566. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  6567. var
  6568. hp1,hp2: tai;
  6569. {$ifndef i8086}
  6570. hp3,hp4,hpmov2, hp5: tai;
  6571. l : Longint;
  6572. condition : TAsmCond;
  6573. {$endif i8086}
  6574. carryadd_opcode : TAsmOp;
  6575. symbol: TAsmSymbol;
  6576. reg: tsuperregister;
  6577. increg, tmpreg: TRegister;
  6578. begin
  6579. result:=false;
  6580. if GetNextInstruction(p,hp1) and (hp1.typ=ait_instruction) then
  6581. begin
  6582. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6583. if (
  6584. (
  6585. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  6586. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  6587. (Taicpu(hp1).oper[0]^.val=1)
  6588. ) or
  6589. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  6590. ) and
  6591. GetNextInstruction(hp1,hp2) and
  6592. SkipAligns(hp2, hp2) and
  6593. (hp2.typ = ait_label) and
  6594. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  6595. { jb @@1 cmc
  6596. inc/dec operand --> adc/sbb operand,0
  6597. @@1:
  6598. ... and ...
  6599. jnb @@1
  6600. inc/dec operand --> adc/sbb operand,0
  6601. @@1: }
  6602. begin
  6603. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  6604. begin
  6605. case taicpu(hp1).opcode of
  6606. A_INC,
  6607. A_ADD:
  6608. carryadd_opcode:=A_ADC;
  6609. A_DEC,
  6610. A_SUB:
  6611. carryadd_opcode:=A_SBB;
  6612. else
  6613. InternalError(2021011001);
  6614. end;
  6615. Taicpu(p).clearop(0);
  6616. Taicpu(p).ops:=0;
  6617. Taicpu(p).is_jmp:=false;
  6618. Taicpu(p).opcode:=A_CMC;
  6619. Taicpu(p).condition:=C_NONE;
  6620. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  6621. Taicpu(hp1).ops:=2;
  6622. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  6623. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  6624. else
  6625. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  6626. Taicpu(hp1).loadconst(0,0);
  6627. Taicpu(hp1).opcode:=carryadd_opcode;
  6628. result:=true;
  6629. exit;
  6630. end
  6631. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  6632. begin
  6633. case taicpu(hp1).opcode of
  6634. A_INC,
  6635. A_ADD:
  6636. carryadd_opcode:=A_ADC;
  6637. A_DEC,
  6638. A_SUB:
  6639. carryadd_opcode:=A_SBB;
  6640. else
  6641. InternalError(2021011002);
  6642. end;
  6643. Taicpu(hp1).ops:=2;
  6644. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  6645. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  6646. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  6647. else
  6648. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  6649. Taicpu(hp1).loadconst(0,0);
  6650. Taicpu(hp1).opcode:=carryadd_opcode;
  6651. RemoveCurrentP(p, hp1);
  6652. result:=true;
  6653. exit;
  6654. end
  6655. {
  6656. jcc @@1 setcc tmpreg
  6657. inc/dec/add/sub operand -> (movzx tmpreg)
  6658. @@1: add/sub tmpreg,operand
  6659. While this increases code size slightly, it makes the code much faster if the
  6660. jump is unpredictable
  6661. }
  6662. else if not(cs_opt_size in current_settings.optimizerswitches) then
  6663. begin
  6664. { search for an available register which is volatile }
  6665. for reg in tcpuregisterset do
  6666. begin
  6667. if
  6668. {$if defined(i386) or defined(i8086)}
  6669. { Only use registers whose lowest 8-bits can Be accessed }
  6670. (reg in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) and
  6671. {$endif i386 or i8086}
  6672. (reg in paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption)) and
  6673. not(reg in UsedRegs[R_INTREGISTER].GetUsedRegs)
  6674. { We don't need to check if tmpreg is in hp1 or not, because
  6675. it will be marked as in use at p (if not, this is
  6676. indictive of a compiler bug). }
  6677. then
  6678. begin
  6679. TAsmLabel(symbol).decrefs;
  6680. increg := newreg(R_INTREGISTER,reg,R_SUBL);
  6681. Taicpu(p).clearop(0);
  6682. Taicpu(p).ops:=1;
  6683. Taicpu(p).is_jmp:=false;
  6684. Taicpu(p).opcode:=A_SETcc;
  6685. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  6686. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  6687. Taicpu(p).loadreg(0,increg);
  6688. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  6689. begin
  6690. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  6691. R_SUBW:
  6692. begin
  6693. tmpreg := newreg(R_INTREGISTER,reg,R_SUBW);
  6694. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  6695. end;
  6696. R_SUBD:
  6697. begin
  6698. tmpreg := newreg(R_INTREGISTER,reg,R_SUBD);
  6699. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  6700. end;
  6701. {$ifdef x86_64}
  6702. R_SUBQ:
  6703. begin
  6704. { MOVZX doesn't have a 64-bit variant, because
  6705. the 32-bit version implicitly zeroes the
  6706. upper 32-bits of the destination register }
  6707. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,
  6708. newreg(R_INTREGISTER,reg,R_SUBD));
  6709. tmpreg := newreg(R_INTREGISTER,reg,R_SUBQ);
  6710. end;
  6711. {$endif x86_64}
  6712. else
  6713. Internalerror(2020030601);
  6714. end;
  6715. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  6716. asml.InsertAfter(hp2,p);
  6717. end
  6718. else
  6719. tmpreg := increg;
  6720. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  6721. begin
  6722. Taicpu(hp1).ops:=2;
  6723. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  6724. end;
  6725. Taicpu(hp1).loadreg(0,tmpreg);
  6726. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  6727. Result := True;
  6728. { p is no longer a Jcc instruction, so exit }
  6729. Exit;
  6730. end;
  6731. end;
  6732. end;
  6733. end;
  6734. { Detect the following:
  6735. jmp<cond> @Lbl1
  6736. jmp @Lbl2
  6737. ...
  6738. @Lbl1:
  6739. ret
  6740. Change to:
  6741. jmp<inv_cond> @Lbl2
  6742. ret
  6743. }
  6744. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  6745. begin
  6746. hp2:=getlabelwithsym(TAsmLabel(symbol));
  6747. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  6748. MatchInstruction(hp2,A_RET,[S_NO]) then
  6749. begin
  6750. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6751. { Change label address to that of the unconditional jump }
  6752. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  6753. TAsmLabel(symbol).DecRefs;
  6754. taicpu(hp1).opcode := A_RET;
  6755. taicpu(hp1).is_jmp := false;
  6756. taicpu(hp1).ops := taicpu(hp2).ops;
  6757. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  6758. case taicpu(hp2).ops of
  6759. 0:
  6760. taicpu(hp1).clearop(0);
  6761. 1:
  6762. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  6763. else
  6764. internalerror(2016041302);
  6765. end;
  6766. end;
  6767. {$ifndef i8086}
  6768. end
  6769. {
  6770. convert
  6771. j<c> .L1
  6772. mov 1,reg
  6773. jmp .L2
  6774. .L1
  6775. mov 0,reg
  6776. .L2
  6777. into
  6778. mov 0,reg
  6779. set<not(c)> reg
  6780. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6781. would destroy the flag contents
  6782. }
  6783. else if MatchInstruction(hp1,A_MOV,[]) and
  6784. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6785. {$ifdef i386}
  6786. (
  6787. { Under i386, ESI, EDI, EBP and ESP
  6788. don't have an 8-bit representation }
  6789. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6790. ) and
  6791. {$endif i386}
  6792. (taicpu(hp1).oper[0]^.val=1) and
  6793. GetNextInstruction(hp1,hp2) and
  6794. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6795. GetNextInstruction(hp2,hp3) and
  6796. { skip align }
  6797. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  6798. (hp3.typ=ait_label) and
  6799. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6800. (tai_label(hp3).labsym.getrefs=1) and
  6801. GetNextInstruction(hp3,hp4) and
  6802. MatchInstruction(hp4,A_MOV,[]) and
  6803. MatchOpType(taicpu(hp4),top_const,top_reg) and
  6804. (taicpu(hp4).oper[0]^.val=0) and
  6805. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6806. GetNextInstruction(hp4,hp5) and
  6807. (hp5.typ=ait_label) and
  6808. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  6809. (tai_label(hp5).labsym.getrefs=1) then
  6810. begin
  6811. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  6812. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  6813. { remove last label }
  6814. RemoveInstruction(hp5);
  6815. { remove second label }
  6816. RemoveInstruction(hp3);
  6817. { if align is present remove it }
  6818. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  6819. RemoveInstruction(hp3);
  6820. { remove jmp }
  6821. RemoveInstruction(hp2);
  6822. if taicpu(hp1).opsize=S_B then
  6823. RemoveInstruction(hp1)
  6824. else
  6825. taicpu(hp1).loadconst(0,0);
  6826. taicpu(hp4).opcode:=A_SETcc;
  6827. taicpu(hp4).opsize:=S_B;
  6828. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  6829. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  6830. taicpu(hp4).opercnt:=1;
  6831. taicpu(hp4).ops:=1;
  6832. taicpu(hp4).freeop(1);
  6833. RemoveCurrentP(p);
  6834. Result:=true;
  6835. exit;
  6836. end
  6837. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  6838. begin
  6839. { check for
  6840. jCC xxx
  6841. <several movs>
  6842. xxx:
  6843. }
  6844. l:=0;
  6845. while assigned(hp1) and
  6846. CanBeCMOV(hp1) and
  6847. { stop on labels }
  6848. not(hp1.typ=ait_label) do
  6849. begin
  6850. inc(l);
  6851. GetNextInstruction(hp1,hp1);
  6852. end;
  6853. if assigned(hp1) then
  6854. begin
  6855. if FindLabel(tasmlabel(symbol),hp1) then
  6856. begin
  6857. if (l<=4) and (l>0) then
  6858. begin
  6859. condition:=inverse_cond(taicpu(p).condition);
  6860. GetNextInstruction(p,hp1);
  6861. repeat
  6862. if not Assigned(hp1) then
  6863. InternalError(2018062900);
  6864. taicpu(hp1).opcode:=A_CMOVcc;
  6865. taicpu(hp1).condition:=condition;
  6866. UpdateUsedRegs(hp1);
  6867. GetNextInstruction(hp1,hp1);
  6868. until not(CanBeCMOV(hp1));
  6869. { Remember what hp1 is in case there's multiple aligns to get rid of }
  6870. hp2 := hp1;
  6871. repeat
  6872. if not Assigned(hp2) then
  6873. InternalError(2018062910);
  6874. case hp2.typ of
  6875. ait_label:
  6876. { What we expected - break out of the loop (it won't be a dead label at the top of
  6877. a cluster because that was optimised at an earlier stage) }
  6878. Break;
  6879. ait_align:
  6880. { Go to the next entry until a label is found (may be multiple aligns before it) }
  6881. begin
  6882. hp2 := tai(hp2.Next);
  6883. Continue;
  6884. end;
  6885. else
  6886. begin
  6887. { Might be a comment or temporary allocation entry }
  6888. if not (hp2.typ in SkipInstr) then
  6889. InternalError(2018062911);
  6890. hp2 := tai(hp2.Next);
  6891. Continue;
  6892. end;
  6893. end;
  6894. until False;
  6895. { Now we can safely decrement the reference count }
  6896. tasmlabel(symbol).decrefs;
  6897. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  6898. { Remove the original jump }
  6899. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  6900. GetNextInstruction(hp2, p); { Instruction after the label }
  6901. { Remove the label if this is its final reference }
  6902. if (tasmlabel(symbol).getrefs=0) then
  6903. StripLabelFast(hp1);
  6904. if Assigned(p) then
  6905. begin
  6906. UpdateUsedRegs(p);
  6907. result:=true;
  6908. end;
  6909. exit;
  6910. end;
  6911. end
  6912. else
  6913. begin
  6914. { check further for
  6915. jCC xxx
  6916. <several movs 1>
  6917. jmp yyy
  6918. xxx:
  6919. <several movs 2>
  6920. yyy:
  6921. }
  6922. { hp2 points to jmp yyy }
  6923. hp2:=hp1;
  6924. { skip hp1 to xxx (or an align right before it) }
  6925. GetNextInstruction(hp1, hp1);
  6926. if assigned(hp2) and
  6927. assigned(hp1) and
  6928. (l<=3) and
  6929. (hp2.typ=ait_instruction) and
  6930. (taicpu(hp2).is_jmp) and
  6931. (taicpu(hp2).condition=C_None) and
  6932. { real label and jump, no further references to the
  6933. label are allowed }
  6934. (tasmlabel(symbol).getrefs=1) and
  6935. FindLabel(tasmlabel(symbol),hp1) then
  6936. begin
  6937. l:=0;
  6938. { skip hp1 to <several moves 2> }
  6939. if (hp1.typ = ait_align) then
  6940. GetNextInstruction(hp1, hp1);
  6941. GetNextInstruction(hp1, hpmov2);
  6942. hp1 := hpmov2;
  6943. while assigned(hp1) and
  6944. CanBeCMOV(hp1) do
  6945. begin
  6946. inc(l);
  6947. GetNextInstruction(hp1, hp1);
  6948. end;
  6949. { hp1 points to yyy (or an align right before it) }
  6950. hp3 := hp1;
  6951. if assigned(hp1) and
  6952. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  6953. begin
  6954. condition:=inverse_cond(taicpu(p).condition);
  6955. GetNextInstruction(p,hp1);
  6956. repeat
  6957. taicpu(hp1).opcode:=A_CMOVcc;
  6958. taicpu(hp1).condition:=condition;
  6959. UpdateUsedRegs(hp1);
  6960. GetNextInstruction(hp1,hp1);
  6961. until not(assigned(hp1)) or
  6962. not(CanBeCMOV(hp1));
  6963. condition:=inverse_cond(condition);
  6964. hp1 := hpmov2;
  6965. { hp1 is now at <several movs 2> }
  6966. while Assigned(hp1) and CanBeCMOV(hp1) do
  6967. begin
  6968. taicpu(hp1).opcode:=A_CMOVcc;
  6969. taicpu(hp1).condition:=condition;
  6970. UpdateUsedRegs(hp1);
  6971. GetNextInstruction(hp1,hp1);
  6972. end;
  6973. hp1 := p;
  6974. { Get first instruction after label }
  6975. GetNextInstruction(hp3, p);
  6976. if assigned(p) and (hp3.typ = ait_align) then
  6977. GetNextInstruction(p, p);
  6978. { Don't dereference yet, as doing so will cause
  6979. GetNextInstruction to skip the label and
  6980. optional align marker. [Kit] }
  6981. GetNextInstruction(hp2, hp4);
  6982. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  6983. { remove jCC }
  6984. RemoveInstruction(hp1);
  6985. { Now we can safely decrement it }
  6986. tasmlabel(symbol).decrefs;
  6987. { Remove label xxx (it will have a ref of zero due to the initial check }
  6988. StripLabelFast(hp4);
  6989. { remove jmp }
  6990. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  6991. RemoveInstruction(hp2);
  6992. { As before, now we can safely decrement it }
  6993. tasmlabel(symbol).decrefs;
  6994. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  6995. if tasmlabel(symbol).getrefs = 0 then
  6996. StripLabelFast(hp3);
  6997. if Assigned(p) then
  6998. begin
  6999. UpdateUsedRegs(p);
  7000. result:=true;
  7001. end;
  7002. exit;
  7003. end;
  7004. end;
  7005. end;
  7006. end;
  7007. {$endif i8086}
  7008. end;
  7009. end;
  7010. end;
  7011. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  7012. var
  7013. hp1,hp2: tai;
  7014. reg_and_hp1_is_instr: Boolean;
  7015. begin
  7016. result:=false;
  7017. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  7018. GetNextInstruction(p,hp1) and
  7019. (hp1.typ = ait_instruction);
  7020. if reg_and_hp1_is_instr and
  7021. (
  7022. (taicpu(hp1).opcode <> A_LEA) or
  7023. { If the LEA instruction can be converted into an arithmetic instruction,
  7024. it may be possible to then fold it. }
  7025. (
  7026. { If the flags register is in use, don't change the instruction
  7027. to an ADD otherwise this will scramble the flags. [Kit] }
  7028. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  7029. ConvertLEA(taicpu(hp1))
  7030. )
  7031. ) and
  7032. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  7033. GetNextInstruction(hp1,hp2) and
  7034. MatchInstruction(hp2,A_MOV,[]) and
  7035. (taicpu(hp2).oper[0]^.typ = top_reg) and
  7036. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  7037. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  7038. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  7039. {$ifdef i386}
  7040. { not all registers have byte size sub registers on i386 }
  7041. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  7042. {$endif i386}
  7043. (((taicpu(hp1).ops=2) and
  7044. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7045. ((taicpu(hp1).ops=1) and
  7046. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  7047. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  7048. begin
  7049. { change movsX/movzX reg/ref, reg2
  7050. add/sub/or/... reg3/$const, reg2
  7051. mov reg2 reg/ref
  7052. to add/sub/or/... reg3/$const, reg/ref }
  7053. { by example:
  7054. movswl %si,%eax movswl %si,%eax p
  7055. decl %eax addl %edx,%eax hp1
  7056. movw %ax,%si movw %ax,%si hp2
  7057. ->
  7058. movswl %si,%eax movswl %si,%eax p
  7059. decw %eax addw %edx,%eax hp1
  7060. movw %ax,%si movw %ax,%si hp2
  7061. }
  7062. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  7063. {
  7064. ->
  7065. movswl %si,%eax movswl %si,%eax p
  7066. decw %si addw %dx,%si hp1
  7067. movw %ax,%si movw %ax,%si hp2
  7068. }
  7069. case taicpu(hp1).ops of
  7070. 1:
  7071. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  7072. 2:
  7073. begin
  7074. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  7075. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  7076. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  7077. end;
  7078. else
  7079. internalerror(2008042702);
  7080. end;
  7081. {
  7082. ->
  7083. decw %si addw %dx,%si p
  7084. }
  7085. DebugMsg(SPeepholeOptimization + 'var3',p);
  7086. RemoveCurrentP(p, hp1);
  7087. RemoveInstruction(hp2);
  7088. end
  7089. else if reg_and_hp1_is_instr and
  7090. (taicpu(hp1).opcode = A_MOV) and
  7091. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7092. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  7093. {$ifdef x86_64}
  7094. { check for implicit extension to 64 bit }
  7095. or
  7096. ((taicpu(p).opsize in [S_BL,S_WL]) and
  7097. (taicpu(hp1).opsize=S_Q) and
  7098. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  7099. )
  7100. {$endif x86_64}
  7101. )
  7102. then
  7103. begin
  7104. { change
  7105. movx %reg1,%reg2
  7106. mov %reg2,%reg3
  7107. dealloc %reg2
  7108. into
  7109. movx %reg,%reg3
  7110. }
  7111. TransferUsedRegs(TmpUsedRegs);
  7112. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7113. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7114. begin
  7115. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  7116. {$ifdef x86_64}
  7117. if (taicpu(p).opsize in [S_BL,S_WL]) and
  7118. (taicpu(hp1).opsize=S_Q) then
  7119. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  7120. else
  7121. {$endif x86_64}
  7122. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7123. RemoveInstruction(hp1);
  7124. end;
  7125. end
  7126. else if reg_and_hp1_is_instr and
  7127. (taicpu(hp1).opcode = A_MOV) and
  7128. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7129. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  7130. (taicpu(hp1).opsize=S_B)) or
  7131. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  7132. (taicpu(hp1).opsize=S_W))
  7133. {$ifdef x86_64}
  7134. or ((taicpu(p).opsize=S_LQ) and
  7135. (taicpu(hp1).opsize=S_L))
  7136. {$endif x86_64}
  7137. ) and
  7138. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  7139. begin
  7140. { change
  7141. movx %reg1,%reg2
  7142. mov %reg2,%reg3
  7143. dealloc %reg2
  7144. into
  7145. mov %reg1,%reg3
  7146. if the second mov accesses only the bits stored in reg1
  7147. }
  7148. TransferUsedRegs(TmpUsedRegs);
  7149. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7150. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7151. begin
  7152. DebugMsg(SPeepholeOptimization + 'MovxMov2Mov',p);
  7153. if taicpu(p).oper[0]^.typ=top_reg then
  7154. begin
  7155. case taicpu(hp1).opsize of
  7156. S_B:
  7157. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  7158. S_W:
  7159. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  7160. S_L:
  7161. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  7162. else
  7163. Internalerror(2020102301);
  7164. end;
  7165. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  7166. end
  7167. else
  7168. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  7169. RemoveCurrentP(p);
  7170. result:=true;
  7171. exit;
  7172. end;
  7173. end
  7174. else if reg_and_hp1_is_instr and
  7175. (taicpu(p).oper[0]^.typ = top_reg) and
  7176. (
  7177. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  7178. ) and
  7179. (taicpu(hp1).oper[0]^.typ = top_const) and
  7180. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  7181. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  7182. { Minimum shift value allowed is the bit difference between the sizes }
  7183. (taicpu(hp1).oper[0]^.val >=
  7184. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  7185. 8 * (
  7186. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  7187. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  7188. )
  7189. ) then
  7190. begin
  7191. { For:
  7192. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  7193. shl/sal ##, %reg1
  7194. Remove the movsx/movzx instruction if the shift overwrites the
  7195. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  7196. }
  7197. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  7198. RemoveCurrentP(p, hp1);
  7199. Result := True;
  7200. Exit;
  7201. end
  7202. else if reg_and_hp1_is_instr and
  7203. (taicpu(p).oper[0]^.typ = top_reg) and
  7204. (
  7205. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  7206. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  7207. ) and
  7208. (taicpu(hp1).oper[0]^.typ = top_const) and
  7209. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  7210. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  7211. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  7212. (taicpu(hp1).oper[0]^.val <
  7213. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  7214. 8 * (
  7215. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  7216. )
  7217. ) then
  7218. begin
  7219. { For:
  7220. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  7221. sar ##, %reg1 shr ##, %reg1
  7222. Move the shift to before the movx instruction if the shift value
  7223. is not too large.
  7224. }
  7225. asml.Remove(hp1);
  7226. asml.InsertBefore(hp1, p);
  7227. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  7228. case taicpu(p).opsize of
  7229. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  7230. taicpu(hp1).opsize := S_B;
  7231. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  7232. taicpu(hp1).opsize := S_W;
  7233. {$ifdef x86_64}
  7234. S_LQ:
  7235. taicpu(hp1).opsize := S_L;
  7236. {$endif}
  7237. else
  7238. InternalError(2020112401);
  7239. end;
  7240. if (taicpu(hp1).opcode = A_SHR) then
  7241. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  7242. else
  7243. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  7244. Result := True;
  7245. end
  7246. else if taicpu(p).opcode=A_MOVZX then
  7247. begin
  7248. { removes superfluous And's after movzx's }
  7249. if reg_and_hp1_is_instr and
  7250. (taicpu(hp1).opcode = A_AND) and
  7251. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7252. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  7253. {$ifdef x86_64}
  7254. { check for implicit extension to 64 bit }
  7255. or
  7256. ((taicpu(p).opsize in [S_BL,S_WL]) and
  7257. (taicpu(hp1).opsize=S_Q) and
  7258. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  7259. )
  7260. {$endif x86_64}
  7261. )
  7262. then
  7263. begin
  7264. case taicpu(p).opsize Of
  7265. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7266. if (taicpu(hp1).oper[0]^.val = $ff) then
  7267. begin
  7268. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  7269. RemoveInstruction(hp1);
  7270. Result:=true;
  7271. exit;
  7272. end;
  7273. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7274. if (taicpu(hp1).oper[0]^.val = $ffff) then
  7275. begin
  7276. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  7277. RemoveInstruction(hp1);
  7278. Result:=true;
  7279. exit;
  7280. end;
  7281. {$ifdef x86_64}
  7282. S_LQ:
  7283. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  7284. begin
  7285. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  7286. RemoveInstruction(hp1);
  7287. Result:=true;
  7288. exit;
  7289. end;
  7290. {$endif x86_64}
  7291. else
  7292. ;
  7293. end;
  7294. { we cannot get rid of the and, but can we get rid of the movz ?}
  7295. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  7296. begin
  7297. case taicpu(p).opsize Of
  7298. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7299. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  7300. begin
  7301. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  7302. RemoveCurrentP(p,hp1);
  7303. Result:=true;
  7304. exit;
  7305. end;
  7306. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7307. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  7308. begin
  7309. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  7310. RemoveCurrentP(p,hp1);
  7311. Result:=true;
  7312. exit;
  7313. end;
  7314. {$ifdef x86_64}
  7315. S_LQ:
  7316. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  7317. begin
  7318. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  7319. RemoveCurrentP(p,hp1);
  7320. Result:=true;
  7321. exit;
  7322. end;
  7323. {$endif x86_64}
  7324. else
  7325. ;
  7326. end;
  7327. end;
  7328. end;
  7329. { changes some movzx constructs to faster synonyms (all examples
  7330. are given with eax/ax, but are also valid for other registers)}
  7331. if MatchOpType(taicpu(p),top_reg,top_reg) then
  7332. begin
  7333. case taicpu(p).opsize of
  7334. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  7335. (the machine code is equivalent to movzbl %al,%eax), but the
  7336. code generator still generates that assembler instruction and
  7337. it is silently converted. This should probably be checked.
  7338. [Kit] }
  7339. S_BW:
  7340. begin
  7341. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7342. (
  7343. not IsMOVZXAcceptable
  7344. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  7345. or (
  7346. (cs_opt_size in current_settings.optimizerswitches) and
  7347. (taicpu(p).oper[1]^.reg = NR_AX)
  7348. )
  7349. ) then
  7350. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  7351. begin
  7352. DebugMsg(SPeepholeOptimization + 'var7',p);
  7353. taicpu(p).opcode := A_AND;
  7354. taicpu(p).changeopsize(S_W);
  7355. taicpu(p).loadConst(0,$ff);
  7356. Result := True;
  7357. end
  7358. else if not IsMOVZXAcceptable and
  7359. GetNextInstruction(p, hp1) and
  7360. (tai(hp1).typ = ait_instruction) and
  7361. (taicpu(hp1).opcode = A_AND) and
  7362. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7363. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7364. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  7365. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  7366. begin
  7367. DebugMsg(SPeepholeOptimization + 'var8',p);
  7368. taicpu(p).opcode := A_MOV;
  7369. taicpu(p).changeopsize(S_W);
  7370. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  7371. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7372. Result := True;
  7373. end;
  7374. end;
  7375. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  7376. S_BL:
  7377. begin
  7378. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7379. (
  7380. not IsMOVZXAcceptable
  7381. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  7382. or (
  7383. (cs_opt_size in current_settings.optimizerswitches) and
  7384. (taicpu(p).oper[1]^.reg = NR_EAX)
  7385. )
  7386. ) then
  7387. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  7388. begin
  7389. DebugMsg(SPeepholeOptimization + 'var9',p);
  7390. taicpu(p).opcode := A_AND;
  7391. taicpu(p).changeopsize(S_L);
  7392. taicpu(p).loadConst(0,$ff);
  7393. Result := True;
  7394. end
  7395. else if not IsMOVZXAcceptable and
  7396. GetNextInstruction(p, hp1) and
  7397. (tai(hp1).typ = ait_instruction) and
  7398. (taicpu(hp1).opcode = A_AND) and
  7399. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7400. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7401. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  7402. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  7403. begin
  7404. DebugMsg(SPeepholeOptimization + 'var10',p);
  7405. taicpu(p).opcode := A_MOV;
  7406. taicpu(p).changeopsize(S_L);
  7407. { do not use R_SUBWHOLE
  7408. as movl %rdx,%eax
  7409. is invalid in assembler PM }
  7410. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  7411. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7412. Result := True;
  7413. end;
  7414. end;
  7415. {$endif i8086}
  7416. S_WL:
  7417. if not IsMOVZXAcceptable then
  7418. begin
  7419. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  7420. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  7421. begin
  7422. DebugMsg(SPeepholeOptimization + 'var11',p);
  7423. taicpu(p).opcode := A_AND;
  7424. taicpu(p).changeopsize(S_L);
  7425. taicpu(p).loadConst(0,$ffff);
  7426. Result := True;
  7427. end
  7428. else if GetNextInstruction(p, hp1) and
  7429. (tai(hp1).typ = ait_instruction) and
  7430. (taicpu(hp1).opcode = A_AND) and
  7431. (taicpu(hp1).oper[0]^.typ = top_const) and
  7432. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7433. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7434. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  7435. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  7436. begin
  7437. DebugMsg(SPeepholeOptimization + 'var12',p);
  7438. taicpu(p).opcode := A_MOV;
  7439. taicpu(p).changeopsize(S_L);
  7440. { do not use R_SUBWHOLE
  7441. as movl %rdx,%eax
  7442. is invalid in assembler PM }
  7443. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  7444. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  7445. Result := True;
  7446. end;
  7447. end;
  7448. else
  7449. InternalError(2017050705);
  7450. end;
  7451. end
  7452. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  7453. begin
  7454. if GetNextInstruction(p, hp1) and
  7455. (tai(hp1).typ = ait_instruction) and
  7456. (taicpu(hp1).opcode = A_AND) and
  7457. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7458. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7459. begin
  7460. //taicpu(p).opcode := A_MOV;
  7461. case taicpu(p).opsize Of
  7462. S_BL:
  7463. begin
  7464. DebugMsg(SPeepholeOptimization + 'var13',p);
  7465. taicpu(hp1).changeopsize(S_L);
  7466. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7467. end;
  7468. S_WL:
  7469. begin
  7470. DebugMsg(SPeepholeOptimization + 'var14',p);
  7471. taicpu(hp1).changeopsize(S_L);
  7472. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  7473. end;
  7474. S_BW:
  7475. begin
  7476. DebugMsg(SPeepholeOptimization + 'var15',p);
  7477. taicpu(hp1).changeopsize(S_W);
  7478. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7479. end;
  7480. else
  7481. Internalerror(2017050704)
  7482. end;
  7483. Result := True;
  7484. end;
  7485. end;
  7486. end;
  7487. end;
  7488. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  7489. var
  7490. hp1, hp2 : tai;
  7491. MaskLength : Cardinal;
  7492. MaskedBits : TCgInt;
  7493. begin
  7494. Result:=false;
  7495. { There are no optimisations for reference targets }
  7496. if (taicpu(p).oper[1]^.typ <> top_reg) then
  7497. Exit;
  7498. while GetNextInstruction(p, hp1) and
  7499. (hp1.typ = ait_instruction) do
  7500. begin
  7501. if (taicpu(p).oper[0]^.typ = top_const) then
  7502. begin
  7503. if (taicpu(hp1).opcode = A_AND) and
  7504. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7505. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7506. { the second register must contain the first one, so compare their subreg types }
  7507. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  7508. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  7509. { change
  7510. and const1, reg
  7511. and const2, reg
  7512. to
  7513. and (const1 and const2), reg
  7514. }
  7515. begin
  7516. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  7517. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  7518. RemoveCurrentP(p, hp1);
  7519. Result:=true;
  7520. exit;
  7521. end
  7522. else if (taicpu(hp1).opcode = A_MOVZX) and
  7523. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7524. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  7525. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7526. (((taicpu(p).opsize=S_W) and
  7527. (taicpu(hp1).opsize=S_BW)) or
  7528. ((taicpu(p).opsize=S_L) and
  7529. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}]))
  7530. {$ifdef x86_64}
  7531. or
  7532. ((taicpu(p).opsize=S_Q) and
  7533. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL]))
  7534. {$endif x86_64}
  7535. ) then
  7536. begin
  7537. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  7538. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  7539. ) or
  7540. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  7541. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  7542. then
  7543. begin
  7544. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  7545. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  7546. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  7547. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  7548. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  7549. }
  7550. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  7551. RemoveInstruction(hp1);
  7552. { See if there are other optimisations possible }
  7553. Continue;
  7554. end;
  7555. end
  7556. else if (taicpu(hp1).opcode = A_SHL) and
  7557. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7558. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7559. begin
  7560. {$ifopt R+}
  7561. {$define RANGE_WAS_ON}
  7562. {$R-}
  7563. {$endif}
  7564. { get length of potential and mask }
  7565. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  7566. { really a mask? }
  7567. {$ifdef RANGE_WAS_ON}
  7568. {$R+}
  7569. {$endif}
  7570. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  7571. { unmasked part shifted out? }
  7572. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  7573. begin
  7574. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  7575. RemoveCurrentP(p, hp1);
  7576. Result:=true;
  7577. exit;
  7578. end;
  7579. end
  7580. else if (taicpu(hp1).opcode = A_SHR) and
  7581. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7582. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  7583. (taicpu(hp1).oper[0]^.val <= 63) then
  7584. begin
  7585. { Does SHR combined with the AND cover all the bits?
  7586. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  7587. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  7588. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  7589. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  7590. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  7591. begin
  7592. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  7593. RemoveCurrentP(p, hp1);
  7594. Result := True;
  7595. Exit;
  7596. end;
  7597. end
  7598. else if ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}) and
  7599. (taicpu(hp1).oper[0]^.typ = top_reg) and
  7600. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  7601. begin
  7602. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  7603. (
  7604. (
  7605. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  7606. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  7607. ) or (
  7608. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  7609. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  7610. {$ifdef x86_64}
  7611. ) or (
  7612. (taicpu(hp1).opsize = S_LQ) and
  7613. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  7614. {$endif x86_64}
  7615. )
  7616. ) then
  7617. begin
  7618. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  7619. begin
  7620. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  7621. RemoveInstruction(hp1);
  7622. { See if there are other optimisations possible }
  7623. Continue;
  7624. end;
  7625. { The super-registers are the same though.
  7626. Note that this change by itself doesn't improve
  7627. code speed, but it opens up other optimisations. }
  7628. {$ifdef x86_64}
  7629. { Convert 64-bit register to 32-bit }
  7630. case taicpu(hp1).opsize of
  7631. S_BQ:
  7632. begin
  7633. taicpu(hp1).opsize := S_BL;
  7634. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  7635. end;
  7636. S_WQ:
  7637. begin
  7638. taicpu(hp1).opsize := S_WL;
  7639. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  7640. end
  7641. else
  7642. ;
  7643. end;
  7644. {$endif x86_64}
  7645. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  7646. taicpu(hp1).opcode := A_MOVZX;
  7647. { See if there are other optimisations possible }
  7648. Continue;
  7649. end;
  7650. end;
  7651. end;
  7652. if (taicpu(hp1).is_jmp) and
  7653. (taicpu(hp1).opcode<>A_JMP) and
  7654. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  7655. begin
  7656. { change
  7657. and x, reg
  7658. jxx
  7659. to
  7660. test x, reg
  7661. jxx
  7662. if reg is deallocated before the
  7663. jump, but only if it's a conditional jump (PFV)
  7664. }
  7665. taicpu(p).opcode := A_TEST;
  7666. Exit;
  7667. end;
  7668. Break;
  7669. end;
  7670. { Lone AND tests }
  7671. if (taicpu(p).oper[0]^.typ = top_const) then
  7672. begin
  7673. {
  7674. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  7675. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  7676. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  7677. }
  7678. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  7679. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  7680. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  7681. begin
  7682. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  7683. if taicpu(p).opsize = S_L then
  7684. begin
  7685. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  7686. Result := True;
  7687. end;
  7688. end;
  7689. end;
  7690. { Backward check to determine necessity of and %reg,%reg }
  7691. if (taicpu(p).oper[0]^.typ = top_reg) and
  7692. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  7693. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  7694. GetLastInstruction(p, hp2) and
  7695. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  7696. { Check size of adjacent instruction to determine if the AND is
  7697. effectively a null operation }
  7698. (
  7699. (taicpu(p).opsize = taicpu(hp2).opsize) or
  7700. { Note: Don't include S_Q }
  7701. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  7702. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  7703. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  7704. ) then
  7705. begin
  7706. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  7707. { If GetNextInstruction returned False, hp1 will be nil }
  7708. RemoveCurrentP(p, hp1);
  7709. Result := True;
  7710. Exit;
  7711. end;
  7712. end;
  7713. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  7714. var
  7715. hp1: tai; NewRef: TReference;
  7716. { This entire nested function is used in an if-statement below, but we
  7717. want to avoid all the used reg transfers and GetNextInstruction calls
  7718. until we really have to check }
  7719. function MemRegisterNotUsedLater: Boolean; inline;
  7720. var
  7721. hp2: tai;
  7722. begin
  7723. TransferUsedRegs(TmpUsedRegs);
  7724. hp2 := p;
  7725. repeat
  7726. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7727. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  7728. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  7729. end;
  7730. begin
  7731. Result := False;
  7732. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  7733. Exit;
  7734. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  7735. begin
  7736. { Change:
  7737. add %reg2,%reg1
  7738. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  7739. To:
  7740. mov/s/z #(%reg1,%reg2),%reg1
  7741. }
  7742. if MatchOpType(taicpu(p), top_reg, top_reg) and
  7743. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  7744. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  7745. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  7746. (
  7747. (
  7748. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  7749. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  7750. { r/esp cannot be an index }
  7751. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  7752. ) or (
  7753. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  7754. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  7755. )
  7756. ) and (
  7757. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  7758. (
  7759. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  7760. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  7761. MemRegisterNotUsedLater
  7762. )
  7763. ) then
  7764. begin
  7765. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  7766. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  7767. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  7768. RemoveCurrentp(p, hp1);
  7769. Result := True;
  7770. Exit;
  7771. end;
  7772. { Change:
  7773. addl/q $x,%reg1
  7774. movl/q %reg1,%reg2
  7775. To:
  7776. leal/q $x(%reg1),%reg2
  7777. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  7778. Breaks the dependency chain.
  7779. }
  7780. if MatchOpType(taicpu(p),top_const,top_reg) and
  7781. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  7782. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7783. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  7784. (
  7785. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  7786. not (cs_opt_size in current_settings.optimizerswitches) or
  7787. (
  7788. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  7789. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  7790. )
  7791. ) then
  7792. begin
  7793. { Change the MOV instruction to a LEA instruction, and update the
  7794. first operand }
  7795. reference_reset(NewRef, 1, []);
  7796. NewRef.base := taicpu(p).oper[1]^.reg;
  7797. NewRef.scalefactor := 1;
  7798. NewRef.offset := taicpu(p).oper[0]^.val;
  7799. taicpu(hp1).opcode := A_LEA;
  7800. taicpu(hp1).loadref(0, NewRef);
  7801. TransferUsedRegs(TmpUsedRegs);
  7802. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7803. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  7804. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7805. begin
  7806. { Move what is now the LEA instruction to before the SUB instruction }
  7807. Asml.Remove(hp1);
  7808. Asml.InsertBefore(hp1, p);
  7809. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  7810. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  7811. p := hp1;
  7812. end
  7813. else
  7814. begin
  7815. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  7816. RemoveCurrentP(p, hp1);
  7817. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  7818. end;
  7819. Result := True;
  7820. end;
  7821. end;
  7822. end;
  7823. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  7824. begin
  7825. Result:=false;
  7826. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  7827. begin
  7828. if MatchReference(taicpu(p).oper[0]^.ref^,taicpu(p).oper[1]^.reg,NR_INVALID) and
  7829. (taicpu(p).oper[0]^.ref^.index<>NR_NO) then
  7830. begin
  7831. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.base);
  7832. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.index);
  7833. taicpu(p).opcode:=A_ADD;
  7834. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  7835. result:=true;
  7836. end
  7837. else if MatchReference(taicpu(p).oper[0]^.ref^,NR_INVALID,taicpu(p).oper[1]^.reg) and
  7838. (taicpu(p).oper[0]^.ref^.base<>NR_NO) then
  7839. begin
  7840. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.index);
  7841. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.base);
  7842. taicpu(p).opcode:=A_ADD;
  7843. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  7844. result:=true;
  7845. end;
  7846. end;
  7847. end;
  7848. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  7849. var
  7850. hp1: tai; NewRef: TReference;
  7851. begin
  7852. { Change:
  7853. subl/q $x,%reg1
  7854. movl/q %reg1,%reg2
  7855. To:
  7856. leal/q $-x(%reg1),%reg2
  7857. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  7858. Breaks the dependency chain and potentially permits the removal of
  7859. a CMP instruction if one follows.
  7860. }
  7861. Result := False;
  7862. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7863. MatchOpType(taicpu(p),top_const,top_reg) and
  7864. GetNextInstruction(p, hp1) and
  7865. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  7866. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7867. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  7868. (
  7869. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  7870. not (cs_opt_size in current_settings.optimizerswitches) or
  7871. (
  7872. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  7873. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  7874. )
  7875. ) then
  7876. begin
  7877. { Change the MOV instruction to a LEA instruction, and update the
  7878. first operand }
  7879. reference_reset(NewRef, 1, []);
  7880. NewRef.base := taicpu(p).oper[1]^.reg;
  7881. NewRef.scalefactor := 1;
  7882. NewRef.offset := -taicpu(p).oper[0]^.val;
  7883. taicpu(hp1).opcode := A_LEA;
  7884. taicpu(hp1).loadref(0, NewRef);
  7885. TransferUsedRegs(TmpUsedRegs);
  7886. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7887. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  7888. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7889. begin
  7890. { Move what is now the LEA instruction to before the SUB instruction }
  7891. Asml.Remove(hp1);
  7892. Asml.InsertBefore(hp1, p);
  7893. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  7894. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  7895. p := hp1;
  7896. end
  7897. else
  7898. begin
  7899. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  7900. RemoveCurrentP(p, hp1);
  7901. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  7902. end;
  7903. Result := True;
  7904. end;
  7905. end;
  7906. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  7907. begin
  7908. { we can skip all instructions not messing with the stack pointer }
  7909. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  7910. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  7911. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  7912. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  7913. ({(taicpu(hp1).ops=0) or }
  7914. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  7915. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  7916. ) and }
  7917. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  7918. )
  7919. ) do
  7920. GetNextInstruction(hp1,hp1);
  7921. Result:=assigned(hp1);
  7922. end;
  7923. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  7924. var
  7925. hp1, hp2, hp3, hp4, hp5: tai;
  7926. begin
  7927. Result:=false;
  7928. hp5:=nil;
  7929. { replace
  7930. leal(q) x(<stackpointer>),<stackpointer>
  7931. call procname
  7932. leal(q) -x(<stackpointer>),<stackpointer>
  7933. ret
  7934. by
  7935. jmp procname
  7936. but do it only on level 4 because it destroys stack back traces
  7937. }
  7938. if (cs_opt_level4 in current_settings.optimizerswitches) and
  7939. MatchOpType(taicpu(p),top_ref,top_reg) and
  7940. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  7941. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  7942. { the -8 or -24 are not required, but bail out early if possible,
  7943. higher values are unlikely }
  7944. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  7945. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  7946. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  7947. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  7948. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  7949. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  7950. GetNextInstruction(p, hp1) and
  7951. { Take a copy of hp1 }
  7952. SetAndTest(hp1, hp4) and
  7953. { trick to skip label }
  7954. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  7955. SkipSimpleInstructions(hp1) and
  7956. MatchInstruction(hp1,A_CALL,[S_NO]) and
  7957. GetNextInstruction(hp1, hp2) and
  7958. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  7959. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  7960. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  7961. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  7962. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  7963. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  7964. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  7965. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  7966. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  7967. GetNextInstruction(hp2, hp3) and
  7968. { trick to skip label }
  7969. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  7970. (MatchInstruction(hp3,A_RET,[S_NO]) or
  7971. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  7972. SetAndTest(hp3,hp5) and
  7973. GetNextInstruction(hp3,hp3) and
  7974. MatchInstruction(hp3,A_RET,[S_NO])
  7975. )
  7976. ) and
  7977. (taicpu(hp3).ops=0) then
  7978. begin
  7979. taicpu(hp1).opcode := A_JMP;
  7980. taicpu(hp1).is_jmp := true;
  7981. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  7982. RemoveCurrentP(p, hp4);
  7983. RemoveInstruction(hp2);
  7984. RemoveInstruction(hp3);
  7985. if Assigned(hp5) then
  7986. begin
  7987. AsmL.Remove(hp5);
  7988. ASmL.InsertBefore(hp5,hp1)
  7989. end;
  7990. Result:=true;
  7991. end;
  7992. end;
  7993. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  7994. {$ifdef x86_64}
  7995. var
  7996. hp1, hp2, hp3, hp4, hp5: tai;
  7997. {$endif x86_64}
  7998. begin
  7999. Result:=false;
  8000. {$ifdef x86_64}
  8001. hp5:=nil;
  8002. { replace
  8003. push %rax
  8004. call procname
  8005. pop %rcx
  8006. ret
  8007. by
  8008. jmp procname
  8009. but do it only on level 4 because it destroys stack back traces
  8010. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  8011. for all supported calling conventions
  8012. }
  8013. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8014. MatchOpType(taicpu(p),top_reg) and
  8015. (taicpu(p).oper[0]^.reg=NR_RAX) and
  8016. GetNextInstruction(p, hp1) and
  8017. { Take a copy of hp1 }
  8018. SetAndTest(hp1, hp4) and
  8019. { trick to skip label }
  8020. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  8021. SkipSimpleInstructions(hp1) and
  8022. MatchInstruction(hp1,A_CALL,[S_NO]) and
  8023. GetNextInstruction(hp1, hp2) and
  8024. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  8025. MatchOpType(taicpu(hp2),top_reg) and
  8026. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  8027. GetNextInstruction(hp2, hp3) and
  8028. { trick to skip label }
  8029. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  8030. (MatchInstruction(hp3,A_RET,[S_NO]) or
  8031. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  8032. SetAndTest(hp3,hp5) and
  8033. GetNextInstruction(hp3,hp3) and
  8034. MatchInstruction(hp3,A_RET,[S_NO])
  8035. )
  8036. ) and
  8037. (taicpu(hp3).ops=0) then
  8038. begin
  8039. taicpu(hp1).opcode := A_JMP;
  8040. taicpu(hp1).is_jmp := true;
  8041. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  8042. RemoveCurrentP(p, hp4);
  8043. RemoveInstruction(hp2);
  8044. RemoveInstruction(hp3);
  8045. if Assigned(hp5) then
  8046. begin
  8047. AsmL.Remove(hp5);
  8048. ASmL.InsertBefore(hp5,hp1)
  8049. end;
  8050. Result:=true;
  8051. end;
  8052. {$endif x86_64}
  8053. end;
  8054. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  8055. var
  8056. Value, RegName: string;
  8057. begin
  8058. Result:=false;
  8059. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  8060. begin
  8061. case taicpu(p).oper[0]^.val of
  8062. 0:
  8063. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  8064. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8065. begin
  8066. { change "mov $0,%reg" into "xor %reg,%reg" }
  8067. taicpu(p).opcode := A_XOR;
  8068. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  8069. Result := True;
  8070. end;
  8071. $1..$FFFFFFFF:
  8072. begin
  8073. { Code size reduction by J. Gareth "Kit" Moreton }
  8074. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  8075. case taicpu(p).opsize of
  8076. S_Q:
  8077. begin
  8078. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  8079. Value := debug_tostr(taicpu(p).oper[0]^.val);
  8080. { The actual optimization }
  8081. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  8082. taicpu(p).changeopsize(S_L);
  8083. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  8084. Result := True;
  8085. end;
  8086. else
  8087. { Do nothing };
  8088. end;
  8089. end;
  8090. -1:
  8091. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  8092. if (cs_opt_size in current_settings.optimizerswitches) and
  8093. (taicpu(p).opsize <> S_B) and
  8094. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8095. begin
  8096. { change "mov $-1,%reg" into "or $-1,%reg" }
  8097. { NOTES:
  8098. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  8099. - This operation creates a false dependency on the register, so only do it when optimising for size
  8100. - 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
  8101. }
  8102. taicpu(p).opcode := A_OR;
  8103. Result := True;
  8104. end;
  8105. end;
  8106. end;
  8107. end;
  8108. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  8109. var
  8110. hp1: tai;
  8111. begin
  8112. { Detect:
  8113. andw x, %ax (0 <= x < $8000)
  8114. ...
  8115. movzwl %ax,%eax
  8116. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  8117. }
  8118. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  8119. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  8120. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  8121. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  8122. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  8123. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  8124. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  8125. begin
  8126. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  8127. taicpu(hp1).opcode := A_CWDE;
  8128. taicpu(hp1).clearop(0);
  8129. taicpu(hp1).clearop(1);
  8130. taicpu(hp1).ops := 0;
  8131. { A change was made, but not with p, so move forward 1 }
  8132. p := tai(p.Next);
  8133. Result := True;
  8134. end;
  8135. end;
  8136. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  8137. begin
  8138. Result := False;
  8139. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  8140. Exit;
  8141. { Convert:
  8142. movswl %ax,%eax -> cwtl
  8143. movslq %eax,%rax -> cdqe
  8144. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  8145. refer to the same opcode and depends only on the assembler's
  8146. current operand-size attribute. [Kit]
  8147. }
  8148. with taicpu(p) do
  8149. case opsize of
  8150. S_WL:
  8151. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  8152. begin
  8153. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  8154. opcode := A_CWDE;
  8155. clearop(0);
  8156. clearop(1);
  8157. ops := 0;
  8158. Result := True;
  8159. end;
  8160. {$ifdef x86_64}
  8161. S_LQ:
  8162. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  8163. begin
  8164. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  8165. opcode := A_CDQE;
  8166. clearop(0);
  8167. clearop(1);
  8168. ops := 0;
  8169. Result := True;
  8170. end;
  8171. {$endif x86_64}
  8172. else
  8173. ;
  8174. end;
  8175. end;
  8176. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  8177. var
  8178. hp1: tai;
  8179. begin
  8180. { Detect:
  8181. shr x, %ax (x > 0)
  8182. ...
  8183. movzwl %ax,%eax
  8184. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  8185. }
  8186. Result := False;
  8187. if MatchOpType(taicpu(p), top_const, top_reg) and
  8188. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  8189. (taicpu(p).oper[0]^.val > 0) and
  8190. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  8191. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  8192. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  8193. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  8194. begin
  8195. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  8196. taicpu(hp1).opcode := A_CWDE;
  8197. taicpu(hp1).clearop(0);
  8198. taicpu(hp1).clearop(1);
  8199. taicpu(hp1).ops := 0;
  8200. { A change was made, but not with p, so move forward 1 }
  8201. p := tai(p.Next);
  8202. Result := True;
  8203. end;
  8204. end;
  8205. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  8206. begin
  8207. Result:=false;
  8208. { change "cmp $0, %reg" to "test %reg, %reg" }
  8209. if MatchOpType(taicpu(p),top_const,top_reg) and
  8210. (taicpu(p).oper[0]^.val = 0) then
  8211. begin
  8212. taicpu(p).opcode := A_TEST;
  8213. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  8214. Result:=true;
  8215. end;
  8216. end;
  8217. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  8218. var
  8219. IsTestConstX : Boolean;
  8220. hp1,hp2 : tai;
  8221. begin
  8222. Result:=false;
  8223. { removes the line marked with (x) from the sequence
  8224. and/or/xor/add/sub/... $x, %y
  8225. test/or %y, %y | test $-1, %y (x)
  8226. j(n)z _Label
  8227. as the first instruction already adjusts the ZF
  8228. %y operand may also be a reference }
  8229. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  8230. MatchOperand(taicpu(p).oper[0]^,-1);
  8231. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  8232. GetLastInstruction(p, hp1) and
  8233. (tai(hp1).typ = ait_instruction) and
  8234. GetNextInstruction(p,hp2) and
  8235. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  8236. case taicpu(hp1).opcode Of
  8237. A_ADD, A_SUB, A_OR, A_XOR, A_AND:
  8238. begin
  8239. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  8240. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  8241. { and in case of carry for A(E)/B(E)/C/NC }
  8242. ((taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  8243. ((taicpu(hp1).opcode <> A_ADD) and
  8244. (taicpu(hp1).opcode <> A_SUB))) then
  8245. begin
  8246. RemoveCurrentP(p, hp2);
  8247. Result:=true;
  8248. Exit;
  8249. end;
  8250. end;
  8251. A_SHL, A_SAL, A_SHR, A_SAR:
  8252. begin
  8253. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  8254. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  8255. { therefore, it's only safe to do this optimization for }
  8256. { shifts by a (nonzero) constant }
  8257. (taicpu(hp1).oper[0]^.typ = top_const) and
  8258. (taicpu(hp1).oper[0]^.val <> 0) and
  8259. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  8260. { and in case of carry for A(E)/B(E)/C/NC }
  8261. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  8262. begin
  8263. RemoveCurrentP(p, hp2);
  8264. Result:=true;
  8265. Exit;
  8266. end;
  8267. end;
  8268. A_DEC, A_INC, A_NEG:
  8269. begin
  8270. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  8271. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  8272. { and in case of carry for A(E)/B(E)/C/NC }
  8273. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  8274. begin
  8275. case taicpu(hp1).opcode of
  8276. A_DEC, A_INC:
  8277. { replace inc/dec with add/sub 1, because inc/dec doesn't set the carry flag }
  8278. begin
  8279. case taicpu(hp1).opcode Of
  8280. A_DEC: taicpu(hp1).opcode := A_SUB;
  8281. A_INC: taicpu(hp1).opcode := A_ADD;
  8282. else
  8283. ;
  8284. end;
  8285. taicpu(hp1).loadoper(1,taicpu(hp1).oper[0]^);
  8286. taicpu(hp1).loadConst(0,1);
  8287. taicpu(hp1).ops:=2;
  8288. end;
  8289. else
  8290. ;
  8291. end;
  8292. RemoveCurrentP(p, hp2);
  8293. Result:=true;
  8294. Exit;
  8295. end;
  8296. end
  8297. else
  8298. ;
  8299. end; { case }
  8300. { change "test $-1,%reg" into "test %reg,%reg" }
  8301. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  8302. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  8303. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  8304. if MatchInstruction(p, A_OR, []) and
  8305. { Can only match if they're both registers }
  8306. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  8307. begin
  8308. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  8309. taicpu(p).opcode := A_TEST;
  8310. { No need to set Result to True, as we've done all the optimisations we can }
  8311. end;
  8312. end;
  8313. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  8314. var
  8315. hp1,hp3 : tai;
  8316. {$ifndef x86_64}
  8317. hp2 : taicpu;
  8318. {$endif x86_64}
  8319. begin
  8320. Result:=false;
  8321. hp3:=nil;
  8322. {$ifndef x86_64}
  8323. { don't do this on modern CPUs, this really hurts them due to
  8324. broken call/ret pairing }
  8325. if (current_settings.optimizecputype < cpu_Pentium2) and
  8326. not(cs_create_pic in current_settings.moduleswitches) and
  8327. GetNextInstruction(p, hp1) and
  8328. MatchInstruction(hp1,A_JMP,[S_NO]) and
  8329. MatchOpType(taicpu(hp1),top_ref) and
  8330. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  8331. begin
  8332. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  8333. InsertLLItem(p.previous, p, hp2);
  8334. taicpu(p).opcode := A_JMP;
  8335. taicpu(p).is_jmp := true;
  8336. RemoveInstruction(hp1);
  8337. Result:=true;
  8338. end
  8339. else
  8340. {$endif x86_64}
  8341. { replace
  8342. call procname
  8343. ret
  8344. by
  8345. jmp procname
  8346. but do it only on level 4 because it destroys stack back traces
  8347. else if the subroutine is marked as no return, remove the ret
  8348. }
  8349. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  8350. (po_noreturn in current_procinfo.procdef.procoptions)) and
  8351. GetNextInstruction(p, hp1) and
  8352. (MatchInstruction(hp1,A_RET,[S_NO]) or
  8353. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  8354. SetAndTest(hp1,hp3) and
  8355. GetNextInstruction(hp1,hp1) and
  8356. MatchInstruction(hp1,A_RET,[S_NO])
  8357. )
  8358. ) and
  8359. (taicpu(hp1).ops=0) then
  8360. begin
  8361. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8362. { we might destroy stack alignment here if we do not do a call }
  8363. (target_info.stackalign<=sizeof(SizeUInt)) then
  8364. begin
  8365. taicpu(p).opcode := A_JMP;
  8366. taicpu(p).is_jmp := true;
  8367. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  8368. end
  8369. else
  8370. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  8371. RemoveInstruction(hp1);
  8372. if Assigned(hp3) then
  8373. begin
  8374. AsmL.Remove(hp3);
  8375. AsmL.InsertBefore(hp3,p)
  8376. end;
  8377. Result:=true;
  8378. end;
  8379. end;
  8380. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  8381. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  8382. begin
  8383. case OpSize of
  8384. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8385. Result := (Val <= $FF) and (Val >= -128);
  8386. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8387. Result := (Val <= $FFFF) and (Val >= -32768);
  8388. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  8389. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  8390. else
  8391. Result := True;
  8392. end;
  8393. end;
  8394. var
  8395. hp1, hp2 : tai;
  8396. SizeChange: Boolean;
  8397. PreMessage: string;
  8398. begin
  8399. Result := False;
  8400. if (taicpu(p).oper[0]^.typ = top_reg) and
  8401. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  8402. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  8403. begin
  8404. { Change (using movzbl %al,%eax as an example):
  8405. movzbl %al, %eax movzbl %al, %eax
  8406. cmpl x, %eax testl %eax,%eax
  8407. To:
  8408. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  8409. movzbl %al, %eax movzbl %al, %eax
  8410. Smaller instruction and minimises pipeline stall as the CPU
  8411. doesn't have to wait for the register to get zero-extended. [Kit]
  8412. Also allow if the smaller of the two registers is being checked,
  8413. as this still removes the false dependency.
  8414. }
  8415. if
  8416. (
  8417. (
  8418. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  8419. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  8420. ) or (
  8421. { If MatchOperand returns True, they must both be registers }
  8422. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  8423. )
  8424. ) and
  8425. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  8426. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  8427. begin
  8428. 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);
  8429. asml.Remove(hp1);
  8430. asml.InsertBefore(hp1, p);
  8431. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  8432. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  8433. begin
  8434. taicpu(hp1).opcode := A_TEST;
  8435. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  8436. end;
  8437. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  8438. case taicpu(p).opsize of
  8439. S_BW, S_BL:
  8440. begin
  8441. SizeChange := taicpu(hp1).opsize <> S_B;
  8442. taicpu(hp1).changeopsize(S_B);
  8443. end;
  8444. S_WL:
  8445. begin
  8446. SizeChange := taicpu(hp1).opsize <> S_W;
  8447. taicpu(hp1).changeopsize(S_W);
  8448. end
  8449. else
  8450. InternalError(2020112701);
  8451. end;
  8452. UpdateUsedRegs(tai(p.Next));
  8453. { Check if the register is used aferwards - if not, we can
  8454. remove the movzx instruction completely }
  8455. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  8456. begin
  8457. { Hp1 is a better position than p for debugging purposes }
  8458. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  8459. RemoveCurrentp(p, hp1);
  8460. Result := True;
  8461. end;
  8462. if SizeChange then
  8463. DebugMsg(SPeepholeOptimization + PreMessage +
  8464. 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)
  8465. else
  8466. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  8467. Exit;
  8468. end;
  8469. { Change (using movzwl %ax,%eax as an example):
  8470. movzwl %ax, %eax
  8471. movb %al, (dest) (Register is smaller than read register in movz)
  8472. To:
  8473. movb %al, (dest) (Move one back to avoid a false dependency)
  8474. movzwl %ax, %eax
  8475. }
  8476. if (taicpu(hp1).opcode = A_MOV) and
  8477. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8478. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  8479. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  8480. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  8481. begin
  8482. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  8483. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  8484. asml.Remove(hp1);
  8485. asml.InsertBefore(hp1, p);
  8486. if taicpu(hp1).oper[1]^.typ = top_reg then
  8487. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  8488. { Check if the register is used aferwards - if not, we can
  8489. remove the movzx instruction completely }
  8490. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  8491. begin
  8492. { Hp1 is a better position than p for debugging purposes }
  8493. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  8494. RemoveCurrentp(p, hp1);
  8495. Result := True;
  8496. end;
  8497. Exit;
  8498. end;
  8499. end;
  8500. {$ifdef x86_64}
  8501. { Code size reduction by J. Gareth "Kit" Moreton }
  8502. { Convert MOVZBQ and MOVZWQ to MOVZBL and MOVZWL respectively if it removes the REX prefix }
  8503. if (taicpu(p).opsize in [S_BQ, S_WQ]) and
  8504. (getsupreg(taicpu(p).oper[1]^.reg) in [RS_RAX, RS_RCX, RS_RDX, RS_RBX, RS_RSI, RS_RDI, RS_RBP, RS_RSP])
  8505. then
  8506. begin
  8507. { Has 64-bit register name and opcode suffix }
  8508. PreMessage := 'movz' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' -> movz';
  8509. { The actual optimization }
  8510. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  8511. if taicpu(p).opsize = S_BQ then
  8512. taicpu(p).changeopsize(S_BL)
  8513. else
  8514. taicpu(p).changeopsize(S_WL);
  8515. DebugMsg(SPeepholeOptimization + PreMessage +
  8516. debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (removes REX prefix)', p);
  8517. end;
  8518. {$endif}
  8519. end;
  8520. {$ifdef x86_64}
  8521. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  8522. var
  8523. PreMessage, RegName: string;
  8524. begin
  8525. { Code size reduction by J. Gareth "Kit" Moreton }
  8526. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  8527. as this removes the REX prefix }
  8528. Result := False;
  8529. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  8530. Exit;
  8531. if taicpu(p).oper[0]^.typ <> top_reg then
  8532. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  8533. InternalError(2018011500);
  8534. case taicpu(p).opsize of
  8535. S_Q:
  8536. begin
  8537. if (getsupreg(taicpu(p).oper[0]^.reg) in [RS_RAX, RS_RCX, RS_RDX, RS_RBX, RS_RSI, RS_RDI, RS_RBP, RS_RSP]) then
  8538. begin
  8539. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  8540. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  8541. { The actual optimization }
  8542. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  8543. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  8544. taicpu(p).changeopsize(S_L);
  8545. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  8546. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (removes REX prefix)', p);
  8547. end;
  8548. end;
  8549. else
  8550. ;
  8551. end;
  8552. end;
  8553. {$endif}
  8554. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  8555. var
  8556. OperIdx: Integer;
  8557. begin
  8558. for OperIdx := 0 to p.ops - 1 do
  8559. if p.oper[OperIdx]^.typ = top_ref then
  8560. optimize_ref(p.oper[OperIdx]^.ref^, False);
  8561. end;
  8562. end.