TargetInfo.cpp 424 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626
  1. //===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // These classes wrap the information about a call or function
  10. // definition used to handle ABI compliancy.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "TargetInfo.h"
  14. #include "ABIInfo.h"
  15. #include "CGBlocks.h"
  16. #include "CGCXXABI.h"
  17. #include "CGValue.h"
  18. #include "CodeGenFunction.h"
  19. #include "clang/AST/Attr.h"
  20. #include "clang/AST/RecordLayout.h"
  21. #include "clang/Basic/Builtins.h"
  22. #include "clang/Basic/CodeGenOptions.h"
  23. #include "clang/Basic/DiagnosticFrontend.h"
  24. #include "clang/CodeGen/CGFunctionInfo.h"
  25. #include "clang/CodeGen/SwiftCallingConv.h"
  26. #include "llvm/ADT/SmallBitVector.h"
  27. #include "llvm/ADT/StringExtras.h"
  28. #include "llvm/ADT/StringSwitch.h"
  29. #include "llvm/ADT/Triple.h"
  30. #include "llvm/ADT/Twine.h"
  31. #include "llvm/IR/DataLayout.h"
  32. #include "llvm/IR/IntrinsicsNVPTX.h"
  33. #include "llvm/IR/IntrinsicsS390.h"
  34. #include "llvm/IR/Type.h"
  35. #include "llvm/Support/MathExtras.h"
  36. #include "llvm/Support/raw_ostream.h"
  37. #include <algorithm> // std::sort
  38. using namespace clang;
  39. using namespace CodeGen;
  40. // Helper for coercing an aggregate argument or return value into an integer
  41. // array of the same size (including padding) and alignment. This alternate
  42. // coercion happens only for the RenderScript ABI and can be removed after
  43. // runtimes that rely on it are no longer supported.
  44. //
  45. // RenderScript assumes that the size of the argument / return value in the IR
  46. // is the same as the size of the corresponding qualified type. This helper
  47. // coerces the aggregate type into an array of the same size (including
  48. // padding). This coercion is used in lieu of expansion of struct members or
  49. // other canonical coercions that return a coerced-type of larger size.
  50. //
  51. // Ty - The argument / return value type
  52. // Context - The associated ASTContext
  53. // LLVMContext - The associated LLVMContext
  54. static ABIArgInfo coerceToIntArray(QualType Ty,
  55. ASTContext &Context,
  56. llvm::LLVMContext &LLVMContext) {
  57. // Alignment and Size are measured in bits.
  58. const uint64_t Size = Context.getTypeSize(Ty);
  59. const uint64_t Alignment = Context.getTypeAlign(Ty);
  60. llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
  61. const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
  62. return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
  63. }
  64. static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
  65. llvm::Value *Array,
  66. llvm::Value *Value,
  67. unsigned FirstIndex,
  68. unsigned LastIndex) {
  69. // Alternatively, we could emit this as a loop in the source.
  70. for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
  71. llvm::Value *Cell =
  72. Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
  73. Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
  74. }
  75. }
  76. static bool isAggregateTypeForABI(QualType T) {
  77. return !CodeGenFunction::hasScalarEvaluationKind(T) ||
  78. T->isMemberFunctionPointerType();
  79. }
  80. ABIArgInfo ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByVal,
  81. bool Realign,
  82. llvm::Type *Padding) const {
  83. return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty), ByVal,
  84. Realign, Padding);
  85. }
  86. ABIArgInfo
  87. ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
  88. return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
  89. /*ByVal*/ false, Realign);
  90. }
  91. Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
  92. QualType Ty) const {
  93. return Address::invalid();
  94. }
  95. bool ABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
  96. if (Ty->isPromotableIntegerType())
  97. return true;
  98. if (const auto *EIT = Ty->getAs<BitIntType>())
  99. if (EIT->getNumBits() < getContext().getTypeSize(getContext().IntTy))
  100. return true;
  101. return false;
  102. }
  103. ABIInfo::~ABIInfo() {}
  104. /// Does the given lowering require more than the given number of
  105. /// registers when expanded?
  106. ///
  107. /// This is intended to be the basis of a reasonable basic implementation
  108. /// of should{Pass,Return}IndirectlyForSwift.
  109. ///
  110. /// For most targets, a limit of four total registers is reasonable; this
  111. /// limits the amount of code required in order to move around the value
  112. /// in case it wasn't produced immediately prior to the call by the caller
  113. /// (or wasn't produced in exactly the right registers) or isn't used
  114. /// immediately within the callee. But some targets may need to further
  115. /// limit the register count due to an inability to support that many
  116. /// return registers.
  117. static bool occupiesMoreThan(CodeGenTypes &cgt,
  118. ArrayRef<llvm::Type*> scalarTypes,
  119. unsigned maxAllRegisters) {
  120. unsigned intCount = 0, fpCount = 0;
  121. for (llvm::Type *type : scalarTypes) {
  122. if (type->isPointerTy()) {
  123. intCount++;
  124. } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
  125. auto ptrWidth = cgt.getTarget().getPointerWidth(0);
  126. intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
  127. } else {
  128. assert(type->isVectorTy() || type->isFloatingPointTy());
  129. fpCount++;
  130. }
  131. }
  132. return (intCount + fpCount > maxAllRegisters);
  133. }
  134. bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
  135. llvm::Type *eltTy,
  136. unsigned numElts) const {
  137. // The default implementation of this assumes that the target guarantees
  138. // 128-bit SIMD support but nothing more.
  139. return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
  140. }
  141. static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
  142. CGCXXABI &CXXABI) {
  143. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  144. if (!RD) {
  145. if (!RT->getDecl()->canPassInRegisters())
  146. return CGCXXABI::RAA_Indirect;
  147. return CGCXXABI::RAA_Default;
  148. }
  149. return CXXABI.getRecordArgABI(RD);
  150. }
  151. static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
  152. CGCXXABI &CXXABI) {
  153. const RecordType *RT = T->getAs<RecordType>();
  154. if (!RT)
  155. return CGCXXABI::RAA_Default;
  156. return getRecordArgABI(RT, CXXABI);
  157. }
  158. static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI,
  159. const ABIInfo &Info) {
  160. QualType Ty = FI.getReturnType();
  161. if (const auto *RT = Ty->getAs<RecordType>())
  162. if (!isa<CXXRecordDecl>(RT->getDecl()) &&
  163. !RT->getDecl()->canPassInRegisters()) {
  164. FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty);
  165. return true;
  166. }
  167. return CXXABI.classifyReturnType(FI);
  168. }
  169. /// Pass transparent unions as if they were the type of the first element. Sema
  170. /// should ensure that all elements of the union have the same "machine type".
  171. static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
  172. if (const RecordType *UT = Ty->getAsUnionType()) {
  173. const RecordDecl *UD = UT->getDecl();
  174. if (UD->hasAttr<TransparentUnionAttr>()) {
  175. assert(!UD->field_empty() && "sema created an empty transparent union");
  176. return UD->field_begin()->getType();
  177. }
  178. }
  179. return Ty;
  180. }
  181. CGCXXABI &ABIInfo::getCXXABI() const {
  182. return CGT.getCXXABI();
  183. }
  184. ASTContext &ABIInfo::getContext() const {
  185. return CGT.getContext();
  186. }
  187. llvm::LLVMContext &ABIInfo::getVMContext() const {
  188. return CGT.getLLVMContext();
  189. }
  190. const llvm::DataLayout &ABIInfo::getDataLayout() const {
  191. return CGT.getDataLayout();
  192. }
  193. const TargetInfo &ABIInfo::getTarget() const {
  194. return CGT.getTarget();
  195. }
  196. const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
  197. return CGT.getCodeGenOpts();
  198. }
  199. bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
  200. bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
  201. return false;
  202. }
  203. bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
  204. uint64_t Members) const {
  205. return false;
  206. }
  207. LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
  208. raw_ostream &OS = llvm::errs();
  209. OS << "(ABIArgInfo Kind=";
  210. switch (TheKind) {
  211. case Direct:
  212. OS << "Direct Type=";
  213. if (llvm::Type *Ty = getCoerceToType())
  214. Ty->print(OS);
  215. else
  216. OS << "null";
  217. break;
  218. case Extend:
  219. OS << "Extend";
  220. break;
  221. case Ignore:
  222. OS << "Ignore";
  223. break;
  224. case InAlloca:
  225. OS << "InAlloca Offset=" << getInAllocaFieldIndex();
  226. break;
  227. case Indirect:
  228. OS << "Indirect Align=" << getIndirectAlign().getQuantity()
  229. << " ByVal=" << getIndirectByVal()
  230. << " Realign=" << getIndirectRealign();
  231. break;
  232. case IndirectAliased:
  233. OS << "Indirect Align=" << getIndirectAlign().getQuantity()
  234. << " AadrSpace=" << getIndirectAddrSpace()
  235. << " Realign=" << getIndirectRealign();
  236. break;
  237. case Expand:
  238. OS << "Expand";
  239. break;
  240. case CoerceAndExpand:
  241. OS << "CoerceAndExpand Type=";
  242. getCoerceAndExpandType()->print(OS);
  243. break;
  244. }
  245. OS << ")\n";
  246. }
  247. // Dynamically round a pointer up to a multiple of the given alignment.
  248. static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
  249. llvm::Value *Ptr,
  250. CharUnits Align) {
  251. llvm::Value *PtrAsInt = Ptr;
  252. // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
  253. PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
  254. PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
  255. llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
  256. PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
  257. llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
  258. PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
  259. Ptr->getType(),
  260. Ptr->getName() + ".aligned");
  261. return PtrAsInt;
  262. }
  263. /// Emit va_arg for a platform using the common void* representation,
  264. /// where arguments are simply emitted in an array of slots on the stack.
  265. ///
  266. /// This version implements the core direct-value passing rules.
  267. ///
  268. /// \param SlotSize - The size and alignment of a stack slot.
  269. /// Each argument will be allocated to a multiple of this number of
  270. /// slots, and all the slots will be aligned to this value.
  271. /// \param AllowHigherAlign - The slot alignment is not a cap;
  272. /// an argument type with an alignment greater than the slot size
  273. /// will be emitted on a higher-alignment address, potentially
  274. /// leaving one or more empty slots behind as padding. If this
  275. /// is false, the returned address might be less-aligned than
  276. /// DirectAlign.
  277. static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
  278. Address VAListAddr,
  279. llvm::Type *DirectTy,
  280. CharUnits DirectSize,
  281. CharUnits DirectAlign,
  282. CharUnits SlotSize,
  283. bool AllowHigherAlign) {
  284. // Cast the element type to i8* if necessary. Some platforms define
  285. // va_list as a struct containing an i8* instead of just an i8*.
  286. if (VAListAddr.getElementType() != CGF.Int8PtrTy)
  287. VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
  288. llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
  289. // If the CC aligns values higher than the slot size, do so if needed.
  290. Address Addr = Address::invalid();
  291. if (AllowHigherAlign && DirectAlign > SlotSize) {
  292. Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
  293. DirectAlign);
  294. } else {
  295. Addr = Address(Ptr, SlotSize);
  296. }
  297. // Advance the pointer past the argument, then store that back.
  298. CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
  299. Address NextPtr =
  300. CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next");
  301. CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
  302. // If the argument is smaller than a slot, and this is a big-endian
  303. // target, the argument will be right-adjusted in its slot.
  304. if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
  305. !DirectTy->isStructTy()) {
  306. Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
  307. }
  308. Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
  309. return Addr;
  310. }
  311. /// Emit va_arg for a platform using the common void* representation,
  312. /// where arguments are simply emitted in an array of slots on the stack.
  313. ///
  314. /// \param IsIndirect - Values of this type are passed indirectly.
  315. /// \param ValueInfo - The size and alignment of this type, generally
  316. /// computed with getContext().getTypeInfoInChars(ValueTy).
  317. /// \param SlotSizeAndAlign - The size and alignment of a stack slot.
  318. /// Each argument will be allocated to a multiple of this number of
  319. /// slots, and all the slots will be aligned to this value.
  320. /// \param AllowHigherAlign - The slot alignment is not a cap;
  321. /// an argument type with an alignment greater than the slot size
  322. /// will be emitted on a higher-alignment address, potentially
  323. /// leaving one or more empty slots behind as padding.
  324. static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
  325. QualType ValueTy, bool IsIndirect,
  326. TypeInfoChars ValueInfo,
  327. CharUnits SlotSizeAndAlign,
  328. bool AllowHigherAlign) {
  329. // The size and alignment of the value that was passed directly.
  330. CharUnits DirectSize, DirectAlign;
  331. if (IsIndirect) {
  332. DirectSize = CGF.getPointerSize();
  333. DirectAlign = CGF.getPointerAlign();
  334. } else {
  335. DirectSize = ValueInfo.Width;
  336. DirectAlign = ValueInfo.Align;
  337. }
  338. // Cast the address we've calculated to the right type.
  339. llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
  340. if (IsIndirect)
  341. DirectTy = DirectTy->getPointerTo(0);
  342. Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
  343. DirectSize, DirectAlign,
  344. SlotSizeAndAlign,
  345. AllowHigherAlign);
  346. if (IsIndirect) {
  347. Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.Align);
  348. }
  349. return Addr;
  350. }
  351. static Address complexTempStructure(CodeGenFunction &CGF, Address VAListAddr,
  352. QualType Ty, CharUnits SlotSize,
  353. CharUnits EltSize, const ComplexType *CTy) {
  354. Address Addr =
  355. emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, SlotSize * 2,
  356. SlotSize, SlotSize, /*AllowHigher*/ true);
  357. Address RealAddr = Addr;
  358. Address ImagAddr = RealAddr;
  359. if (CGF.CGM.getDataLayout().isBigEndian()) {
  360. RealAddr =
  361. CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize - EltSize);
  362. ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
  363. 2 * SlotSize - EltSize);
  364. } else {
  365. ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
  366. }
  367. llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
  368. RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
  369. ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
  370. llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
  371. llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
  372. Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
  373. CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
  374. /*init*/ true);
  375. return Temp;
  376. }
  377. static Address emitMergePHI(CodeGenFunction &CGF,
  378. Address Addr1, llvm::BasicBlock *Block1,
  379. Address Addr2, llvm::BasicBlock *Block2,
  380. const llvm::Twine &Name = "") {
  381. assert(Addr1.getType() == Addr2.getType());
  382. llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
  383. PHI->addIncoming(Addr1.getPointer(), Block1);
  384. PHI->addIncoming(Addr2.getPointer(), Block2);
  385. CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
  386. return Address(PHI, Addr1.getElementType(), Align);
  387. }
  388. TargetCodeGenInfo::~TargetCodeGenInfo() = default;
  389. // If someone can figure out a general rule for this, that would be great.
  390. // It's probably just doomed to be platform-dependent, though.
  391. unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
  392. // Verified for:
  393. // x86-64 FreeBSD, Linux, Darwin
  394. // x86-32 FreeBSD, Linux, Darwin
  395. // PowerPC Linux, Darwin
  396. // ARM Darwin (*not* EABI)
  397. // AArch64 Linux
  398. return 32;
  399. }
  400. bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
  401. const FunctionNoProtoType *fnType) const {
  402. // The following conventions are known to require this to be false:
  403. // x86_stdcall
  404. // MIPS
  405. // For everything else, we just prefer false unless we opt out.
  406. return false;
  407. }
  408. void
  409. TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
  410. llvm::SmallString<24> &Opt) const {
  411. // This assumes the user is passing a library name like "rt" instead of a
  412. // filename like "librt.a/so", and that they don't care whether it's static or
  413. // dynamic.
  414. Opt = "-l";
  415. Opt += Lib;
  416. }
  417. unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
  418. // OpenCL kernels are called via an explicit runtime API with arguments
  419. // set with clSetKernelArg(), not as normal sub-functions.
  420. // Return SPIR_KERNEL by default as the kernel calling convention to
  421. // ensure the fingerprint is fixed such way that each OpenCL argument
  422. // gets one matching argument in the produced kernel function argument
  423. // list to enable feasible implementation of clSetKernelArg() with
  424. // aggregates etc. In case we would use the default C calling conv here,
  425. // clSetKernelArg() might break depending on the target-specific
  426. // conventions; different targets might split structs passed as values
  427. // to multiple function arguments etc.
  428. return llvm::CallingConv::SPIR_KERNEL;
  429. }
  430. llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
  431. llvm::PointerType *T, QualType QT) const {
  432. return llvm::ConstantPointerNull::get(T);
  433. }
  434. LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
  435. const VarDecl *D) const {
  436. assert(!CGM.getLangOpts().OpenCL &&
  437. !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
  438. "Address space agnostic languages only");
  439. return D ? D->getType().getAddressSpace() : LangAS::Default;
  440. }
  441. llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
  442. CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
  443. LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
  444. // Since target may map different address spaces in AST to the same address
  445. // space, an address space conversion may end up as a bitcast.
  446. if (auto *C = dyn_cast<llvm::Constant>(Src))
  447. return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
  448. // Try to preserve the source's name to make IR more readable.
  449. return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
  450. Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
  451. }
  452. llvm::Constant *
  453. TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
  454. LangAS SrcAddr, LangAS DestAddr,
  455. llvm::Type *DestTy) const {
  456. // Since target may map different address spaces in AST to the same address
  457. // space, an address space conversion may end up as a bitcast.
  458. return llvm::ConstantExpr::getPointerCast(Src, DestTy);
  459. }
  460. llvm::SyncScope::ID
  461. TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
  462. SyncScope Scope,
  463. llvm::AtomicOrdering Ordering,
  464. llvm::LLVMContext &Ctx) const {
  465. return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
  466. }
  467. static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
  468. /// isEmptyField - Return true iff a the field is "empty", that is it
  469. /// is an unnamed bit-field or an (array of) empty record(s).
  470. static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
  471. bool AllowArrays) {
  472. if (FD->isUnnamedBitfield())
  473. return true;
  474. QualType FT = FD->getType();
  475. // Constant arrays of empty records count as empty, strip them off.
  476. // Constant arrays of zero length always count as empty.
  477. bool WasArray = false;
  478. if (AllowArrays)
  479. while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
  480. if (AT->getSize() == 0)
  481. return true;
  482. FT = AT->getElementType();
  483. // The [[no_unique_address]] special case below does not apply to
  484. // arrays of C++ empty records, so we need to remember this fact.
  485. WasArray = true;
  486. }
  487. const RecordType *RT = FT->getAs<RecordType>();
  488. if (!RT)
  489. return false;
  490. // C++ record fields are never empty, at least in the Itanium ABI.
  491. //
  492. // FIXME: We should use a predicate for whether this behavior is true in the
  493. // current ABI.
  494. //
  495. // The exception to the above rule are fields marked with the
  496. // [[no_unique_address]] attribute (since C++20). Those do count as empty
  497. // according to the Itanium ABI. The exception applies only to records,
  498. // not arrays of records, so we must also check whether we stripped off an
  499. // array type above.
  500. if (isa<CXXRecordDecl>(RT->getDecl()) &&
  501. (WasArray || !FD->hasAttr<NoUniqueAddressAttr>()))
  502. return false;
  503. return isEmptyRecord(Context, FT, AllowArrays);
  504. }
  505. /// isEmptyRecord - Return true iff a structure contains only empty
  506. /// fields. Note that a structure with a flexible array member is not
  507. /// considered empty.
  508. static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
  509. const RecordType *RT = T->getAs<RecordType>();
  510. if (!RT)
  511. return false;
  512. const RecordDecl *RD = RT->getDecl();
  513. if (RD->hasFlexibleArrayMember())
  514. return false;
  515. // If this is a C++ record, check the bases first.
  516. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  517. for (const auto &I : CXXRD->bases())
  518. if (!isEmptyRecord(Context, I.getType(), true))
  519. return false;
  520. for (const auto *I : RD->fields())
  521. if (!isEmptyField(Context, I, AllowArrays))
  522. return false;
  523. return true;
  524. }
  525. /// isSingleElementStruct - Determine if a structure is a "single
  526. /// element struct", i.e. it has exactly one non-empty field or
  527. /// exactly one field which is itself a single element
  528. /// struct. Structures with flexible array members are never
  529. /// considered single element structs.
  530. ///
  531. /// \return The field declaration for the single non-empty field, if
  532. /// it exists.
  533. static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
  534. const RecordType *RT = T->getAs<RecordType>();
  535. if (!RT)
  536. return nullptr;
  537. const RecordDecl *RD = RT->getDecl();
  538. if (RD->hasFlexibleArrayMember())
  539. return nullptr;
  540. const Type *Found = nullptr;
  541. // If this is a C++ record, check the bases first.
  542. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  543. for (const auto &I : CXXRD->bases()) {
  544. // Ignore empty records.
  545. if (isEmptyRecord(Context, I.getType(), true))
  546. continue;
  547. // If we already found an element then this isn't a single-element struct.
  548. if (Found)
  549. return nullptr;
  550. // If this is non-empty and not a single element struct, the composite
  551. // cannot be a single element struct.
  552. Found = isSingleElementStruct(I.getType(), Context);
  553. if (!Found)
  554. return nullptr;
  555. }
  556. }
  557. // Check for single element.
  558. for (const auto *FD : RD->fields()) {
  559. QualType FT = FD->getType();
  560. // Ignore empty fields.
  561. if (isEmptyField(Context, FD, true))
  562. continue;
  563. // If we already found an element then this isn't a single-element
  564. // struct.
  565. if (Found)
  566. return nullptr;
  567. // Treat single element arrays as the element.
  568. while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
  569. if (AT->getSize().getZExtValue() != 1)
  570. break;
  571. FT = AT->getElementType();
  572. }
  573. if (!isAggregateTypeForABI(FT)) {
  574. Found = FT.getTypePtr();
  575. } else {
  576. Found = isSingleElementStruct(FT, Context);
  577. if (!Found)
  578. return nullptr;
  579. }
  580. }
  581. // We don't consider a struct a single-element struct if it has
  582. // padding beyond the element type.
  583. if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
  584. return nullptr;
  585. return Found;
  586. }
  587. namespace {
  588. Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
  589. const ABIArgInfo &AI) {
  590. // This default implementation defers to the llvm backend's va_arg
  591. // instruction. It can handle only passing arguments directly
  592. // (typically only handled in the backend for primitive types), or
  593. // aggregates passed indirectly by pointer (NOTE: if the "byval"
  594. // flag has ABI impact in the callee, this implementation cannot
  595. // work.)
  596. // Only a few cases are covered here at the moment -- those needed
  597. // by the default abi.
  598. llvm::Value *Val;
  599. if (AI.isIndirect()) {
  600. assert(!AI.getPaddingType() &&
  601. "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
  602. assert(
  603. !AI.getIndirectRealign() &&
  604. "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
  605. auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
  606. CharUnits TyAlignForABI = TyInfo.Align;
  607. llvm::Type *BaseTy =
  608. llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
  609. llvm::Value *Addr =
  610. CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
  611. return Address(Addr, TyAlignForABI);
  612. } else {
  613. assert((AI.isDirect() || AI.isExtend()) &&
  614. "Unexpected ArgInfo Kind in generic VAArg emitter!");
  615. assert(!AI.getInReg() &&
  616. "Unexpected InReg seen in arginfo in generic VAArg emitter!");
  617. assert(!AI.getPaddingType() &&
  618. "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
  619. assert(!AI.getDirectOffset() &&
  620. "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
  621. assert(!AI.getCoerceToType() &&
  622. "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
  623. Address Temp = CGF.CreateMemTemp(Ty, "varet");
  624. Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
  625. CGF.Builder.CreateStore(Val, Temp);
  626. return Temp;
  627. }
  628. }
  629. /// DefaultABIInfo - The default implementation for ABI specific
  630. /// details. This implementation provides information which results in
  631. /// self-consistent and sensible LLVM IR generation, but does not
  632. /// conform to any particular ABI.
  633. class DefaultABIInfo : public ABIInfo {
  634. public:
  635. DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
  636. ABIArgInfo classifyReturnType(QualType RetTy) const;
  637. ABIArgInfo classifyArgumentType(QualType RetTy) const;
  638. void computeInfo(CGFunctionInfo &FI) const override {
  639. if (!getCXXABI().classifyReturnType(FI))
  640. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  641. for (auto &I : FI.arguments())
  642. I.info = classifyArgumentType(I.type);
  643. }
  644. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  645. QualType Ty) const override {
  646. return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
  647. }
  648. };
  649. class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
  650. public:
  651. DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
  652. : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
  653. };
  654. ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
  655. Ty = useFirstFieldIfTransparentUnion(Ty);
  656. if (isAggregateTypeForABI(Ty)) {
  657. // Records with non-trivial destructors/copy-constructors should not be
  658. // passed by value.
  659. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
  660. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  661. return getNaturalAlignIndirect(Ty);
  662. }
  663. // Treat an enum type as its underlying type.
  664. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  665. Ty = EnumTy->getDecl()->getIntegerType();
  666. ASTContext &Context = getContext();
  667. if (const auto *EIT = Ty->getAs<BitIntType>())
  668. if (EIT->getNumBits() >
  669. Context.getTypeSize(Context.getTargetInfo().hasInt128Type()
  670. ? Context.Int128Ty
  671. : Context.LongLongTy))
  672. return getNaturalAlignIndirect(Ty);
  673. return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
  674. : ABIArgInfo::getDirect());
  675. }
  676. ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
  677. if (RetTy->isVoidType())
  678. return ABIArgInfo::getIgnore();
  679. if (isAggregateTypeForABI(RetTy))
  680. return getNaturalAlignIndirect(RetTy);
  681. // Treat an enum type as its underlying type.
  682. if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
  683. RetTy = EnumTy->getDecl()->getIntegerType();
  684. if (const auto *EIT = RetTy->getAs<BitIntType>())
  685. if (EIT->getNumBits() >
  686. getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type()
  687. ? getContext().Int128Ty
  688. : getContext().LongLongTy))
  689. return getNaturalAlignIndirect(RetTy);
  690. return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
  691. : ABIArgInfo::getDirect());
  692. }
  693. //===----------------------------------------------------------------------===//
  694. // WebAssembly ABI Implementation
  695. //
  696. // This is a very simple ABI that relies a lot on DefaultABIInfo.
  697. //===----------------------------------------------------------------------===//
  698. class WebAssemblyABIInfo final : public SwiftABIInfo {
  699. public:
  700. enum ABIKind {
  701. MVP = 0,
  702. ExperimentalMV = 1,
  703. };
  704. private:
  705. DefaultABIInfo defaultInfo;
  706. ABIKind Kind;
  707. public:
  708. explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
  709. : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {}
  710. private:
  711. ABIArgInfo classifyReturnType(QualType RetTy) const;
  712. ABIArgInfo classifyArgumentType(QualType Ty) const;
  713. // DefaultABIInfo's classifyReturnType and classifyArgumentType are
  714. // non-virtual, but computeInfo and EmitVAArg are virtual, so we
  715. // overload them.
  716. void computeInfo(CGFunctionInfo &FI) const override {
  717. if (!getCXXABI().classifyReturnType(FI))
  718. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  719. for (auto &Arg : FI.arguments())
  720. Arg.info = classifyArgumentType(Arg.type);
  721. }
  722. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  723. QualType Ty) const override;
  724. bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
  725. bool asReturnValue) const override {
  726. return occupiesMoreThan(CGT, scalars, /*total*/ 4);
  727. }
  728. bool isSwiftErrorInRegister() const override {
  729. return false;
  730. }
  731. };
  732. class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
  733. public:
  734. explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
  735. WebAssemblyABIInfo::ABIKind K)
  736. : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {}
  737. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  738. CodeGen::CodeGenModule &CGM) const override {
  739. TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
  740. if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  741. if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
  742. llvm::Function *Fn = cast<llvm::Function>(GV);
  743. llvm::AttrBuilder B(GV->getContext());
  744. B.addAttribute("wasm-import-module", Attr->getImportModule());
  745. Fn->addFnAttrs(B);
  746. }
  747. if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
  748. llvm::Function *Fn = cast<llvm::Function>(GV);
  749. llvm::AttrBuilder B(GV->getContext());
  750. B.addAttribute("wasm-import-name", Attr->getImportName());
  751. Fn->addFnAttrs(B);
  752. }
  753. if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) {
  754. llvm::Function *Fn = cast<llvm::Function>(GV);
  755. llvm::AttrBuilder B(GV->getContext());
  756. B.addAttribute("wasm-export-name", Attr->getExportName());
  757. Fn->addFnAttrs(B);
  758. }
  759. }
  760. if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  761. llvm::Function *Fn = cast<llvm::Function>(GV);
  762. if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
  763. Fn->addFnAttr("no-prototype");
  764. }
  765. }
  766. };
  767. /// Classify argument of given type \p Ty.
  768. ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
  769. Ty = useFirstFieldIfTransparentUnion(Ty);
  770. if (isAggregateTypeForABI(Ty)) {
  771. // Records with non-trivial destructors/copy-constructors should not be
  772. // passed by value.
  773. if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
  774. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  775. // Ignore empty structs/unions.
  776. if (isEmptyRecord(getContext(), Ty, true))
  777. return ABIArgInfo::getIgnore();
  778. // Lower single-element structs to just pass a regular value. TODO: We
  779. // could do reasonable-size multiple-element structs too, using getExpand(),
  780. // though watch out for things like bitfields.
  781. if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
  782. return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
  783. // For the experimental multivalue ABI, fully expand all other aggregates
  784. if (Kind == ABIKind::ExperimentalMV) {
  785. const RecordType *RT = Ty->getAs<RecordType>();
  786. assert(RT);
  787. bool HasBitField = false;
  788. for (auto *Field : RT->getDecl()->fields()) {
  789. if (Field->isBitField()) {
  790. HasBitField = true;
  791. break;
  792. }
  793. }
  794. if (!HasBitField)
  795. return ABIArgInfo::getExpand();
  796. }
  797. }
  798. // Otherwise just do the default thing.
  799. return defaultInfo.classifyArgumentType(Ty);
  800. }
  801. ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
  802. if (isAggregateTypeForABI(RetTy)) {
  803. // Records with non-trivial destructors/copy-constructors should not be
  804. // returned by value.
  805. if (!getRecordArgABI(RetTy, getCXXABI())) {
  806. // Ignore empty structs/unions.
  807. if (isEmptyRecord(getContext(), RetTy, true))
  808. return ABIArgInfo::getIgnore();
  809. // Lower single-element structs to just return a regular value. TODO: We
  810. // could do reasonable-size multiple-element structs too, using
  811. // ABIArgInfo::getDirect().
  812. if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
  813. return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
  814. // For the experimental multivalue ABI, return all other aggregates
  815. if (Kind == ABIKind::ExperimentalMV)
  816. return ABIArgInfo::getDirect();
  817. }
  818. }
  819. // Otherwise just do the default thing.
  820. return defaultInfo.classifyReturnType(RetTy);
  821. }
  822. Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  823. QualType Ty) const {
  824. bool IsIndirect = isAggregateTypeForABI(Ty) &&
  825. !isEmptyRecord(getContext(), Ty, true) &&
  826. !isSingleElementStruct(Ty, getContext());
  827. return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
  828. getContext().getTypeInfoInChars(Ty),
  829. CharUnits::fromQuantity(4),
  830. /*AllowHigherAlign=*/true);
  831. }
  832. //===----------------------------------------------------------------------===//
  833. // le32/PNaCl bitcode ABI Implementation
  834. //
  835. // This is a simplified version of the x86_32 ABI. Arguments and return values
  836. // are always passed on the stack.
  837. //===----------------------------------------------------------------------===//
  838. class PNaClABIInfo : public ABIInfo {
  839. public:
  840. PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
  841. ABIArgInfo classifyReturnType(QualType RetTy) const;
  842. ABIArgInfo classifyArgumentType(QualType RetTy) const;
  843. void computeInfo(CGFunctionInfo &FI) const override;
  844. Address EmitVAArg(CodeGenFunction &CGF,
  845. Address VAListAddr, QualType Ty) const override;
  846. };
  847. class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
  848. public:
  849. PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
  850. : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {}
  851. };
  852. void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
  853. if (!getCXXABI().classifyReturnType(FI))
  854. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  855. for (auto &I : FI.arguments())
  856. I.info = classifyArgumentType(I.type);
  857. }
  858. Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  859. QualType Ty) const {
  860. // The PNaCL ABI is a bit odd, in that varargs don't use normal
  861. // function classification. Structs get passed directly for varargs
  862. // functions, through a rewriting transform in
  863. // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
  864. // this target to actually support a va_arg instructions with an
  865. // aggregate type, unlike other targets.
  866. return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
  867. }
  868. /// Classify argument of given type \p Ty.
  869. ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
  870. if (isAggregateTypeForABI(Ty)) {
  871. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
  872. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  873. return getNaturalAlignIndirect(Ty);
  874. } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
  875. // Treat an enum type as its underlying type.
  876. Ty = EnumTy->getDecl()->getIntegerType();
  877. } else if (Ty->isFloatingType()) {
  878. // Floating-point types don't go inreg.
  879. return ABIArgInfo::getDirect();
  880. } else if (const auto *EIT = Ty->getAs<BitIntType>()) {
  881. // Treat bit-precise integers as integers if <= 64, otherwise pass
  882. // indirectly.
  883. if (EIT->getNumBits() > 64)
  884. return getNaturalAlignIndirect(Ty);
  885. return ABIArgInfo::getDirect();
  886. }
  887. return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
  888. : ABIArgInfo::getDirect());
  889. }
  890. ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
  891. if (RetTy->isVoidType())
  892. return ABIArgInfo::getIgnore();
  893. // In the PNaCl ABI we always return records/structures on the stack.
  894. if (isAggregateTypeForABI(RetTy))
  895. return getNaturalAlignIndirect(RetTy);
  896. // Treat bit-precise integers as integers if <= 64, otherwise pass indirectly.
  897. if (const auto *EIT = RetTy->getAs<BitIntType>()) {
  898. if (EIT->getNumBits() > 64)
  899. return getNaturalAlignIndirect(RetTy);
  900. return ABIArgInfo::getDirect();
  901. }
  902. // Treat an enum type as its underlying type.
  903. if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
  904. RetTy = EnumTy->getDecl()->getIntegerType();
  905. return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
  906. : ABIArgInfo::getDirect());
  907. }
  908. /// IsX86_MMXType - Return true if this is an MMX type.
  909. bool IsX86_MMXType(llvm::Type *IRType) {
  910. // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
  911. return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
  912. cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
  913. IRType->getScalarSizeInBits() != 64;
  914. }
  915. static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
  916. StringRef Constraint,
  917. llvm::Type* Ty) {
  918. bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
  919. .Cases("y", "&y", "^Ym", true)
  920. .Default(false);
  921. if (IsMMXCons && Ty->isVectorTy()) {
  922. if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() !=
  923. 64) {
  924. // Invalid MMX constraint
  925. return nullptr;
  926. }
  927. return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
  928. }
  929. // No operation needed
  930. return Ty;
  931. }
  932. /// Returns true if this type can be passed in SSE registers with the
  933. /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
  934. static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
  935. if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
  936. if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
  937. if (BT->getKind() == BuiltinType::LongDouble) {
  938. if (&Context.getTargetInfo().getLongDoubleFormat() ==
  939. &llvm::APFloat::x87DoubleExtended())
  940. return false;
  941. }
  942. return true;
  943. }
  944. } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
  945. // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
  946. // registers specially.
  947. unsigned VecSize = Context.getTypeSize(VT);
  948. if (VecSize == 128 || VecSize == 256 || VecSize == 512)
  949. return true;
  950. }
  951. return false;
  952. }
  953. /// Returns true if this aggregate is small enough to be passed in SSE registers
  954. /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
  955. static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
  956. return NumMembers <= 4;
  957. }
  958. /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
  959. static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
  960. auto AI = ABIArgInfo::getDirect(T);
  961. AI.setInReg(true);
  962. AI.setCanBeFlattened(false);
  963. return AI;
  964. }
  965. //===----------------------------------------------------------------------===//
  966. // X86-32 ABI Implementation
  967. //===----------------------------------------------------------------------===//
  968. /// Similar to llvm::CCState, but for Clang.
  969. struct CCState {
  970. CCState(CGFunctionInfo &FI)
  971. : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {}
  972. llvm::SmallBitVector IsPreassigned;
  973. unsigned CC = CallingConv::CC_C;
  974. unsigned FreeRegs = 0;
  975. unsigned FreeSSERegs = 0;
  976. };
  977. /// X86_32ABIInfo - The X86-32 ABI information.
  978. class X86_32ABIInfo : public SwiftABIInfo {
  979. enum Class {
  980. Integer,
  981. Float
  982. };
  983. static const unsigned MinABIStackAlignInBytes = 4;
  984. bool IsDarwinVectorABI;
  985. bool IsRetSmallStructInRegABI;
  986. bool IsWin32StructABI;
  987. bool IsSoftFloatABI;
  988. bool IsMCUABI;
  989. bool IsLinuxABI;
  990. unsigned DefaultNumRegisterParameters;
  991. static bool isRegisterSize(unsigned Size) {
  992. return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
  993. }
  994. bool isHomogeneousAggregateBaseType(QualType Ty) const override {
  995. // FIXME: Assumes vectorcall is in use.
  996. return isX86VectorTypeForVectorCall(getContext(), Ty);
  997. }
  998. bool isHomogeneousAggregateSmallEnough(const Type *Ty,
  999. uint64_t NumMembers) const override {
  1000. // FIXME: Assumes vectorcall is in use.
  1001. return isX86VectorCallAggregateSmallEnough(NumMembers);
  1002. }
  1003. bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
  1004. /// getIndirectResult - Give a source type \arg Ty, return a suitable result
  1005. /// such that the argument will be passed in memory.
  1006. ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
  1007. ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
  1008. /// Return the alignment to use for the given type on the stack.
  1009. unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
  1010. Class classify(QualType Ty) const;
  1011. ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
  1012. ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
  1013. /// Updates the number of available free registers, returns
  1014. /// true if any registers were allocated.
  1015. bool updateFreeRegs(QualType Ty, CCState &State) const;
  1016. bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
  1017. bool &NeedsPadding) const;
  1018. bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
  1019. bool canExpandIndirectArgument(QualType Ty) const;
  1020. /// Rewrite the function info so that all memory arguments use
  1021. /// inalloca.
  1022. void rewriteWithInAlloca(CGFunctionInfo &FI) const;
  1023. void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
  1024. CharUnits &StackOffset, ABIArgInfo &Info,
  1025. QualType Type) const;
  1026. void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
  1027. public:
  1028. void computeInfo(CGFunctionInfo &FI) const override;
  1029. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  1030. QualType Ty) const override;
  1031. X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
  1032. bool RetSmallStructInRegABI, bool Win32StructABI,
  1033. unsigned NumRegisterParameters, bool SoftFloatABI)
  1034. : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
  1035. IsRetSmallStructInRegABI(RetSmallStructInRegABI),
  1036. IsWin32StructABI(Win32StructABI), IsSoftFloatABI(SoftFloatABI),
  1037. IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
  1038. IsLinuxABI(CGT.getTarget().getTriple().isOSLinux() ||
  1039. CGT.getTarget().getTriple().isOSCygMing()),
  1040. DefaultNumRegisterParameters(NumRegisterParameters) {}
  1041. bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
  1042. bool asReturnValue) const override {
  1043. // LLVM's x86-32 lowering currently only assigns up to three
  1044. // integer registers and three fp registers. Oddly, it'll use up to
  1045. // four vector registers for vectors, but those can overlap with the
  1046. // scalar registers.
  1047. return occupiesMoreThan(CGT, scalars, /*total*/ 3);
  1048. }
  1049. bool isSwiftErrorInRegister() const override {
  1050. // x86-32 lowering does not support passing swifterror in a register.
  1051. return false;
  1052. }
  1053. };
  1054. class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
  1055. public:
  1056. X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
  1057. bool RetSmallStructInRegABI, bool Win32StructABI,
  1058. unsigned NumRegisterParameters, bool SoftFloatABI)
  1059. : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>(
  1060. CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
  1061. NumRegisterParameters, SoftFloatABI)) {}
  1062. static bool isStructReturnInRegABI(
  1063. const llvm::Triple &Triple, const CodeGenOptions &Opts);
  1064. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  1065. CodeGen::CodeGenModule &CGM) const override;
  1066. int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
  1067. // Darwin uses different dwarf register numbers for EH.
  1068. if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
  1069. return 4;
  1070. }
  1071. bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  1072. llvm::Value *Address) const override;
  1073. llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
  1074. StringRef Constraint,
  1075. llvm::Type* Ty) const override {
  1076. return X86AdjustInlineAsmType(CGF, Constraint, Ty);
  1077. }
  1078. void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
  1079. std::string &Constraints,
  1080. std::vector<llvm::Type *> &ResultRegTypes,
  1081. std::vector<llvm::Type *> &ResultTruncRegTypes,
  1082. std::vector<LValue> &ResultRegDests,
  1083. std::string &AsmString,
  1084. unsigned NumOutputs) const override;
  1085. llvm::Constant *
  1086. getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
  1087. unsigned Sig = (0xeb << 0) | // jmp rel8
  1088. (0x06 << 8) | // .+0x08
  1089. ('v' << 16) |
  1090. ('2' << 24);
  1091. return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
  1092. }
  1093. StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
  1094. return "movl\t%ebp, %ebp"
  1095. "\t\t// marker for objc_retainAutoreleaseReturnValue";
  1096. }
  1097. };
  1098. }
  1099. /// Rewrite input constraint references after adding some output constraints.
  1100. /// In the case where there is one output and one input and we add one output,
  1101. /// we need to replace all operand references greater than or equal to 1:
  1102. /// mov $0, $1
  1103. /// mov eax, $1
  1104. /// The result will be:
  1105. /// mov $0, $2
  1106. /// mov eax, $2
  1107. static void rewriteInputConstraintReferences(unsigned FirstIn,
  1108. unsigned NumNewOuts,
  1109. std::string &AsmString) {
  1110. std::string Buf;
  1111. llvm::raw_string_ostream OS(Buf);
  1112. size_t Pos = 0;
  1113. while (Pos < AsmString.size()) {
  1114. size_t DollarStart = AsmString.find('$', Pos);
  1115. if (DollarStart == std::string::npos)
  1116. DollarStart = AsmString.size();
  1117. size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
  1118. if (DollarEnd == std::string::npos)
  1119. DollarEnd = AsmString.size();
  1120. OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
  1121. Pos = DollarEnd;
  1122. size_t NumDollars = DollarEnd - DollarStart;
  1123. if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
  1124. // We have an operand reference.
  1125. size_t DigitStart = Pos;
  1126. if (AsmString[DigitStart] == '{') {
  1127. OS << '{';
  1128. ++DigitStart;
  1129. }
  1130. size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
  1131. if (DigitEnd == std::string::npos)
  1132. DigitEnd = AsmString.size();
  1133. StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
  1134. unsigned OperandIndex;
  1135. if (!OperandStr.getAsInteger(10, OperandIndex)) {
  1136. if (OperandIndex >= FirstIn)
  1137. OperandIndex += NumNewOuts;
  1138. OS << OperandIndex;
  1139. } else {
  1140. OS << OperandStr;
  1141. }
  1142. Pos = DigitEnd;
  1143. }
  1144. }
  1145. AsmString = std::move(OS.str());
  1146. }
  1147. /// Add output constraints for EAX:EDX because they are return registers.
  1148. void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
  1149. CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
  1150. std::vector<llvm::Type *> &ResultRegTypes,
  1151. std::vector<llvm::Type *> &ResultTruncRegTypes,
  1152. std::vector<LValue> &ResultRegDests, std::string &AsmString,
  1153. unsigned NumOutputs) const {
  1154. uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
  1155. // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
  1156. // larger.
  1157. if (!Constraints.empty())
  1158. Constraints += ',';
  1159. if (RetWidth <= 32) {
  1160. Constraints += "={eax}";
  1161. ResultRegTypes.push_back(CGF.Int32Ty);
  1162. } else {
  1163. // Use the 'A' constraint for EAX:EDX.
  1164. Constraints += "=A";
  1165. ResultRegTypes.push_back(CGF.Int64Ty);
  1166. }
  1167. // Truncate EAX or EAX:EDX to an integer of the appropriate size.
  1168. llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
  1169. ResultTruncRegTypes.push_back(CoerceTy);
  1170. // Coerce the integer by bitcasting the return slot pointer.
  1171. ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF),
  1172. CoerceTy->getPointerTo()));
  1173. ResultRegDests.push_back(ReturnSlot);
  1174. rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
  1175. }
  1176. /// shouldReturnTypeInRegister - Determine if the given type should be
  1177. /// returned in a register (for the Darwin and MCU ABI).
  1178. bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
  1179. ASTContext &Context) const {
  1180. uint64_t Size = Context.getTypeSize(Ty);
  1181. // For i386, type must be register sized.
  1182. // For the MCU ABI, it only needs to be <= 8-byte
  1183. if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
  1184. return false;
  1185. if (Ty->isVectorType()) {
  1186. // 64- and 128- bit vectors inside structures are not returned in
  1187. // registers.
  1188. if (Size == 64 || Size == 128)
  1189. return false;
  1190. return true;
  1191. }
  1192. // If this is a builtin, pointer, enum, complex type, member pointer, or
  1193. // member function pointer it is ok.
  1194. if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
  1195. Ty->isAnyComplexType() || Ty->isEnumeralType() ||
  1196. Ty->isBlockPointerType() || Ty->isMemberPointerType())
  1197. return true;
  1198. // Arrays are treated like records.
  1199. if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
  1200. return shouldReturnTypeInRegister(AT->getElementType(), Context);
  1201. // Otherwise, it must be a record type.
  1202. const RecordType *RT = Ty->getAs<RecordType>();
  1203. if (!RT) return false;
  1204. // FIXME: Traverse bases here too.
  1205. // Structure types are passed in register if all fields would be
  1206. // passed in a register.
  1207. for (const auto *FD : RT->getDecl()->fields()) {
  1208. // Empty fields are ignored.
  1209. if (isEmptyField(Context, FD, true))
  1210. continue;
  1211. // Check fields recursively.
  1212. if (!shouldReturnTypeInRegister(FD->getType(), Context))
  1213. return false;
  1214. }
  1215. return true;
  1216. }
  1217. static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
  1218. // Treat complex types as the element type.
  1219. if (const ComplexType *CTy = Ty->getAs<ComplexType>())
  1220. Ty = CTy->getElementType();
  1221. // Check for a type which we know has a simple scalar argument-passing
  1222. // convention without any padding. (We're specifically looking for 32
  1223. // and 64-bit integer and integer-equivalents, float, and double.)
  1224. if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
  1225. !Ty->isEnumeralType() && !Ty->isBlockPointerType())
  1226. return false;
  1227. uint64_t Size = Context.getTypeSize(Ty);
  1228. return Size == 32 || Size == 64;
  1229. }
  1230. static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
  1231. uint64_t &Size) {
  1232. for (const auto *FD : RD->fields()) {
  1233. // Scalar arguments on the stack get 4 byte alignment on x86. If the
  1234. // argument is smaller than 32-bits, expanding the struct will create
  1235. // alignment padding.
  1236. if (!is32Or64BitBasicType(FD->getType(), Context))
  1237. return false;
  1238. // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
  1239. // how to expand them yet, and the predicate for telling if a bitfield still
  1240. // counts as "basic" is more complicated than what we were doing previously.
  1241. if (FD->isBitField())
  1242. return false;
  1243. Size += Context.getTypeSize(FD->getType());
  1244. }
  1245. return true;
  1246. }
  1247. static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
  1248. uint64_t &Size) {
  1249. // Don't do this if there are any non-empty bases.
  1250. for (const CXXBaseSpecifier &Base : RD->bases()) {
  1251. if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
  1252. Size))
  1253. return false;
  1254. }
  1255. if (!addFieldSizes(Context, RD, Size))
  1256. return false;
  1257. return true;
  1258. }
  1259. /// Test whether an argument type which is to be passed indirectly (on the
  1260. /// stack) would have the equivalent layout if it was expanded into separate
  1261. /// arguments. If so, we prefer to do the latter to avoid inhibiting
  1262. /// optimizations.
  1263. bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
  1264. // We can only expand structure types.
  1265. const RecordType *RT = Ty->getAs<RecordType>();
  1266. if (!RT)
  1267. return false;
  1268. const RecordDecl *RD = RT->getDecl();
  1269. uint64_t Size = 0;
  1270. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  1271. if (!IsWin32StructABI) {
  1272. // On non-Windows, we have to conservatively match our old bitcode
  1273. // prototypes in order to be ABI-compatible at the bitcode level.
  1274. if (!CXXRD->isCLike())
  1275. return false;
  1276. } else {
  1277. // Don't do this for dynamic classes.
  1278. if (CXXRD->isDynamicClass())
  1279. return false;
  1280. }
  1281. if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
  1282. return false;
  1283. } else {
  1284. if (!addFieldSizes(getContext(), RD, Size))
  1285. return false;
  1286. }
  1287. // We can do this if there was no alignment padding.
  1288. return Size == getContext().getTypeSize(Ty);
  1289. }
  1290. ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
  1291. // If the return value is indirect, then the hidden argument is consuming one
  1292. // integer register.
  1293. if (State.FreeRegs) {
  1294. --State.FreeRegs;
  1295. if (!IsMCUABI)
  1296. return getNaturalAlignIndirectInReg(RetTy);
  1297. }
  1298. return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
  1299. }
  1300. ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
  1301. CCState &State) const {
  1302. if (RetTy->isVoidType())
  1303. return ABIArgInfo::getIgnore();
  1304. const Type *Base = nullptr;
  1305. uint64_t NumElts = 0;
  1306. if ((State.CC == llvm::CallingConv::X86_VectorCall ||
  1307. State.CC == llvm::CallingConv::X86_RegCall) &&
  1308. isHomogeneousAggregate(RetTy, Base, NumElts)) {
  1309. // The LLVM struct type for such an aggregate should lower properly.
  1310. return ABIArgInfo::getDirect();
  1311. }
  1312. if (const VectorType *VT = RetTy->getAs<VectorType>()) {
  1313. // On Darwin, some vectors are returned in registers.
  1314. if (IsDarwinVectorABI) {
  1315. uint64_t Size = getContext().getTypeSize(RetTy);
  1316. // 128-bit vectors are a special case; they are returned in
  1317. // registers and we need to make sure to pick a type the LLVM
  1318. // backend will like.
  1319. if (Size == 128)
  1320. return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
  1321. llvm::Type::getInt64Ty(getVMContext()), 2));
  1322. // Always return in register if it fits in a general purpose
  1323. // register, or if it is 64 bits and has a single element.
  1324. if ((Size == 8 || Size == 16 || Size == 32) ||
  1325. (Size == 64 && VT->getNumElements() == 1))
  1326. return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
  1327. Size));
  1328. return getIndirectReturnResult(RetTy, State);
  1329. }
  1330. return ABIArgInfo::getDirect();
  1331. }
  1332. if (isAggregateTypeForABI(RetTy)) {
  1333. if (const RecordType *RT = RetTy->getAs<RecordType>()) {
  1334. // Structures with flexible arrays are always indirect.
  1335. if (RT->getDecl()->hasFlexibleArrayMember())
  1336. return getIndirectReturnResult(RetTy, State);
  1337. }
  1338. // If specified, structs and unions are always indirect.
  1339. if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
  1340. return getIndirectReturnResult(RetTy, State);
  1341. // Ignore empty structs/unions.
  1342. if (isEmptyRecord(getContext(), RetTy, true))
  1343. return ABIArgInfo::getIgnore();
  1344. // Return complex of _Float16 as <2 x half> so the backend will use xmm0.
  1345. if (const ComplexType *CT = RetTy->getAs<ComplexType>()) {
  1346. QualType ET = getContext().getCanonicalType(CT->getElementType());
  1347. if (ET->isFloat16Type())
  1348. return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
  1349. llvm::Type::getHalfTy(getVMContext()), 2));
  1350. }
  1351. // Small structures which are register sized are generally returned
  1352. // in a register.
  1353. if (shouldReturnTypeInRegister(RetTy, getContext())) {
  1354. uint64_t Size = getContext().getTypeSize(RetTy);
  1355. // As a special-case, if the struct is a "single-element" struct, and
  1356. // the field is of type "float" or "double", return it in a
  1357. // floating-point register. (MSVC does not apply this special case.)
  1358. // We apply a similar transformation for pointer types to improve the
  1359. // quality of the generated IR.
  1360. if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
  1361. if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
  1362. || SeltTy->hasPointerRepresentation())
  1363. return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
  1364. // FIXME: We should be able to narrow this integer in cases with dead
  1365. // padding.
  1366. return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
  1367. }
  1368. return getIndirectReturnResult(RetTy, State);
  1369. }
  1370. // Treat an enum type as its underlying type.
  1371. if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
  1372. RetTy = EnumTy->getDecl()->getIntegerType();
  1373. if (const auto *EIT = RetTy->getAs<BitIntType>())
  1374. if (EIT->getNumBits() > 64)
  1375. return getIndirectReturnResult(RetTy, State);
  1376. return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
  1377. : ABIArgInfo::getDirect());
  1378. }
  1379. static bool isSIMDVectorType(ASTContext &Context, QualType Ty) {
  1380. return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
  1381. }
  1382. static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) {
  1383. const RecordType *RT = Ty->getAs<RecordType>();
  1384. if (!RT)
  1385. return false;
  1386. const RecordDecl *RD = RT->getDecl();
  1387. // If this is a C++ record, check the bases first.
  1388. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  1389. for (const auto &I : CXXRD->bases())
  1390. if (!isRecordWithSIMDVectorType(Context, I.getType()))
  1391. return false;
  1392. for (const auto *i : RD->fields()) {
  1393. QualType FT = i->getType();
  1394. if (isSIMDVectorType(Context, FT))
  1395. return true;
  1396. if (isRecordWithSIMDVectorType(Context, FT))
  1397. return true;
  1398. }
  1399. return false;
  1400. }
  1401. unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
  1402. unsigned Align) const {
  1403. // Otherwise, if the alignment is less than or equal to the minimum ABI
  1404. // alignment, just use the default; the backend will handle this.
  1405. if (Align <= MinABIStackAlignInBytes)
  1406. return 0; // Use default alignment.
  1407. if (IsLinuxABI) {
  1408. // Exclude other System V OS (e.g Darwin, PS4 and FreeBSD) since we don't
  1409. // want to spend any effort dealing with the ramifications of ABI breaks.
  1410. //
  1411. // If the vector type is __m128/__m256/__m512, return the default alignment.
  1412. if (Ty->isVectorType() && (Align == 16 || Align == 32 || Align == 64))
  1413. return Align;
  1414. }
  1415. // On non-Darwin, the stack type alignment is always 4.
  1416. if (!IsDarwinVectorABI) {
  1417. // Set explicit alignment, since we may need to realign the top.
  1418. return MinABIStackAlignInBytes;
  1419. }
  1420. // Otherwise, if the type contains an SSE vector type, the alignment is 16.
  1421. if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) ||
  1422. isRecordWithSIMDVectorType(getContext(), Ty)))
  1423. return 16;
  1424. return MinABIStackAlignInBytes;
  1425. }
  1426. ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
  1427. CCState &State) const {
  1428. if (!ByVal) {
  1429. if (State.FreeRegs) {
  1430. --State.FreeRegs; // Non-byval indirects just use one pointer.
  1431. if (!IsMCUABI)
  1432. return getNaturalAlignIndirectInReg(Ty);
  1433. }
  1434. return getNaturalAlignIndirect(Ty, false);
  1435. }
  1436. // Compute the byval alignment.
  1437. unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
  1438. unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
  1439. if (StackAlign == 0)
  1440. return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
  1441. // If the stack alignment is less than the type alignment, realign the
  1442. // argument.
  1443. bool Realign = TypeAlign > StackAlign;
  1444. return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
  1445. /*ByVal=*/true, Realign);
  1446. }
  1447. X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
  1448. const Type *T = isSingleElementStruct(Ty, getContext());
  1449. if (!T)
  1450. T = Ty.getTypePtr();
  1451. if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
  1452. BuiltinType::Kind K = BT->getKind();
  1453. if (K == BuiltinType::Float || K == BuiltinType::Double)
  1454. return Float;
  1455. }
  1456. return Integer;
  1457. }
  1458. bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
  1459. if (!IsSoftFloatABI) {
  1460. Class C = classify(Ty);
  1461. if (C == Float)
  1462. return false;
  1463. }
  1464. unsigned Size = getContext().getTypeSize(Ty);
  1465. unsigned SizeInRegs = (Size + 31) / 32;
  1466. if (SizeInRegs == 0)
  1467. return false;
  1468. if (!IsMCUABI) {
  1469. if (SizeInRegs > State.FreeRegs) {
  1470. State.FreeRegs = 0;
  1471. return false;
  1472. }
  1473. } else {
  1474. // The MCU psABI allows passing parameters in-reg even if there are
  1475. // earlier parameters that are passed on the stack. Also,
  1476. // it does not allow passing >8-byte structs in-register,
  1477. // even if there are 3 free registers available.
  1478. if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
  1479. return false;
  1480. }
  1481. State.FreeRegs -= SizeInRegs;
  1482. return true;
  1483. }
  1484. bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
  1485. bool &InReg,
  1486. bool &NeedsPadding) const {
  1487. // On Windows, aggregates other than HFAs are never passed in registers, and
  1488. // they do not consume register slots. Homogenous floating-point aggregates
  1489. // (HFAs) have already been dealt with at this point.
  1490. if (IsWin32StructABI && isAggregateTypeForABI(Ty))
  1491. return false;
  1492. NeedsPadding = false;
  1493. InReg = !IsMCUABI;
  1494. if (!updateFreeRegs(Ty, State))
  1495. return false;
  1496. if (IsMCUABI)
  1497. return true;
  1498. if (State.CC == llvm::CallingConv::X86_FastCall ||
  1499. State.CC == llvm::CallingConv::X86_VectorCall ||
  1500. State.CC == llvm::CallingConv::X86_RegCall) {
  1501. if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
  1502. NeedsPadding = true;
  1503. return false;
  1504. }
  1505. return true;
  1506. }
  1507. bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
  1508. if (!updateFreeRegs(Ty, State))
  1509. return false;
  1510. if (IsMCUABI)
  1511. return false;
  1512. if (State.CC == llvm::CallingConv::X86_FastCall ||
  1513. State.CC == llvm::CallingConv::X86_VectorCall ||
  1514. State.CC == llvm::CallingConv::X86_RegCall) {
  1515. if (getContext().getTypeSize(Ty) > 32)
  1516. return false;
  1517. return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
  1518. Ty->isReferenceType());
  1519. }
  1520. return true;
  1521. }
  1522. void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
  1523. // Vectorcall x86 works subtly different than in x64, so the format is
  1524. // a bit different than the x64 version. First, all vector types (not HVAs)
  1525. // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
  1526. // This differs from the x64 implementation, where the first 6 by INDEX get
  1527. // registers.
  1528. // In the second pass over the arguments, HVAs are passed in the remaining
  1529. // vector registers if possible, or indirectly by address. The address will be
  1530. // passed in ECX/EDX if available. Any other arguments are passed according to
  1531. // the usual fastcall rules.
  1532. MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
  1533. for (int I = 0, E = Args.size(); I < E; ++I) {
  1534. const Type *Base = nullptr;
  1535. uint64_t NumElts = 0;
  1536. const QualType &Ty = Args[I].type;
  1537. if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
  1538. isHomogeneousAggregate(Ty, Base, NumElts)) {
  1539. if (State.FreeSSERegs >= NumElts) {
  1540. State.FreeSSERegs -= NumElts;
  1541. Args[I].info = ABIArgInfo::getDirectInReg();
  1542. State.IsPreassigned.set(I);
  1543. }
  1544. }
  1545. }
  1546. }
  1547. ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
  1548. CCState &State) const {
  1549. // FIXME: Set alignment on indirect arguments.
  1550. bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
  1551. bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
  1552. bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
  1553. Ty = useFirstFieldIfTransparentUnion(Ty);
  1554. TypeInfo TI = getContext().getTypeInfo(Ty);
  1555. // Check with the C++ ABI first.
  1556. const RecordType *RT = Ty->getAs<RecordType>();
  1557. if (RT) {
  1558. CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
  1559. if (RAA == CGCXXABI::RAA_Indirect) {
  1560. return getIndirectResult(Ty, false, State);
  1561. } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
  1562. // The field index doesn't matter, we'll fix it up later.
  1563. return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
  1564. }
  1565. }
  1566. // Regcall uses the concept of a homogenous vector aggregate, similar
  1567. // to other targets.
  1568. const Type *Base = nullptr;
  1569. uint64_t NumElts = 0;
  1570. if ((IsRegCall || IsVectorCall) &&
  1571. isHomogeneousAggregate(Ty, Base, NumElts)) {
  1572. if (State.FreeSSERegs >= NumElts) {
  1573. State.FreeSSERegs -= NumElts;
  1574. // Vectorcall passes HVAs directly and does not flatten them, but regcall
  1575. // does.
  1576. if (IsVectorCall)
  1577. return getDirectX86Hva();
  1578. if (Ty->isBuiltinType() || Ty->isVectorType())
  1579. return ABIArgInfo::getDirect();
  1580. return ABIArgInfo::getExpand();
  1581. }
  1582. return getIndirectResult(Ty, /*ByVal=*/false, State);
  1583. }
  1584. if (isAggregateTypeForABI(Ty)) {
  1585. // Structures with flexible arrays are always indirect.
  1586. // FIXME: This should not be byval!
  1587. if (RT && RT->getDecl()->hasFlexibleArrayMember())
  1588. return getIndirectResult(Ty, true, State);
  1589. // Ignore empty structs/unions on non-Windows.
  1590. if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
  1591. return ABIArgInfo::getIgnore();
  1592. llvm::LLVMContext &LLVMContext = getVMContext();
  1593. llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
  1594. bool NeedsPadding = false;
  1595. bool InReg;
  1596. if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
  1597. unsigned SizeInRegs = (TI.Width + 31) / 32;
  1598. SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
  1599. llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
  1600. if (InReg)
  1601. return ABIArgInfo::getDirectInReg(Result);
  1602. else
  1603. return ABIArgInfo::getDirect(Result);
  1604. }
  1605. llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
  1606. // Pass over-aligned aggregates on Windows indirectly. This behavior was
  1607. // added in MSVC 2015.
  1608. if (IsWin32StructABI && TI.isAlignRequired() && TI.Align > 32)
  1609. return getIndirectResult(Ty, /*ByVal=*/false, State);
  1610. // Expand small (<= 128-bit) record types when we know that the stack layout
  1611. // of those arguments will match the struct. This is important because the
  1612. // LLVM backend isn't smart enough to remove byval, which inhibits many
  1613. // optimizations.
  1614. // Don't do this for the MCU if there are still free integer registers
  1615. // (see X86_64 ABI for full explanation).
  1616. if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
  1617. canExpandIndirectArgument(Ty))
  1618. return ABIArgInfo::getExpandWithPadding(
  1619. IsFastCall || IsVectorCall || IsRegCall, PaddingType);
  1620. return getIndirectResult(Ty, true, State);
  1621. }
  1622. if (const VectorType *VT = Ty->getAs<VectorType>()) {
  1623. // On Windows, vectors are passed directly if registers are available, or
  1624. // indirectly if not. This avoids the need to align argument memory. Pass
  1625. // user-defined vector types larger than 512 bits indirectly for simplicity.
  1626. if (IsWin32StructABI) {
  1627. if (TI.Width <= 512 && State.FreeSSERegs > 0) {
  1628. --State.FreeSSERegs;
  1629. return ABIArgInfo::getDirectInReg();
  1630. }
  1631. return getIndirectResult(Ty, /*ByVal=*/false, State);
  1632. }
  1633. // On Darwin, some vectors are passed in memory, we handle this by passing
  1634. // it as an i8/i16/i32/i64.
  1635. if (IsDarwinVectorABI) {
  1636. if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
  1637. (TI.Width == 64 && VT->getNumElements() == 1))
  1638. return ABIArgInfo::getDirect(
  1639. llvm::IntegerType::get(getVMContext(), TI.Width));
  1640. }
  1641. if (IsX86_MMXType(CGT.ConvertType(Ty)))
  1642. return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
  1643. return ABIArgInfo::getDirect();
  1644. }
  1645. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  1646. Ty = EnumTy->getDecl()->getIntegerType();
  1647. bool InReg = shouldPrimitiveUseInReg(Ty, State);
  1648. if (isPromotableIntegerTypeForABI(Ty)) {
  1649. if (InReg)
  1650. return ABIArgInfo::getExtendInReg(Ty);
  1651. return ABIArgInfo::getExtend(Ty);
  1652. }
  1653. if (const auto *EIT = Ty->getAs<BitIntType>()) {
  1654. if (EIT->getNumBits() <= 64) {
  1655. if (InReg)
  1656. return ABIArgInfo::getDirectInReg();
  1657. return ABIArgInfo::getDirect();
  1658. }
  1659. return getIndirectResult(Ty, /*ByVal=*/false, State);
  1660. }
  1661. if (InReg)
  1662. return ABIArgInfo::getDirectInReg();
  1663. return ABIArgInfo::getDirect();
  1664. }
  1665. void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
  1666. CCState State(FI);
  1667. if (IsMCUABI)
  1668. State.FreeRegs = 3;
  1669. else if (State.CC == llvm::CallingConv::X86_FastCall) {
  1670. State.FreeRegs = 2;
  1671. State.FreeSSERegs = 3;
  1672. } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
  1673. State.FreeRegs = 2;
  1674. State.FreeSSERegs = 6;
  1675. } else if (FI.getHasRegParm())
  1676. State.FreeRegs = FI.getRegParm();
  1677. else if (State.CC == llvm::CallingConv::X86_RegCall) {
  1678. State.FreeRegs = 5;
  1679. State.FreeSSERegs = 8;
  1680. } else if (IsWin32StructABI) {
  1681. // Since MSVC 2015, the first three SSE vectors have been passed in
  1682. // registers. The rest are passed indirectly.
  1683. State.FreeRegs = DefaultNumRegisterParameters;
  1684. State.FreeSSERegs = 3;
  1685. } else
  1686. State.FreeRegs = DefaultNumRegisterParameters;
  1687. if (!::classifyReturnType(getCXXABI(), FI, *this)) {
  1688. FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
  1689. } else if (FI.getReturnInfo().isIndirect()) {
  1690. // The C++ ABI is not aware of register usage, so we have to check if the
  1691. // return value was sret and put it in a register ourselves if appropriate.
  1692. if (State.FreeRegs) {
  1693. --State.FreeRegs; // The sret parameter consumes a register.
  1694. if (!IsMCUABI)
  1695. FI.getReturnInfo().setInReg(true);
  1696. }
  1697. }
  1698. // The chain argument effectively gives us another free register.
  1699. if (FI.isChainCall())
  1700. ++State.FreeRegs;
  1701. // For vectorcall, do a first pass over the arguments, assigning FP and vector
  1702. // arguments to XMM registers as available.
  1703. if (State.CC == llvm::CallingConv::X86_VectorCall)
  1704. runVectorCallFirstPass(FI, State);
  1705. bool UsedInAlloca = false;
  1706. MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
  1707. for (int I = 0, E = Args.size(); I < E; ++I) {
  1708. // Skip arguments that have already been assigned.
  1709. if (State.IsPreassigned.test(I))
  1710. continue;
  1711. Args[I].info = classifyArgumentType(Args[I].type, State);
  1712. UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
  1713. }
  1714. // If we needed to use inalloca for any argument, do a second pass and rewrite
  1715. // all the memory arguments to use inalloca.
  1716. if (UsedInAlloca)
  1717. rewriteWithInAlloca(FI);
  1718. }
  1719. void
  1720. X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
  1721. CharUnits &StackOffset, ABIArgInfo &Info,
  1722. QualType Type) const {
  1723. // Arguments are always 4-byte-aligned.
  1724. CharUnits WordSize = CharUnits::fromQuantity(4);
  1725. assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
  1726. // sret pointers and indirect things will require an extra pointer
  1727. // indirection, unless they are byval. Most things are byval, and will not
  1728. // require this indirection.
  1729. bool IsIndirect = false;
  1730. if (Info.isIndirect() && !Info.getIndirectByVal())
  1731. IsIndirect = true;
  1732. Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
  1733. llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
  1734. if (IsIndirect)
  1735. LLTy = LLTy->getPointerTo(0);
  1736. FrameFields.push_back(LLTy);
  1737. StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
  1738. // Insert padding bytes to respect alignment.
  1739. CharUnits FieldEnd = StackOffset;
  1740. StackOffset = FieldEnd.alignTo(WordSize);
  1741. if (StackOffset != FieldEnd) {
  1742. CharUnits NumBytes = StackOffset - FieldEnd;
  1743. llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
  1744. Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
  1745. FrameFields.push_back(Ty);
  1746. }
  1747. }
  1748. static bool isArgInAlloca(const ABIArgInfo &Info) {
  1749. // Leave ignored and inreg arguments alone.
  1750. switch (Info.getKind()) {
  1751. case ABIArgInfo::InAlloca:
  1752. return true;
  1753. case ABIArgInfo::Ignore:
  1754. case ABIArgInfo::IndirectAliased:
  1755. return false;
  1756. case ABIArgInfo::Indirect:
  1757. case ABIArgInfo::Direct:
  1758. case ABIArgInfo::Extend:
  1759. return !Info.getInReg();
  1760. case ABIArgInfo::Expand:
  1761. case ABIArgInfo::CoerceAndExpand:
  1762. // These are aggregate types which are never passed in registers when
  1763. // inalloca is involved.
  1764. return true;
  1765. }
  1766. llvm_unreachable("invalid enum");
  1767. }
  1768. void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
  1769. assert(IsWin32StructABI && "inalloca only supported on win32");
  1770. // Build a packed struct type for all of the arguments in memory.
  1771. SmallVector<llvm::Type *, 6> FrameFields;
  1772. // The stack alignment is always 4.
  1773. CharUnits StackAlign = CharUnits::fromQuantity(4);
  1774. CharUnits StackOffset;
  1775. CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
  1776. // Put 'this' into the struct before 'sret', if necessary.
  1777. bool IsThisCall =
  1778. FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
  1779. ABIArgInfo &Ret = FI.getReturnInfo();
  1780. if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
  1781. isArgInAlloca(I->info)) {
  1782. addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
  1783. ++I;
  1784. }
  1785. // Put the sret parameter into the inalloca struct if it's in memory.
  1786. if (Ret.isIndirect() && !Ret.getInReg()) {
  1787. addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
  1788. // On Windows, the hidden sret parameter is always returned in eax.
  1789. Ret.setInAllocaSRet(IsWin32StructABI);
  1790. }
  1791. // Skip the 'this' parameter in ecx.
  1792. if (IsThisCall)
  1793. ++I;
  1794. // Put arguments passed in memory into the struct.
  1795. for (; I != E; ++I) {
  1796. if (isArgInAlloca(I->info))
  1797. addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
  1798. }
  1799. FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
  1800. /*isPacked=*/true),
  1801. StackAlign);
  1802. }
  1803. Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
  1804. Address VAListAddr, QualType Ty) const {
  1805. auto TypeInfo = getContext().getTypeInfoInChars(Ty);
  1806. // x86-32 changes the alignment of certain arguments on the stack.
  1807. //
  1808. // Just messing with TypeInfo like this works because we never pass
  1809. // anything indirectly.
  1810. TypeInfo.Align = CharUnits::fromQuantity(
  1811. getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity()));
  1812. return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
  1813. TypeInfo, CharUnits::fromQuantity(4),
  1814. /*AllowHigherAlign*/ true);
  1815. }
  1816. bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
  1817. const llvm::Triple &Triple, const CodeGenOptions &Opts) {
  1818. assert(Triple.getArch() == llvm::Triple::x86);
  1819. switch (Opts.getStructReturnConvention()) {
  1820. case CodeGenOptions::SRCK_Default:
  1821. break;
  1822. case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
  1823. return false;
  1824. case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
  1825. return true;
  1826. }
  1827. if (Triple.isOSDarwin() || Triple.isOSIAMCU())
  1828. return true;
  1829. switch (Triple.getOS()) {
  1830. case llvm::Triple::DragonFly:
  1831. case llvm::Triple::FreeBSD:
  1832. case llvm::Triple::OpenBSD:
  1833. case llvm::Triple::Win32:
  1834. return true;
  1835. default:
  1836. return false;
  1837. }
  1838. }
  1839. static void addX86InterruptAttrs(const FunctionDecl *FD, llvm::GlobalValue *GV,
  1840. CodeGen::CodeGenModule &CGM) {
  1841. if (!FD->hasAttr<AnyX86InterruptAttr>())
  1842. return;
  1843. llvm::Function *Fn = cast<llvm::Function>(GV);
  1844. Fn->setCallingConv(llvm::CallingConv::X86_INTR);
  1845. if (FD->getNumParams() == 0)
  1846. return;
  1847. auto PtrTy = cast<PointerType>(FD->getParamDecl(0)->getType());
  1848. llvm::Type *ByValTy = CGM.getTypes().ConvertType(PtrTy->getPointeeType());
  1849. llvm::Attribute NewAttr = llvm::Attribute::getWithByValType(
  1850. Fn->getContext(), ByValTy);
  1851. Fn->addParamAttr(0, NewAttr);
  1852. }
  1853. void X86_32TargetCodeGenInfo::setTargetAttributes(
  1854. const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
  1855. if (GV->isDeclaration())
  1856. return;
  1857. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  1858. if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
  1859. llvm::Function *Fn = cast<llvm::Function>(GV);
  1860. Fn->addFnAttr("stackrealign");
  1861. }
  1862. addX86InterruptAttrs(FD, GV, CGM);
  1863. }
  1864. }
  1865. bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
  1866. CodeGen::CodeGenFunction &CGF,
  1867. llvm::Value *Address) const {
  1868. CodeGen::CGBuilderTy &Builder = CGF.Builder;
  1869. llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
  1870. // 0-7 are the eight integer registers; the order is different
  1871. // on Darwin (for EH), but the range is the same.
  1872. // 8 is %eip.
  1873. AssignToArrayRange(Builder, Address, Four8, 0, 8);
  1874. if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
  1875. // 12-16 are st(0..4). Not sure why we stop at 4.
  1876. // These have size 16, which is sizeof(long double) on
  1877. // platforms with 8-byte alignment for that type.
  1878. llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
  1879. AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
  1880. } else {
  1881. // 9 is %eflags, which doesn't get a size on Darwin for some
  1882. // reason.
  1883. Builder.CreateAlignedStore(
  1884. Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
  1885. CharUnits::One());
  1886. // 11-16 are st(0..5). Not sure why we stop at 5.
  1887. // These have size 12, which is sizeof(long double) on
  1888. // platforms with 4-byte alignment for that type.
  1889. llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
  1890. AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
  1891. }
  1892. return false;
  1893. }
  1894. //===----------------------------------------------------------------------===//
  1895. // X86-64 ABI Implementation
  1896. //===----------------------------------------------------------------------===//
  1897. namespace {
  1898. /// The AVX ABI level for X86 targets.
  1899. enum class X86AVXABILevel {
  1900. None,
  1901. AVX,
  1902. AVX512
  1903. };
  1904. /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
  1905. static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
  1906. switch (AVXLevel) {
  1907. case X86AVXABILevel::AVX512:
  1908. return 512;
  1909. case X86AVXABILevel::AVX:
  1910. return 256;
  1911. case X86AVXABILevel::None:
  1912. return 128;
  1913. }
  1914. llvm_unreachable("Unknown AVXLevel");
  1915. }
  1916. /// X86_64ABIInfo - The X86_64 ABI information.
  1917. class X86_64ABIInfo : public SwiftABIInfo {
  1918. enum Class {
  1919. Integer = 0,
  1920. SSE,
  1921. SSEUp,
  1922. X87,
  1923. X87Up,
  1924. ComplexX87,
  1925. NoClass,
  1926. Memory
  1927. };
  1928. /// merge - Implement the X86_64 ABI merging algorithm.
  1929. ///
  1930. /// Merge an accumulating classification \arg Accum with a field
  1931. /// classification \arg Field.
  1932. ///
  1933. /// \param Accum - The accumulating classification. This should
  1934. /// always be either NoClass or the result of a previous merge
  1935. /// call. In addition, this should never be Memory (the caller
  1936. /// should just return Memory for the aggregate).
  1937. static Class merge(Class Accum, Class Field);
  1938. /// postMerge - Implement the X86_64 ABI post merging algorithm.
  1939. ///
  1940. /// Post merger cleanup, reduces a malformed Hi and Lo pair to
  1941. /// final MEMORY or SSE classes when necessary.
  1942. ///
  1943. /// \param AggregateSize - The size of the current aggregate in
  1944. /// the classification process.
  1945. ///
  1946. /// \param Lo - The classification for the parts of the type
  1947. /// residing in the low word of the containing object.
  1948. ///
  1949. /// \param Hi - The classification for the parts of the type
  1950. /// residing in the higher words of the containing object.
  1951. ///
  1952. void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
  1953. /// classify - Determine the x86_64 register classes in which the
  1954. /// given type T should be passed.
  1955. ///
  1956. /// \param Lo - The classification for the parts of the type
  1957. /// residing in the low word of the containing object.
  1958. ///
  1959. /// \param Hi - The classification for the parts of the type
  1960. /// residing in the high word of the containing object.
  1961. ///
  1962. /// \param OffsetBase - The bit offset of this type in the
  1963. /// containing object. Some parameters are classified different
  1964. /// depending on whether they straddle an eightbyte boundary.
  1965. ///
  1966. /// \param isNamedArg - Whether the argument in question is a "named"
  1967. /// argument, as used in AMD64-ABI 3.5.7.
  1968. ///
  1969. /// If a word is unused its result will be NoClass; if a type should
  1970. /// be passed in Memory then at least the classification of \arg Lo
  1971. /// will be Memory.
  1972. ///
  1973. /// The \arg Lo class will be NoClass iff the argument is ignored.
  1974. ///
  1975. /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
  1976. /// also be ComplexX87.
  1977. void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
  1978. bool isNamedArg) const;
  1979. llvm::Type *GetByteVectorType(QualType Ty) const;
  1980. llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
  1981. unsigned IROffset, QualType SourceTy,
  1982. unsigned SourceOffset) const;
  1983. llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
  1984. unsigned IROffset, QualType SourceTy,
  1985. unsigned SourceOffset) const;
  1986. /// getIndirectResult - Give a source type \arg Ty, return a suitable result
  1987. /// such that the argument will be returned in memory.
  1988. ABIArgInfo getIndirectReturnResult(QualType Ty) const;
  1989. /// getIndirectResult - Give a source type \arg Ty, return a suitable result
  1990. /// such that the argument will be passed in memory.
  1991. ///
  1992. /// \param freeIntRegs - The number of free integer registers remaining
  1993. /// available.
  1994. ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
  1995. ABIArgInfo classifyReturnType(QualType RetTy) const;
  1996. ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
  1997. unsigned &neededInt, unsigned &neededSSE,
  1998. bool isNamedArg) const;
  1999. ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
  2000. unsigned &NeededSSE) const;
  2001. ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
  2002. unsigned &NeededSSE) const;
  2003. bool IsIllegalVectorType(QualType Ty) const;
  2004. /// The 0.98 ABI revision clarified a lot of ambiguities,
  2005. /// unfortunately in ways that were not always consistent with
  2006. /// certain previous compilers. In particular, platforms which
  2007. /// required strict binary compatibility with older versions of GCC
  2008. /// may need to exempt themselves.
  2009. bool honorsRevision0_98() const {
  2010. return !getTarget().getTriple().isOSDarwin();
  2011. }
  2012. /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
  2013. /// classify it as INTEGER (for compatibility with older clang compilers).
  2014. bool classifyIntegerMMXAsSSE() const {
  2015. // Clang <= 3.8 did not do this.
  2016. if (getContext().getLangOpts().getClangABICompat() <=
  2017. LangOptions::ClangABI::Ver3_8)
  2018. return false;
  2019. const llvm::Triple &Triple = getTarget().getTriple();
  2020. if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
  2021. return false;
  2022. if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
  2023. return false;
  2024. return true;
  2025. }
  2026. // GCC classifies vectors of __int128 as memory.
  2027. bool passInt128VectorsInMem() const {
  2028. // Clang <= 9.0 did not do this.
  2029. if (getContext().getLangOpts().getClangABICompat() <=
  2030. LangOptions::ClangABI::Ver9)
  2031. return false;
  2032. const llvm::Triple &T = getTarget().getTriple();
  2033. return T.isOSLinux() || T.isOSNetBSD();
  2034. }
  2035. X86AVXABILevel AVXLevel;
  2036. // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
  2037. // 64-bit hardware.
  2038. bool Has64BitPointers;
  2039. public:
  2040. X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
  2041. SwiftABIInfo(CGT), AVXLevel(AVXLevel),
  2042. Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
  2043. }
  2044. bool isPassedUsingAVXType(QualType type) const {
  2045. unsigned neededInt, neededSSE;
  2046. // The freeIntRegs argument doesn't matter here.
  2047. ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
  2048. /*isNamedArg*/true);
  2049. if (info.isDirect()) {
  2050. llvm::Type *ty = info.getCoerceToType();
  2051. if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
  2052. return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128;
  2053. }
  2054. return false;
  2055. }
  2056. void computeInfo(CGFunctionInfo &FI) const override;
  2057. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  2058. QualType Ty) const override;
  2059. Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
  2060. QualType Ty) const override;
  2061. bool has64BitPointers() const {
  2062. return Has64BitPointers;
  2063. }
  2064. bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
  2065. bool asReturnValue) const override {
  2066. return occupiesMoreThan(CGT, scalars, /*total*/ 4);
  2067. }
  2068. bool isSwiftErrorInRegister() const override {
  2069. return true;
  2070. }
  2071. };
  2072. /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
  2073. class WinX86_64ABIInfo : public SwiftABIInfo {
  2074. public:
  2075. WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
  2076. : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
  2077. IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
  2078. void computeInfo(CGFunctionInfo &FI) const override;
  2079. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  2080. QualType Ty) const override;
  2081. bool isHomogeneousAggregateBaseType(QualType Ty) const override {
  2082. // FIXME: Assumes vectorcall is in use.
  2083. return isX86VectorTypeForVectorCall(getContext(), Ty);
  2084. }
  2085. bool isHomogeneousAggregateSmallEnough(const Type *Ty,
  2086. uint64_t NumMembers) const override {
  2087. // FIXME: Assumes vectorcall is in use.
  2088. return isX86VectorCallAggregateSmallEnough(NumMembers);
  2089. }
  2090. bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
  2091. bool asReturnValue) const override {
  2092. return occupiesMoreThan(CGT, scalars, /*total*/ 4);
  2093. }
  2094. bool isSwiftErrorInRegister() const override {
  2095. return true;
  2096. }
  2097. private:
  2098. ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
  2099. bool IsVectorCall, bool IsRegCall) const;
  2100. ABIArgInfo reclassifyHvaArgForVectorCall(QualType Ty, unsigned &FreeSSERegs,
  2101. const ABIArgInfo &current) const;
  2102. X86AVXABILevel AVXLevel;
  2103. bool IsMingw64;
  2104. };
  2105. class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
  2106. public:
  2107. X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
  2108. : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {}
  2109. const X86_64ABIInfo &getABIInfo() const {
  2110. return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
  2111. }
  2112. /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
  2113. /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations.
  2114. bool markARCOptimizedReturnCallsAsNoTail() const override { return true; }
  2115. int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
  2116. return 7;
  2117. }
  2118. bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  2119. llvm::Value *Address) const override {
  2120. llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
  2121. // 0-15 are the 16 integer registers.
  2122. // 16 is %rip.
  2123. AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
  2124. return false;
  2125. }
  2126. llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
  2127. StringRef Constraint,
  2128. llvm::Type* Ty) const override {
  2129. return X86AdjustInlineAsmType(CGF, Constraint, Ty);
  2130. }
  2131. bool isNoProtoCallVariadic(const CallArgList &args,
  2132. const FunctionNoProtoType *fnType) const override {
  2133. // The default CC on x86-64 sets %al to the number of SSA
  2134. // registers used, and GCC sets this when calling an unprototyped
  2135. // function, so we override the default behavior. However, don't do
  2136. // that when AVX types are involved: the ABI explicitly states it is
  2137. // undefined, and it doesn't work in practice because of how the ABI
  2138. // defines varargs anyway.
  2139. if (fnType->getCallConv() == CC_C) {
  2140. bool HasAVXType = false;
  2141. for (CallArgList::const_iterator
  2142. it = args.begin(), ie = args.end(); it != ie; ++it) {
  2143. if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
  2144. HasAVXType = true;
  2145. break;
  2146. }
  2147. }
  2148. if (!HasAVXType)
  2149. return true;
  2150. }
  2151. return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
  2152. }
  2153. llvm::Constant *
  2154. getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
  2155. unsigned Sig = (0xeb << 0) | // jmp rel8
  2156. (0x06 << 8) | // .+0x08
  2157. ('v' << 16) |
  2158. ('2' << 24);
  2159. return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
  2160. }
  2161. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  2162. CodeGen::CodeGenModule &CGM) const override {
  2163. if (GV->isDeclaration())
  2164. return;
  2165. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  2166. if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
  2167. llvm::Function *Fn = cast<llvm::Function>(GV);
  2168. Fn->addFnAttr("stackrealign");
  2169. }
  2170. addX86InterruptAttrs(FD, GV, CGM);
  2171. }
  2172. }
  2173. void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc,
  2174. const FunctionDecl *Caller,
  2175. const FunctionDecl *Callee,
  2176. const CallArgList &Args) const override;
  2177. };
  2178. static void initFeatureMaps(const ASTContext &Ctx,
  2179. llvm::StringMap<bool> &CallerMap,
  2180. const FunctionDecl *Caller,
  2181. llvm::StringMap<bool> &CalleeMap,
  2182. const FunctionDecl *Callee) {
  2183. if (CalleeMap.empty() && CallerMap.empty()) {
  2184. // The caller is potentially nullptr in the case where the call isn't in a
  2185. // function. In this case, the getFunctionFeatureMap ensures we just get
  2186. // the TU level setting (since it cannot be modified by 'target'..
  2187. Ctx.getFunctionFeatureMap(CallerMap, Caller);
  2188. Ctx.getFunctionFeatureMap(CalleeMap, Callee);
  2189. }
  2190. }
  2191. static bool checkAVXParamFeature(DiagnosticsEngine &Diag,
  2192. SourceLocation CallLoc,
  2193. const llvm::StringMap<bool> &CallerMap,
  2194. const llvm::StringMap<bool> &CalleeMap,
  2195. QualType Ty, StringRef Feature,
  2196. bool IsArgument) {
  2197. bool CallerHasFeat = CallerMap.lookup(Feature);
  2198. bool CalleeHasFeat = CalleeMap.lookup(Feature);
  2199. if (!CallerHasFeat && !CalleeHasFeat)
  2200. return Diag.Report(CallLoc, diag::warn_avx_calling_convention)
  2201. << IsArgument << Ty << Feature;
  2202. // Mixing calling conventions here is very clearly an error.
  2203. if (!CallerHasFeat || !CalleeHasFeat)
  2204. return Diag.Report(CallLoc, diag::err_avx_calling_convention)
  2205. << IsArgument << Ty << Feature;
  2206. // Else, both caller and callee have the required feature, so there is no need
  2207. // to diagnose.
  2208. return false;
  2209. }
  2210. static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx,
  2211. SourceLocation CallLoc,
  2212. const llvm::StringMap<bool> &CallerMap,
  2213. const llvm::StringMap<bool> &CalleeMap, QualType Ty,
  2214. bool IsArgument) {
  2215. uint64_t Size = Ctx.getTypeSize(Ty);
  2216. if (Size > 256)
  2217. return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty,
  2218. "avx512f", IsArgument);
  2219. if (Size > 128)
  2220. return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx",
  2221. IsArgument);
  2222. return false;
  2223. }
  2224. void X86_64TargetCodeGenInfo::checkFunctionCallABI(
  2225. CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller,
  2226. const FunctionDecl *Callee, const CallArgList &Args) const {
  2227. llvm::StringMap<bool> CallerMap;
  2228. llvm::StringMap<bool> CalleeMap;
  2229. unsigned ArgIndex = 0;
  2230. // We need to loop through the actual call arguments rather than the the
  2231. // function's parameters, in case this variadic.
  2232. for (const CallArg &Arg : Args) {
  2233. // The "avx" feature changes how vectors >128 in size are passed. "avx512f"
  2234. // additionally changes how vectors >256 in size are passed. Like GCC, we
  2235. // warn when a function is called with an argument where this will change.
  2236. // Unlike GCC, we also error when it is an obvious ABI mismatch, that is,
  2237. // the caller and callee features are mismatched.
  2238. // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can
  2239. // change its ABI with attribute-target after this call.
  2240. if (Arg.getType()->isVectorType() &&
  2241. CGM.getContext().getTypeSize(Arg.getType()) > 128) {
  2242. initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
  2243. QualType Ty = Arg.getType();
  2244. // The CallArg seems to have desugared the type already, so for clearer
  2245. // diagnostics, replace it with the type in the FunctionDecl if possible.
  2246. if (ArgIndex < Callee->getNumParams())
  2247. Ty = Callee->getParamDecl(ArgIndex)->getType();
  2248. if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
  2249. CalleeMap, Ty, /*IsArgument*/ true))
  2250. return;
  2251. }
  2252. ++ArgIndex;
  2253. }
  2254. // Check return always, as we don't have a good way of knowing in codegen
  2255. // whether this value is used, tail-called, etc.
  2256. if (Callee->getReturnType()->isVectorType() &&
  2257. CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) {
  2258. initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee);
  2259. checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap,
  2260. CalleeMap, Callee->getReturnType(),
  2261. /*IsArgument*/ false);
  2262. }
  2263. }
  2264. static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
  2265. // If the argument does not end in .lib, automatically add the suffix.
  2266. // If the argument contains a space, enclose it in quotes.
  2267. // This matches the behavior of MSVC.
  2268. bool Quote = Lib.contains(' ');
  2269. std::string ArgStr = Quote ? "\"" : "";
  2270. ArgStr += Lib;
  2271. if (!Lib.endswith_insensitive(".lib") && !Lib.endswith_insensitive(".a"))
  2272. ArgStr += ".lib";
  2273. ArgStr += Quote ? "\"" : "";
  2274. return ArgStr;
  2275. }
  2276. class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
  2277. public:
  2278. WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
  2279. bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
  2280. unsigned NumRegisterParameters)
  2281. : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
  2282. Win32StructABI, NumRegisterParameters, false) {}
  2283. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  2284. CodeGen::CodeGenModule &CGM) const override;
  2285. void getDependentLibraryOption(llvm::StringRef Lib,
  2286. llvm::SmallString<24> &Opt) const override {
  2287. Opt = "/DEFAULTLIB:";
  2288. Opt += qualifyWindowsLibrary(Lib);
  2289. }
  2290. void getDetectMismatchOption(llvm::StringRef Name,
  2291. llvm::StringRef Value,
  2292. llvm::SmallString<32> &Opt) const override {
  2293. Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
  2294. }
  2295. };
  2296. static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  2297. CodeGen::CodeGenModule &CGM) {
  2298. if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
  2299. if (CGM.getCodeGenOpts().StackProbeSize != 4096)
  2300. Fn->addFnAttr("stack-probe-size",
  2301. llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
  2302. if (CGM.getCodeGenOpts().NoStackArgProbe)
  2303. Fn->addFnAttr("no-stack-arg-probe");
  2304. }
  2305. }
  2306. void WinX86_32TargetCodeGenInfo::setTargetAttributes(
  2307. const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
  2308. X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
  2309. if (GV->isDeclaration())
  2310. return;
  2311. addStackProbeTargetAttributes(D, GV, CGM);
  2312. }
  2313. class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
  2314. public:
  2315. WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
  2316. X86AVXABILevel AVXLevel)
  2317. : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {}
  2318. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  2319. CodeGen::CodeGenModule &CGM) const override;
  2320. int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
  2321. return 7;
  2322. }
  2323. bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  2324. llvm::Value *Address) const override {
  2325. llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
  2326. // 0-15 are the 16 integer registers.
  2327. // 16 is %rip.
  2328. AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
  2329. return false;
  2330. }
  2331. void getDependentLibraryOption(llvm::StringRef Lib,
  2332. llvm::SmallString<24> &Opt) const override {
  2333. Opt = "/DEFAULTLIB:";
  2334. Opt += qualifyWindowsLibrary(Lib);
  2335. }
  2336. void getDetectMismatchOption(llvm::StringRef Name,
  2337. llvm::StringRef Value,
  2338. llvm::SmallString<32> &Opt) const override {
  2339. Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
  2340. }
  2341. };
  2342. void WinX86_64TargetCodeGenInfo::setTargetAttributes(
  2343. const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
  2344. TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
  2345. if (GV->isDeclaration())
  2346. return;
  2347. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  2348. if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
  2349. llvm::Function *Fn = cast<llvm::Function>(GV);
  2350. Fn->addFnAttr("stackrealign");
  2351. }
  2352. addX86InterruptAttrs(FD, GV, CGM);
  2353. }
  2354. addStackProbeTargetAttributes(D, GV, CGM);
  2355. }
  2356. }
  2357. void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
  2358. Class &Hi) const {
  2359. // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
  2360. //
  2361. // (a) If one of the classes is Memory, the whole argument is passed in
  2362. // memory.
  2363. //
  2364. // (b) If X87UP is not preceded by X87, the whole argument is passed in
  2365. // memory.
  2366. //
  2367. // (c) If the size of the aggregate exceeds two eightbytes and the first
  2368. // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
  2369. // argument is passed in memory. NOTE: This is necessary to keep the
  2370. // ABI working for processors that don't support the __m256 type.
  2371. //
  2372. // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
  2373. //
  2374. // Some of these are enforced by the merging logic. Others can arise
  2375. // only with unions; for example:
  2376. // union { _Complex double; unsigned; }
  2377. //
  2378. // Note that clauses (b) and (c) were added in 0.98.
  2379. //
  2380. if (Hi == Memory)
  2381. Lo = Memory;
  2382. if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
  2383. Lo = Memory;
  2384. if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
  2385. Lo = Memory;
  2386. if (Hi == SSEUp && Lo != SSE)
  2387. Hi = SSE;
  2388. }
  2389. X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
  2390. // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
  2391. // classified recursively so that always two fields are
  2392. // considered. The resulting class is calculated according to
  2393. // the classes of the fields in the eightbyte:
  2394. //
  2395. // (a) If both classes are equal, this is the resulting class.
  2396. //
  2397. // (b) If one of the classes is NO_CLASS, the resulting class is
  2398. // the other class.
  2399. //
  2400. // (c) If one of the classes is MEMORY, the result is the MEMORY
  2401. // class.
  2402. //
  2403. // (d) If one of the classes is INTEGER, the result is the
  2404. // INTEGER.
  2405. //
  2406. // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
  2407. // MEMORY is used as class.
  2408. //
  2409. // (f) Otherwise class SSE is used.
  2410. // Accum should never be memory (we should have returned) or
  2411. // ComplexX87 (because this cannot be passed in a structure).
  2412. assert((Accum != Memory && Accum != ComplexX87) &&
  2413. "Invalid accumulated classification during merge.");
  2414. if (Accum == Field || Field == NoClass)
  2415. return Accum;
  2416. if (Field == Memory)
  2417. return Memory;
  2418. if (Accum == NoClass)
  2419. return Field;
  2420. if (Accum == Integer || Field == Integer)
  2421. return Integer;
  2422. if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
  2423. Accum == X87 || Accum == X87Up)
  2424. return Memory;
  2425. return SSE;
  2426. }
  2427. void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
  2428. Class &Lo, Class &Hi, bool isNamedArg) const {
  2429. // FIXME: This code can be simplified by introducing a simple value class for
  2430. // Class pairs with appropriate constructor methods for the various
  2431. // situations.
  2432. // FIXME: Some of the split computations are wrong; unaligned vectors
  2433. // shouldn't be passed in registers for example, so there is no chance they
  2434. // can straddle an eightbyte. Verify & simplify.
  2435. Lo = Hi = NoClass;
  2436. Class &Current = OffsetBase < 64 ? Lo : Hi;
  2437. Current = Memory;
  2438. if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
  2439. BuiltinType::Kind k = BT->getKind();
  2440. if (k == BuiltinType::Void) {
  2441. Current = NoClass;
  2442. } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
  2443. Lo = Integer;
  2444. Hi = Integer;
  2445. } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
  2446. Current = Integer;
  2447. } else if (k == BuiltinType::Float || k == BuiltinType::Double ||
  2448. k == BuiltinType::Float16) {
  2449. Current = SSE;
  2450. } else if (k == BuiltinType::LongDouble) {
  2451. const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
  2452. if (LDF == &llvm::APFloat::IEEEquad()) {
  2453. Lo = SSE;
  2454. Hi = SSEUp;
  2455. } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
  2456. Lo = X87;
  2457. Hi = X87Up;
  2458. } else if (LDF == &llvm::APFloat::IEEEdouble()) {
  2459. Current = SSE;
  2460. } else
  2461. llvm_unreachable("unexpected long double representation!");
  2462. }
  2463. // FIXME: _Decimal32 and _Decimal64 are SSE.
  2464. // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
  2465. return;
  2466. }
  2467. if (const EnumType *ET = Ty->getAs<EnumType>()) {
  2468. // Classify the underlying integer type.
  2469. classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
  2470. return;
  2471. }
  2472. if (Ty->hasPointerRepresentation()) {
  2473. Current = Integer;
  2474. return;
  2475. }
  2476. if (Ty->isMemberPointerType()) {
  2477. if (Ty->isMemberFunctionPointerType()) {
  2478. if (Has64BitPointers) {
  2479. // If Has64BitPointers, this is an {i64, i64}, so classify both
  2480. // Lo and Hi now.
  2481. Lo = Hi = Integer;
  2482. } else {
  2483. // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
  2484. // straddles an eightbyte boundary, Hi should be classified as well.
  2485. uint64_t EB_FuncPtr = (OffsetBase) / 64;
  2486. uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
  2487. if (EB_FuncPtr != EB_ThisAdj) {
  2488. Lo = Hi = Integer;
  2489. } else {
  2490. Current = Integer;
  2491. }
  2492. }
  2493. } else {
  2494. Current = Integer;
  2495. }
  2496. return;
  2497. }
  2498. if (const VectorType *VT = Ty->getAs<VectorType>()) {
  2499. uint64_t Size = getContext().getTypeSize(VT);
  2500. if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
  2501. // gcc passes the following as integer:
  2502. // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
  2503. // 2 bytes - <2 x char>, <1 x short>
  2504. // 1 byte - <1 x char>
  2505. Current = Integer;
  2506. // If this type crosses an eightbyte boundary, it should be
  2507. // split.
  2508. uint64_t EB_Lo = (OffsetBase) / 64;
  2509. uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
  2510. if (EB_Lo != EB_Hi)
  2511. Hi = Lo;
  2512. } else if (Size == 64) {
  2513. QualType ElementType = VT->getElementType();
  2514. // gcc passes <1 x double> in memory. :(
  2515. if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
  2516. return;
  2517. // gcc passes <1 x long long> as SSE but clang used to unconditionally
  2518. // pass them as integer. For platforms where clang is the de facto
  2519. // platform compiler, we must continue to use integer.
  2520. if (!classifyIntegerMMXAsSSE() &&
  2521. (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
  2522. ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
  2523. ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
  2524. ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
  2525. Current = Integer;
  2526. else
  2527. Current = SSE;
  2528. // If this type crosses an eightbyte boundary, it should be
  2529. // split.
  2530. if (OffsetBase && OffsetBase != 64)
  2531. Hi = Lo;
  2532. } else if (Size == 128 ||
  2533. (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
  2534. QualType ElementType = VT->getElementType();
  2535. // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
  2536. if (passInt128VectorsInMem() && Size != 128 &&
  2537. (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
  2538. ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
  2539. return;
  2540. // Arguments of 256-bits are split into four eightbyte chunks. The
  2541. // least significant one belongs to class SSE and all the others to class
  2542. // SSEUP. The original Lo and Hi design considers that types can't be
  2543. // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
  2544. // This design isn't correct for 256-bits, but since there're no cases
  2545. // where the upper parts would need to be inspected, avoid adding
  2546. // complexity and just consider Hi to match the 64-256 part.
  2547. //
  2548. // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
  2549. // registers if they are "named", i.e. not part of the "..." of a
  2550. // variadic function.
  2551. //
  2552. // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
  2553. // split into eight eightbyte chunks, one SSE and seven SSEUP.
  2554. Lo = SSE;
  2555. Hi = SSEUp;
  2556. }
  2557. return;
  2558. }
  2559. if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
  2560. QualType ET = getContext().getCanonicalType(CT->getElementType());
  2561. uint64_t Size = getContext().getTypeSize(Ty);
  2562. if (ET->isIntegralOrEnumerationType()) {
  2563. if (Size <= 64)
  2564. Current = Integer;
  2565. else if (Size <= 128)
  2566. Lo = Hi = Integer;
  2567. } else if (ET->isFloat16Type() || ET == getContext().FloatTy) {
  2568. Current = SSE;
  2569. } else if (ET == getContext().DoubleTy) {
  2570. Lo = Hi = SSE;
  2571. } else if (ET == getContext().LongDoubleTy) {
  2572. const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
  2573. if (LDF == &llvm::APFloat::IEEEquad())
  2574. Current = Memory;
  2575. else if (LDF == &llvm::APFloat::x87DoubleExtended())
  2576. Current = ComplexX87;
  2577. else if (LDF == &llvm::APFloat::IEEEdouble())
  2578. Lo = Hi = SSE;
  2579. else
  2580. llvm_unreachable("unexpected long double representation!");
  2581. }
  2582. // If this complex type crosses an eightbyte boundary then it
  2583. // should be split.
  2584. uint64_t EB_Real = (OffsetBase) / 64;
  2585. uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
  2586. if (Hi == NoClass && EB_Real != EB_Imag)
  2587. Hi = Lo;
  2588. return;
  2589. }
  2590. if (const auto *EITy = Ty->getAs<BitIntType>()) {
  2591. if (EITy->getNumBits() <= 64)
  2592. Current = Integer;
  2593. else if (EITy->getNumBits() <= 128)
  2594. Lo = Hi = Integer;
  2595. // Larger values need to get passed in memory.
  2596. return;
  2597. }
  2598. if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
  2599. // Arrays are treated like structures.
  2600. uint64_t Size = getContext().getTypeSize(Ty);
  2601. // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
  2602. // than eight eightbytes, ..., it has class MEMORY.
  2603. if (Size > 512)
  2604. return;
  2605. // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
  2606. // fields, it has class MEMORY.
  2607. //
  2608. // Only need to check alignment of array base.
  2609. if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
  2610. return;
  2611. // Otherwise implement simplified merge. We could be smarter about
  2612. // this, but it isn't worth it and would be harder to verify.
  2613. Current = NoClass;
  2614. uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
  2615. uint64_t ArraySize = AT->getSize().getZExtValue();
  2616. // The only case a 256-bit wide vector could be used is when the array
  2617. // contains a single 256-bit element. Since Lo and Hi logic isn't extended
  2618. // to work for sizes wider than 128, early check and fallback to memory.
  2619. //
  2620. if (Size > 128 &&
  2621. (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
  2622. return;
  2623. for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
  2624. Class FieldLo, FieldHi;
  2625. classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
  2626. Lo = merge(Lo, FieldLo);
  2627. Hi = merge(Hi, FieldHi);
  2628. if (Lo == Memory || Hi == Memory)
  2629. break;
  2630. }
  2631. postMerge(Size, Lo, Hi);
  2632. assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
  2633. return;
  2634. }
  2635. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  2636. uint64_t Size = getContext().getTypeSize(Ty);
  2637. // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
  2638. // than eight eightbytes, ..., it has class MEMORY.
  2639. if (Size > 512)
  2640. return;
  2641. // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
  2642. // copy constructor or a non-trivial destructor, it is passed by invisible
  2643. // reference.
  2644. if (getRecordArgABI(RT, getCXXABI()))
  2645. return;
  2646. const RecordDecl *RD = RT->getDecl();
  2647. // Assume variable sized types are passed in memory.
  2648. if (RD->hasFlexibleArrayMember())
  2649. return;
  2650. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  2651. // Reset Lo class, this will be recomputed.
  2652. Current = NoClass;
  2653. // If this is a C++ record, classify the bases first.
  2654. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  2655. for (const auto &I : CXXRD->bases()) {
  2656. assert(!I.isVirtual() && !I.getType()->isDependentType() &&
  2657. "Unexpected base class!");
  2658. const auto *Base =
  2659. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  2660. // Classify this field.
  2661. //
  2662. // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
  2663. // single eightbyte, each is classified separately. Each eightbyte gets
  2664. // initialized to class NO_CLASS.
  2665. Class FieldLo, FieldHi;
  2666. uint64_t Offset =
  2667. OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
  2668. classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
  2669. Lo = merge(Lo, FieldLo);
  2670. Hi = merge(Hi, FieldHi);
  2671. if (Lo == Memory || Hi == Memory) {
  2672. postMerge(Size, Lo, Hi);
  2673. return;
  2674. }
  2675. }
  2676. }
  2677. // Classify the fields one at a time, merging the results.
  2678. unsigned idx = 0;
  2679. bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <=
  2680. LangOptions::ClangABI::Ver11 ||
  2681. getContext().getTargetInfo().getTriple().isPS4();
  2682. bool IsUnion = RT->isUnionType() && !UseClang11Compat;
  2683. for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
  2684. i != e; ++i, ++idx) {
  2685. uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
  2686. bool BitField = i->isBitField();
  2687. // Ignore padding bit-fields.
  2688. if (BitField && i->isUnnamedBitfield())
  2689. continue;
  2690. // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
  2691. // eight eightbytes, or it contains unaligned fields, it has class MEMORY.
  2692. //
  2693. // The only case a 256-bit or a 512-bit wide vector could be used is when
  2694. // the struct contains a single 256-bit or 512-bit element. Early check
  2695. // and fallback to memory.
  2696. //
  2697. // FIXME: Extended the Lo and Hi logic properly to work for size wider
  2698. // than 128.
  2699. if (Size > 128 &&
  2700. ((!IsUnion && Size != getContext().getTypeSize(i->getType())) ||
  2701. Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
  2702. Lo = Memory;
  2703. postMerge(Size, Lo, Hi);
  2704. return;
  2705. }
  2706. // Note, skip this test for bit-fields, see below.
  2707. if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
  2708. Lo = Memory;
  2709. postMerge(Size, Lo, Hi);
  2710. return;
  2711. }
  2712. // Classify this field.
  2713. //
  2714. // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
  2715. // exceeds a single eightbyte, each is classified
  2716. // separately. Each eightbyte gets initialized to class
  2717. // NO_CLASS.
  2718. Class FieldLo, FieldHi;
  2719. // Bit-fields require special handling, they do not force the
  2720. // structure to be passed in memory even if unaligned, and
  2721. // therefore they can straddle an eightbyte.
  2722. if (BitField) {
  2723. assert(!i->isUnnamedBitfield());
  2724. uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
  2725. uint64_t Size = i->getBitWidthValue(getContext());
  2726. uint64_t EB_Lo = Offset / 64;
  2727. uint64_t EB_Hi = (Offset + Size - 1) / 64;
  2728. if (EB_Lo) {
  2729. assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
  2730. FieldLo = NoClass;
  2731. FieldHi = Integer;
  2732. } else {
  2733. FieldLo = Integer;
  2734. FieldHi = EB_Hi ? Integer : NoClass;
  2735. }
  2736. } else
  2737. classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
  2738. Lo = merge(Lo, FieldLo);
  2739. Hi = merge(Hi, FieldHi);
  2740. if (Lo == Memory || Hi == Memory)
  2741. break;
  2742. }
  2743. postMerge(Size, Lo, Hi);
  2744. }
  2745. }
  2746. ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
  2747. // If this is a scalar LLVM value then assume LLVM will pass it in the right
  2748. // place naturally.
  2749. if (!isAggregateTypeForABI(Ty)) {
  2750. // Treat an enum type as its underlying type.
  2751. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  2752. Ty = EnumTy->getDecl()->getIntegerType();
  2753. if (Ty->isBitIntType())
  2754. return getNaturalAlignIndirect(Ty);
  2755. return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
  2756. : ABIArgInfo::getDirect());
  2757. }
  2758. return getNaturalAlignIndirect(Ty);
  2759. }
  2760. bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
  2761. if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
  2762. uint64_t Size = getContext().getTypeSize(VecTy);
  2763. unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
  2764. if (Size <= 64 || Size > LargestVector)
  2765. return true;
  2766. QualType EltTy = VecTy->getElementType();
  2767. if (passInt128VectorsInMem() &&
  2768. (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
  2769. EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
  2770. return true;
  2771. }
  2772. return false;
  2773. }
  2774. ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
  2775. unsigned freeIntRegs) const {
  2776. // If this is a scalar LLVM value then assume LLVM will pass it in the right
  2777. // place naturally.
  2778. //
  2779. // This assumption is optimistic, as there could be free registers available
  2780. // when we need to pass this argument in memory, and LLVM could try to pass
  2781. // the argument in the free register. This does not seem to happen currently,
  2782. // but this code would be much safer if we could mark the argument with
  2783. // 'onstack'. See PR12193.
  2784. if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) &&
  2785. !Ty->isBitIntType()) {
  2786. // Treat an enum type as its underlying type.
  2787. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  2788. Ty = EnumTy->getDecl()->getIntegerType();
  2789. return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
  2790. : ABIArgInfo::getDirect());
  2791. }
  2792. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
  2793. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  2794. // Compute the byval alignment. We specify the alignment of the byval in all
  2795. // cases so that the mid-level optimizer knows the alignment of the byval.
  2796. unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
  2797. // Attempt to avoid passing indirect results using byval when possible. This
  2798. // is important for good codegen.
  2799. //
  2800. // We do this by coercing the value into a scalar type which the backend can
  2801. // handle naturally (i.e., without using byval).
  2802. //
  2803. // For simplicity, we currently only do this when we have exhausted all of the
  2804. // free integer registers. Doing this when there are free integer registers
  2805. // would require more care, as we would have to ensure that the coerced value
  2806. // did not claim the unused register. That would require either reording the
  2807. // arguments to the function (so that any subsequent inreg values came first),
  2808. // or only doing this optimization when there were no following arguments that
  2809. // might be inreg.
  2810. //
  2811. // We currently expect it to be rare (particularly in well written code) for
  2812. // arguments to be passed on the stack when there are still free integer
  2813. // registers available (this would typically imply large structs being passed
  2814. // by value), so this seems like a fair tradeoff for now.
  2815. //
  2816. // We can revisit this if the backend grows support for 'onstack' parameter
  2817. // attributes. See PR12193.
  2818. if (freeIntRegs == 0) {
  2819. uint64_t Size = getContext().getTypeSize(Ty);
  2820. // If this type fits in an eightbyte, coerce it into the matching integral
  2821. // type, which will end up on the stack (with alignment 8).
  2822. if (Align == 8 && Size <= 64)
  2823. return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
  2824. Size));
  2825. }
  2826. return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
  2827. }
  2828. /// The ABI specifies that a value should be passed in a full vector XMM/YMM
  2829. /// register. Pick an LLVM IR type that will be passed as a vector register.
  2830. llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
  2831. // Wrapper structs/arrays that only contain vectors are passed just like
  2832. // vectors; strip them off if present.
  2833. if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
  2834. Ty = QualType(InnerTy, 0);
  2835. llvm::Type *IRType = CGT.ConvertType(Ty);
  2836. if (isa<llvm::VectorType>(IRType)) {
  2837. // Don't pass vXi128 vectors in their native type, the backend can't
  2838. // legalize them.
  2839. if (passInt128VectorsInMem() &&
  2840. cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
  2841. // Use a vXi64 vector.
  2842. uint64_t Size = getContext().getTypeSize(Ty);
  2843. return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
  2844. Size / 64);
  2845. }
  2846. return IRType;
  2847. }
  2848. if (IRType->getTypeID() == llvm::Type::FP128TyID)
  2849. return IRType;
  2850. // We couldn't find the preferred IR vector type for 'Ty'.
  2851. uint64_t Size = getContext().getTypeSize(Ty);
  2852. assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
  2853. // Return a LLVM IR vector type based on the size of 'Ty'.
  2854. return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()),
  2855. Size / 64);
  2856. }
  2857. /// BitsContainNoUserData - Return true if the specified [start,end) bit range
  2858. /// is known to either be off the end of the specified type or being in
  2859. /// alignment padding. The user type specified is known to be at most 128 bits
  2860. /// in size, and have passed through X86_64ABIInfo::classify with a successful
  2861. /// classification that put one of the two halves in the INTEGER class.
  2862. ///
  2863. /// It is conservatively correct to return false.
  2864. static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
  2865. unsigned EndBit, ASTContext &Context) {
  2866. // If the bytes being queried are off the end of the type, there is no user
  2867. // data hiding here. This handles analysis of builtins, vectors and other
  2868. // types that don't contain interesting padding.
  2869. unsigned TySize = (unsigned)Context.getTypeSize(Ty);
  2870. if (TySize <= StartBit)
  2871. return true;
  2872. if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
  2873. unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
  2874. unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
  2875. // Check each element to see if the element overlaps with the queried range.
  2876. for (unsigned i = 0; i != NumElts; ++i) {
  2877. // If the element is after the span we care about, then we're done..
  2878. unsigned EltOffset = i*EltSize;
  2879. if (EltOffset >= EndBit) break;
  2880. unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
  2881. if (!BitsContainNoUserData(AT->getElementType(), EltStart,
  2882. EndBit-EltOffset, Context))
  2883. return false;
  2884. }
  2885. // If it overlaps no elements, then it is safe to process as padding.
  2886. return true;
  2887. }
  2888. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  2889. const RecordDecl *RD = RT->getDecl();
  2890. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  2891. // If this is a C++ record, check the bases first.
  2892. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  2893. for (const auto &I : CXXRD->bases()) {
  2894. assert(!I.isVirtual() && !I.getType()->isDependentType() &&
  2895. "Unexpected base class!");
  2896. const auto *Base =
  2897. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  2898. // If the base is after the span we care about, ignore it.
  2899. unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
  2900. if (BaseOffset >= EndBit) continue;
  2901. unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
  2902. if (!BitsContainNoUserData(I.getType(), BaseStart,
  2903. EndBit-BaseOffset, Context))
  2904. return false;
  2905. }
  2906. }
  2907. // Verify that no field has data that overlaps the region of interest. Yes
  2908. // this could be sped up a lot by being smarter about queried fields,
  2909. // however we're only looking at structs up to 16 bytes, so we don't care
  2910. // much.
  2911. unsigned idx = 0;
  2912. for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
  2913. i != e; ++i, ++idx) {
  2914. unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
  2915. // If we found a field after the region we care about, then we're done.
  2916. if (FieldOffset >= EndBit) break;
  2917. unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
  2918. if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
  2919. Context))
  2920. return false;
  2921. }
  2922. // If nothing in this record overlapped the area of interest, then we're
  2923. // clean.
  2924. return true;
  2925. }
  2926. return false;
  2927. }
  2928. /// getFPTypeAtOffset - Return a floating point type at the specified offset.
  2929. static llvm::Type *getFPTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
  2930. const llvm::DataLayout &TD) {
  2931. if (IROffset == 0 && IRType->isFloatingPointTy())
  2932. return IRType;
  2933. // If this is a struct, recurse into the field at the specified offset.
  2934. if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
  2935. if (!STy->getNumContainedTypes())
  2936. return nullptr;
  2937. const llvm::StructLayout *SL = TD.getStructLayout(STy);
  2938. unsigned Elt = SL->getElementContainingOffset(IROffset);
  2939. IROffset -= SL->getElementOffset(Elt);
  2940. return getFPTypeAtOffset(STy->getElementType(Elt), IROffset, TD);
  2941. }
  2942. // If this is an array, recurse into the field at the specified offset.
  2943. if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
  2944. llvm::Type *EltTy = ATy->getElementType();
  2945. unsigned EltSize = TD.getTypeAllocSize(EltTy);
  2946. IROffset -= IROffset / EltSize * EltSize;
  2947. return getFPTypeAtOffset(EltTy, IROffset, TD);
  2948. }
  2949. return nullptr;
  2950. }
  2951. /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
  2952. /// low 8 bytes of an XMM register, corresponding to the SSE class.
  2953. llvm::Type *X86_64ABIInfo::
  2954. GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
  2955. QualType SourceTy, unsigned SourceOffset) const {
  2956. const llvm::DataLayout &TD = getDataLayout();
  2957. unsigned SourceSize =
  2958. (unsigned)getContext().getTypeSize(SourceTy) / 8 - SourceOffset;
  2959. llvm::Type *T0 = getFPTypeAtOffset(IRType, IROffset, TD);
  2960. if (!T0 || T0->isDoubleTy())
  2961. return llvm::Type::getDoubleTy(getVMContext());
  2962. // Get the adjacent FP type.
  2963. llvm::Type *T1 = nullptr;
  2964. unsigned T0Size = TD.getTypeAllocSize(T0);
  2965. if (SourceSize > T0Size)
  2966. T1 = getFPTypeAtOffset(IRType, IROffset + T0Size, TD);
  2967. if (T1 == nullptr) {
  2968. // Check if IRType is a half + float. float type will be in IROffset+4 due
  2969. // to its alignment.
  2970. if (T0->isHalfTy() && SourceSize > 4)
  2971. T1 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
  2972. // If we can't get a second FP type, return a simple half or float.
  2973. // avx512fp16-abi.c:pr51813_2 shows it works to return float for
  2974. // {float, i8} too.
  2975. if (T1 == nullptr)
  2976. return T0;
  2977. }
  2978. if (T0->isFloatTy() && T1->isFloatTy())
  2979. return llvm::FixedVectorType::get(T0, 2);
  2980. if (T0->isHalfTy() && T1->isHalfTy()) {
  2981. llvm::Type *T2 = nullptr;
  2982. if (SourceSize > 4)
  2983. T2 = getFPTypeAtOffset(IRType, IROffset + 4, TD);
  2984. if (T2 == nullptr)
  2985. return llvm::FixedVectorType::get(T0, 2);
  2986. return llvm::FixedVectorType::get(T0, 4);
  2987. }
  2988. if (T0->isHalfTy() || T1->isHalfTy())
  2989. return llvm::FixedVectorType::get(llvm::Type::getHalfTy(getVMContext()), 4);
  2990. return llvm::Type::getDoubleTy(getVMContext());
  2991. }
  2992. /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
  2993. /// an 8-byte GPR. This means that we either have a scalar or we are talking
  2994. /// about the high or low part of an up-to-16-byte struct. This routine picks
  2995. /// the best LLVM IR type to represent this, which may be i64 or may be anything
  2996. /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
  2997. /// etc).
  2998. ///
  2999. /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
  3000. /// the source type. IROffset is an offset in bytes into the LLVM IR type that
  3001. /// the 8-byte value references. PrefType may be null.
  3002. ///
  3003. /// SourceTy is the source-level type for the entire argument. SourceOffset is
  3004. /// an offset into this that we're processing (which is always either 0 or 8).
  3005. ///
  3006. llvm::Type *X86_64ABIInfo::
  3007. GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
  3008. QualType SourceTy, unsigned SourceOffset) const {
  3009. // If we're dealing with an un-offset LLVM IR type, then it means that we're
  3010. // returning an 8-byte unit starting with it. See if we can safely use it.
  3011. if (IROffset == 0) {
  3012. // Pointers and int64's always fill the 8-byte unit.
  3013. if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
  3014. IRType->isIntegerTy(64))
  3015. return IRType;
  3016. // If we have a 1/2/4-byte integer, we can use it only if the rest of the
  3017. // goodness in the source type is just tail padding. This is allowed to
  3018. // kick in for struct {double,int} on the int, but not on
  3019. // struct{double,int,int} because we wouldn't return the second int. We
  3020. // have to do this analysis on the source type because we can't depend on
  3021. // unions being lowered a specific way etc.
  3022. if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
  3023. IRType->isIntegerTy(32) ||
  3024. (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
  3025. unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
  3026. cast<llvm::IntegerType>(IRType)->getBitWidth();
  3027. if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
  3028. SourceOffset*8+64, getContext()))
  3029. return IRType;
  3030. }
  3031. }
  3032. if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
  3033. // If this is a struct, recurse into the field at the specified offset.
  3034. const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
  3035. if (IROffset < SL->getSizeInBytes()) {
  3036. unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
  3037. IROffset -= SL->getElementOffset(FieldIdx);
  3038. return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
  3039. SourceTy, SourceOffset);
  3040. }
  3041. }
  3042. if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
  3043. llvm::Type *EltTy = ATy->getElementType();
  3044. unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
  3045. unsigned EltOffset = IROffset/EltSize*EltSize;
  3046. return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
  3047. SourceOffset);
  3048. }
  3049. // Okay, we don't have any better idea of what to pass, so we pass this in an
  3050. // integer register that isn't too big to fit the rest of the struct.
  3051. unsigned TySizeInBytes =
  3052. (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
  3053. assert(TySizeInBytes != SourceOffset && "Empty field?");
  3054. // It is always safe to classify this as an integer type up to i64 that
  3055. // isn't larger than the structure.
  3056. return llvm::IntegerType::get(getVMContext(),
  3057. std::min(TySizeInBytes-SourceOffset, 8U)*8);
  3058. }
  3059. /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
  3060. /// be used as elements of a two register pair to pass or return, return a
  3061. /// first class aggregate to represent them. For example, if the low part of
  3062. /// a by-value argument should be passed as i32* and the high part as float,
  3063. /// return {i32*, float}.
  3064. static llvm::Type *
  3065. GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
  3066. const llvm::DataLayout &TD) {
  3067. // In order to correctly satisfy the ABI, we need to the high part to start
  3068. // at offset 8. If the high and low parts we inferred are both 4-byte types
  3069. // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
  3070. // the second element at offset 8. Check for this:
  3071. unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
  3072. unsigned HiAlign = TD.getABITypeAlignment(Hi);
  3073. unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
  3074. assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
  3075. // To handle this, we have to increase the size of the low part so that the
  3076. // second element will start at an 8 byte offset. We can't increase the size
  3077. // of the second element because it might make us access off the end of the
  3078. // struct.
  3079. if (HiStart != 8) {
  3080. // There are usually two sorts of types the ABI generation code can produce
  3081. // for the low part of a pair that aren't 8 bytes in size: half, float or
  3082. // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
  3083. // NaCl).
  3084. // Promote these to a larger type.
  3085. if (Lo->isHalfTy() || Lo->isFloatTy())
  3086. Lo = llvm::Type::getDoubleTy(Lo->getContext());
  3087. else {
  3088. assert((Lo->isIntegerTy() || Lo->isPointerTy())
  3089. && "Invalid/unknown lo type");
  3090. Lo = llvm::Type::getInt64Ty(Lo->getContext());
  3091. }
  3092. }
  3093. llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
  3094. // Verify that the second element is at an 8-byte offset.
  3095. assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
  3096. "Invalid x86-64 argument pair!");
  3097. return Result;
  3098. }
  3099. ABIArgInfo X86_64ABIInfo::
  3100. classifyReturnType(QualType RetTy) const {
  3101. // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
  3102. // classification algorithm.
  3103. X86_64ABIInfo::Class Lo, Hi;
  3104. classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
  3105. // Check some invariants.
  3106. assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
  3107. assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
  3108. llvm::Type *ResType = nullptr;
  3109. switch (Lo) {
  3110. case NoClass:
  3111. if (Hi == NoClass)
  3112. return ABIArgInfo::getIgnore();
  3113. // If the low part is just padding, it takes no register, leave ResType
  3114. // null.
  3115. assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
  3116. "Unknown missing lo part");
  3117. break;
  3118. case SSEUp:
  3119. case X87Up:
  3120. llvm_unreachable("Invalid classification for lo word.");
  3121. // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
  3122. // hidden argument.
  3123. case Memory:
  3124. return getIndirectReturnResult(RetTy);
  3125. // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
  3126. // available register of the sequence %rax, %rdx is used.
  3127. case Integer:
  3128. ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
  3129. // If we have a sign or zero extended integer, make sure to return Extend
  3130. // so that the parameter gets the right LLVM IR attributes.
  3131. if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
  3132. // Treat an enum type as its underlying type.
  3133. if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
  3134. RetTy = EnumTy->getDecl()->getIntegerType();
  3135. if (RetTy->isIntegralOrEnumerationType() &&
  3136. isPromotableIntegerTypeForABI(RetTy))
  3137. return ABIArgInfo::getExtend(RetTy);
  3138. }
  3139. break;
  3140. // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
  3141. // available SSE register of the sequence %xmm0, %xmm1 is used.
  3142. case SSE:
  3143. ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
  3144. break;
  3145. // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
  3146. // returned on the X87 stack in %st0 as 80-bit x87 number.
  3147. case X87:
  3148. ResType = llvm::Type::getX86_FP80Ty(getVMContext());
  3149. break;
  3150. // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
  3151. // part of the value is returned in %st0 and the imaginary part in
  3152. // %st1.
  3153. case ComplexX87:
  3154. assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
  3155. ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
  3156. llvm::Type::getX86_FP80Ty(getVMContext()));
  3157. break;
  3158. }
  3159. llvm::Type *HighPart = nullptr;
  3160. switch (Hi) {
  3161. // Memory was handled previously and X87 should
  3162. // never occur as a hi class.
  3163. case Memory:
  3164. case X87:
  3165. llvm_unreachable("Invalid classification for hi word.");
  3166. case ComplexX87: // Previously handled.
  3167. case NoClass:
  3168. break;
  3169. case Integer:
  3170. HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
  3171. if (Lo == NoClass) // Return HighPart at offset 8 in memory.
  3172. return ABIArgInfo::getDirect(HighPart, 8);
  3173. break;
  3174. case SSE:
  3175. HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
  3176. if (Lo == NoClass) // Return HighPart at offset 8 in memory.
  3177. return ABIArgInfo::getDirect(HighPart, 8);
  3178. break;
  3179. // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
  3180. // is passed in the next available eightbyte chunk if the last used
  3181. // vector register.
  3182. //
  3183. // SSEUP should always be preceded by SSE, just widen.
  3184. case SSEUp:
  3185. assert(Lo == SSE && "Unexpected SSEUp classification.");
  3186. ResType = GetByteVectorType(RetTy);
  3187. break;
  3188. // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
  3189. // returned together with the previous X87 value in %st0.
  3190. case X87Up:
  3191. // If X87Up is preceded by X87, we don't need to do
  3192. // anything. However, in some cases with unions it may not be
  3193. // preceded by X87. In such situations we follow gcc and pass the
  3194. // extra bits in an SSE reg.
  3195. if (Lo != X87) {
  3196. HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
  3197. if (Lo == NoClass) // Return HighPart at offset 8 in memory.
  3198. return ABIArgInfo::getDirect(HighPart, 8);
  3199. }
  3200. break;
  3201. }
  3202. // If a high part was specified, merge it together with the low part. It is
  3203. // known to pass in the high eightbyte of the result. We do this by forming a
  3204. // first class struct aggregate with the high and low part: {low, high}
  3205. if (HighPart)
  3206. ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
  3207. return ABIArgInfo::getDirect(ResType);
  3208. }
  3209. ABIArgInfo X86_64ABIInfo::classifyArgumentType(
  3210. QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
  3211. bool isNamedArg)
  3212. const
  3213. {
  3214. Ty = useFirstFieldIfTransparentUnion(Ty);
  3215. X86_64ABIInfo::Class Lo, Hi;
  3216. classify(Ty, 0, Lo, Hi, isNamedArg);
  3217. // Check some invariants.
  3218. // FIXME: Enforce these by construction.
  3219. assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
  3220. assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
  3221. neededInt = 0;
  3222. neededSSE = 0;
  3223. llvm::Type *ResType = nullptr;
  3224. switch (Lo) {
  3225. case NoClass:
  3226. if (Hi == NoClass)
  3227. return ABIArgInfo::getIgnore();
  3228. // If the low part is just padding, it takes no register, leave ResType
  3229. // null.
  3230. assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
  3231. "Unknown missing lo part");
  3232. break;
  3233. // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
  3234. // on the stack.
  3235. case Memory:
  3236. // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
  3237. // COMPLEX_X87, it is passed in memory.
  3238. case X87:
  3239. case ComplexX87:
  3240. if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
  3241. ++neededInt;
  3242. return getIndirectResult(Ty, freeIntRegs);
  3243. case SSEUp:
  3244. case X87Up:
  3245. llvm_unreachable("Invalid classification for lo word.");
  3246. // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
  3247. // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
  3248. // and %r9 is used.
  3249. case Integer:
  3250. ++neededInt;
  3251. // Pick an 8-byte type based on the preferred type.
  3252. ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
  3253. // If we have a sign or zero extended integer, make sure to return Extend
  3254. // so that the parameter gets the right LLVM IR attributes.
  3255. if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
  3256. // Treat an enum type as its underlying type.
  3257. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  3258. Ty = EnumTy->getDecl()->getIntegerType();
  3259. if (Ty->isIntegralOrEnumerationType() &&
  3260. isPromotableIntegerTypeForABI(Ty))
  3261. return ABIArgInfo::getExtend(Ty);
  3262. }
  3263. break;
  3264. // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
  3265. // available SSE register is used, the registers are taken in the
  3266. // order from %xmm0 to %xmm7.
  3267. case SSE: {
  3268. llvm::Type *IRType = CGT.ConvertType(Ty);
  3269. ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
  3270. ++neededSSE;
  3271. break;
  3272. }
  3273. }
  3274. llvm::Type *HighPart = nullptr;
  3275. switch (Hi) {
  3276. // Memory was handled previously, ComplexX87 and X87 should
  3277. // never occur as hi classes, and X87Up must be preceded by X87,
  3278. // which is passed in memory.
  3279. case Memory:
  3280. case X87:
  3281. case ComplexX87:
  3282. llvm_unreachable("Invalid classification for hi word.");
  3283. case NoClass: break;
  3284. case Integer:
  3285. ++neededInt;
  3286. // Pick an 8-byte type based on the preferred type.
  3287. HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
  3288. if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
  3289. return ABIArgInfo::getDirect(HighPart, 8);
  3290. break;
  3291. // X87Up generally doesn't occur here (long double is passed in
  3292. // memory), except in situations involving unions.
  3293. case X87Up:
  3294. case SSE:
  3295. HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
  3296. if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
  3297. return ABIArgInfo::getDirect(HighPart, 8);
  3298. ++neededSSE;
  3299. break;
  3300. // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
  3301. // eightbyte is passed in the upper half of the last used SSE
  3302. // register. This only happens when 128-bit vectors are passed.
  3303. case SSEUp:
  3304. assert(Lo == SSE && "Unexpected SSEUp classification");
  3305. ResType = GetByteVectorType(Ty);
  3306. break;
  3307. }
  3308. // If a high part was specified, merge it together with the low part. It is
  3309. // known to pass in the high eightbyte of the result. We do this by forming a
  3310. // first class struct aggregate with the high and low part: {low, high}
  3311. if (HighPart)
  3312. ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
  3313. return ABIArgInfo::getDirect(ResType);
  3314. }
  3315. ABIArgInfo
  3316. X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
  3317. unsigned &NeededSSE) const {
  3318. auto RT = Ty->getAs<RecordType>();
  3319. assert(RT && "classifyRegCallStructType only valid with struct types");
  3320. if (RT->getDecl()->hasFlexibleArrayMember())
  3321. return getIndirectReturnResult(Ty);
  3322. // Sum up bases
  3323. if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
  3324. if (CXXRD->isDynamicClass()) {
  3325. NeededInt = NeededSSE = 0;
  3326. return getIndirectReturnResult(Ty);
  3327. }
  3328. for (const auto &I : CXXRD->bases())
  3329. if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
  3330. .isIndirect()) {
  3331. NeededInt = NeededSSE = 0;
  3332. return getIndirectReturnResult(Ty);
  3333. }
  3334. }
  3335. // Sum up members
  3336. for (const auto *FD : RT->getDecl()->fields()) {
  3337. if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
  3338. if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
  3339. .isIndirect()) {
  3340. NeededInt = NeededSSE = 0;
  3341. return getIndirectReturnResult(Ty);
  3342. }
  3343. } else {
  3344. unsigned LocalNeededInt, LocalNeededSSE;
  3345. if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
  3346. LocalNeededSSE, true)
  3347. .isIndirect()) {
  3348. NeededInt = NeededSSE = 0;
  3349. return getIndirectReturnResult(Ty);
  3350. }
  3351. NeededInt += LocalNeededInt;
  3352. NeededSSE += LocalNeededSSE;
  3353. }
  3354. }
  3355. return ABIArgInfo::getDirect();
  3356. }
  3357. ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
  3358. unsigned &NeededInt,
  3359. unsigned &NeededSSE) const {
  3360. NeededInt = 0;
  3361. NeededSSE = 0;
  3362. return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
  3363. }
  3364. void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
  3365. const unsigned CallingConv = FI.getCallingConvention();
  3366. // It is possible to force Win64 calling convention on any x86_64 target by
  3367. // using __attribute__((ms_abi)). In such case to correctly emit Win64
  3368. // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
  3369. if (CallingConv == llvm::CallingConv::Win64) {
  3370. WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
  3371. Win64ABIInfo.computeInfo(FI);
  3372. return;
  3373. }
  3374. bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
  3375. // Keep track of the number of assigned registers.
  3376. unsigned FreeIntRegs = IsRegCall ? 11 : 6;
  3377. unsigned FreeSSERegs = IsRegCall ? 16 : 8;
  3378. unsigned NeededInt, NeededSSE;
  3379. if (!::classifyReturnType(getCXXABI(), FI, *this)) {
  3380. if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
  3381. !FI.getReturnType()->getTypePtr()->isUnionType()) {
  3382. FI.getReturnInfo() =
  3383. classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
  3384. if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
  3385. FreeIntRegs -= NeededInt;
  3386. FreeSSERegs -= NeededSSE;
  3387. } else {
  3388. FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
  3389. }
  3390. } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() &&
  3391. getContext().getCanonicalType(FI.getReturnType()
  3392. ->getAs<ComplexType>()
  3393. ->getElementType()) ==
  3394. getContext().LongDoubleTy)
  3395. // Complex Long Double Type is passed in Memory when Regcall
  3396. // calling convention is used.
  3397. FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
  3398. else
  3399. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  3400. }
  3401. // If the return value is indirect, then the hidden argument is consuming one
  3402. // integer register.
  3403. if (FI.getReturnInfo().isIndirect())
  3404. --FreeIntRegs;
  3405. // The chain argument effectively gives us another free register.
  3406. if (FI.isChainCall())
  3407. ++FreeIntRegs;
  3408. unsigned NumRequiredArgs = FI.getNumRequiredArgs();
  3409. // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
  3410. // get assigned (in left-to-right order) for passing as follows...
  3411. unsigned ArgNo = 0;
  3412. for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
  3413. it != ie; ++it, ++ArgNo) {
  3414. bool IsNamedArg = ArgNo < NumRequiredArgs;
  3415. if (IsRegCall && it->type->isStructureOrClassType())
  3416. it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
  3417. else
  3418. it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
  3419. NeededSSE, IsNamedArg);
  3420. // AMD64-ABI 3.2.3p3: If there are no registers available for any
  3421. // eightbyte of an argument, the whole argument is passed on the
  3422. // stack. If registers have already been assigned for some
  3423. // eightbytes of such an argument, the assignments get reverted.
  3424. if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
  3425. FreeIntRegs -= NeededInt;
  3426. FreeSSERegs -= NeededSSE;
  3427. } else {
  3428. it->info = getIndirectResult(it->type, FreeIntRegs);
  3429. }
  3430. }
  3431. }
  3432. static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
  3433. Address VAListAddr, QualType Ty) {
  3434. Address overflow_arg_area_p =
  3435. CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
  3436. llvm::Value *overflow_arg_area =
  3437. CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
  3438. // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
  3439. // byte boundary if alignment needed by type exceeds 8 byte boundary.
  3440. // It isn't stated explicitly in the standard, but in practice we use
  3441. // alignment greater than 16 where necessary.
  3442. CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
  3443. if (Align > CharUnits::fromQuantity(8)) {
  3444. overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
  3445. Align);
  3446. }
  3447. // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
  3448. llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
  3449. llvm::Value *Res =
  3450. CGF.Builder.CreateBitCast(overflow_arg_area,
  3451. llvm::PointerType::getUnqual(LTy));
  3452. // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
  3453. // l->overflow_arg_area + sizeof(type).
  3454. // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
  3455. // an 8 byte boundary.
  3456. uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
  3457. llvm::Value *Offset =
  3458. llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
  3459. overflow_arg_area = CGF.Builder.CreateGEP(CGF.Int8Ty, overflow_arg_area,
  3460. Offset, "overflow_arg_area.next");
  3461. CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
  3462. // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
  3463. return Address(Res, LTy, Align);
  3464. }
  3465. Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  3466. QualType Ty) const {
  3467. // Assume that va_list type is correct; should be pointer to LLVM type:
  3468. // struct {
  3469. // i32 gp_offset;
  3470. // i32 fp_offset;
  3471. // i8* overflow_arg_area;
  3472. // i8* reg_save_area;
  3473. // };
  3474. unsigned neededInt, neededSSE;
  3475. Ty = getContext().getCanonicalType(Ty);
  3476. ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
  3477. /*isNamedArg*/false);
  3478. // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
  3479. // in the registers. If not go to step 7.
  3480. if (!neededInt && !neededSSE)
  3481. return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
  3482. // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
  3483. // general purpose registers needed to pass type and num_fp to hold
  3484. // the number of floating point registers needed.
  3485. // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
  3486. // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
  3487. // l->fp_offset > 304 - num_fp * 16 go to step 7.
  3488. //
  3489. // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
  3490. // register save space).
  3491. llvm::Value *InRegs = nullptr;
  3492. Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
  3493. llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
  3494. if (neededInt) {
  3495. gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
  3496. gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
  3497. InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
  3498. InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
  3499. }
  3500. if (neededSSE) {
  3501. fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
  3502. fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
  3503. llvm::Value *FitsInFP =
  3504. llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
  3505. FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
  3506. InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
  3507. }
  3508. llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
  3509. llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
  3510. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
  3511. CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
  3512. // Emit code to load the value if it was passed in registers.
  3513. CGF.EmitBlock(InRegBlock);
  3514. // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
  3515. // an offset of l->gp_offset and/or l->fp_offset. This may require
  3516. // copying to a temporary location in case the parameter is passed
  3517. // in different register classes or requires an alignment greater
  3518. // than 8 for general purpose registers and 16 for XMM registers.
  3519. //
  3520. // FIXME: This really results in shameful code when we end up needing to
  3521. // collect arguments from different places; often what should result in a
  3522. // simple assembling of a structure from scattered addresses has many more
  3523. // loads than necessary. Can we clean this up?
  3524. llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
  3525. llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
  3526. CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
  3527. Address RegAddr = Address::invalid();
  3528. if (neededInt && neededSSE) {
  3529. // FIXME: Cleanup.
  3530. assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
  3531. llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
  3532. Address Tmp = CGF.CreateMemTemp(Ty);
  3533. Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
  3534. assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
  3535. llvm::Type *TyLo = ST->getElementType(0);
  3536. llvm::Type *TyHi = ST->getElementType(1);
  3537. assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
  3538. "Unexpected ABI info for mixed regs");
  3539. llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
  3540. llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
  3541. llvm::Value *GPAddr =
  3542. CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset);
  3543. llvm::Value *FPAddr =
  3544. CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset);
  3545. llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
  3546. llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
  3547. // Copy the first element.
  3548. // FIXME: Our choice of alignment here and below is probably pessimistic.
  3549. llvm::Value *V = CGF.Builder.CreateAlignedLoad(
  3550. TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
  3551. CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
  3552. CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
  3553. // Copy the second element.
  3554. V = CGF.Builder.CreateAlignedLoad(
  3555. TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
  3556. CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
  3557. CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
  3558. RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
  3559. } else if (neededInt) {
  3560. RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, gp_offset),
  3561. CGF.Int8Ty, CharUnits::fromQuantity(8));
  3562. RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
  3563. // Copy to a temporary if necessary to ensure the appropriate alignment.
  3564. auto TInfo = getContext().getTypeInfoInChars(Ty);
  3565. uint64_t TySize = TInfo.Width.getQuantity();
  3566. CharUnits TyAlign = TInfo.Align;
  3567. // Copy into a temporary if the type is more aligned than the
  3568. // register save area.
  3569. if (TyAlign.getQuantity() > 8) {
  3570. Address Tmp = CGF.CreateMemTemp(Ty);
  3571. CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
  3572. RegAddr = Tmp;
  3573. }
  3574. } else if (neededSSE == 1) {
  3575. RegAddr = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, fp_offset),
  3576. CGF.Int8Ty, CharUnits::fromQuantity(16));
  3577. RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
  3578. } else {
  3579. assert(neededSSE == 2 && "Invalid number of needed registers!");
  3580. // SSE registers are spaced 16 bytes apart in the register save
  3581. // area, we need to collect the two eightbytes together.
  3582. // The ABI isn't explicit about this, but it seems reasonable
  3583. // to assume that the slots are 16-byte aligned, since the stack is
  3584. // naturally 16-byte aligned and the prologue is expected to store
  3585. // all the SSE registers to the RSA.
  3586. Address RegAddrLo = Address(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea,
  3587. fp_offset),
  3588. CGF.Int8Ty, CharUnits::fromQuantity(16));
  3589. Address RegAddrHi =
  3590. CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
  3591. CharUnits::fromQuantity(16));
  3592. llvm::Type *ST = AI.canHaveCoerceToType()
  3593. ? AI.getCoerceToType()
  3594. : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
  3595. llvm::Value *V;
  3596. Address Tmp = CGF.CreateMemTemp(Ty);
  3597. Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
  3598. V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
  3599. RegAddrLo, ST->getStructElementType(0)));
  3600. CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
  3601. V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
  3602. RegAddrHi, ST->getStructElementType(1)));
  3603. CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
  3604. RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
  3605. }
  3606. // AMD64-ABI 3.5.7p5: Step 5. Set:
  3607. // l->gp_offset = l->gp_offset + num_gp * 8
  3608. // l->fp_offset = l->fp_offset + num_fp * 16.
  3609. if (neededInt) {
  3610. llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
  3611. CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
  3612. gp_offset_p);
  3613. }
  3614. if (neededSSE) {
  3615. llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
  3616. CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
  3617. fp_offset_p);
  3618. }
  3619. CGF.EmitBranch(ContBlock);
  3620. // Emit code to load the value if it was passed in memory.
  3621. CGF.EmitBlock(InMemBlock);
  3622. Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
  3623. // Return the appropriate result.
  3624. CGF.EmitBlock(ContBlock);
  3625. Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
  3626. "vaarg.addr");
  3627. return ResAddr;
  3628. }
  3629. Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
  3630. QualType Ty) const {
  3631. // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
  3632. // not 1, 2, 4, or 8 bytes, must be passed by reference."
  3633. uint64_t Width = getContext().getTypeSize(Ty);
  3634. bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
  3635. return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
  3636. CGF.getContext().getTypeInfoInChars(Ty),
  3637. CharUnits::fromQuantity(8),
  3638. /*allowHigherAlign*/ false);
  3639. }
  3640. ABIArgInfo WinX86_64ABIInfo::reclassifyHvaArgForVectorCall(
  3641. QualType Ty, unsigned &FreeSSERegs, const ABIArgInfo &current) const {
  3642. const Type *Base = nullptr;
  3643. uint64_t NumElts = 0;
  3644. if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
  3645. isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
  3646. FreeSSERegs -= NumElts;
  3647. return getDirectX86Hva();
  3648. }
  3649. return current;
  3650. }
  3651. ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
  3652. bool IsReturnType, bool IsVectorCall,
  3653. bool IsRegCall) const {
  3654. if (Ty->isVoidType())
  3655. return ABIArgInfo::getIgnore();
  3656. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  3657. Ty = EnumTy->getDecl()->getIntegerType();
  3658. TypeInfo Info = getContext().getTypeInfo(Ty);
  3659. uint64_t Width = Info.Width;
  3660. CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
  3661. const RecordType *RT = Ty->getAs<RecordType>();
  3662. if (RT) {
  3663. if (!IsReturnType) {
  3664. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
  3665. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  3666. }
  3667. if (RT->getDecl()->hasFlexibleArrayMember())
  3668. return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
  3669. }
  3670. const Type *Base = nullptr;
  3671. uint64_t NumElts = 0;
  3672. // vectorcall adds the concept of a homogenous vector aggregate, similar to
  3673. // other targets.
  3674. if ((IsVectorCall || IsRegCall) &&
  3675. isHomogeneousAggregate(Ty, Base, NumElts)) {
  3676. if (IsRegCall) {
  3677. if (FreeSSERegs >= NumElts) {
  3678. FreeSSERegs -= NumElts;
  3679. if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
  3680. return ABIArgInfo::getDirect();
  3681. return ABIArgInfo::getExpand();
  3682. }
  3683. return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
  3684. } else if (IsVectorCall) {
  3685. if (FreeSSERegs >= NumElts &&
  3686. (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
  3687. FreeSSERegs -= NumElts;
  3688. return ABIArgInfo::getDirect();
  3689. } else if (IsReturnType) {
  3690. return ABIArgInfo::getExpand();
  3691. } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
  3692. // HVAs are delayed and reclassified in the 2nd step.
  3693. return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
  3694. }
  3695. }
  3696. }
  3697. if (Ty->isMemberPointerType()) {
  3698. // If the member pointer is represented by an LLVM int or ptr, pass it
  3699. // directly.
  3700. llvm::Type *LLTy = CGT.ConvertType(Ty);
  3701. if (LLTy->isPointerTy() || LLTy->isIntegerTy())
  3702. return ABIArgInfo::getDirect();
  3703. }
  3704. if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
  3705. // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
  3706. // not 1, 2, 4, or 8 bytes, must be passed by reference."
  3707. if (Width > 64 || !llvm::isPowerOf2_64(Width))
  3708. return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
  3709. // Otherwise, coerce it to a small integer.
  3710. return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
  3711. }
  3712. if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
  3713. switch (BT->getKind()) {
  3714. case BuiltinType::Bool:
  3715. // Bool type is always extended to the ABI, other builtin types are not
  3716. // extended.
  3717. return ABIArgInfo::getExtend(Ty);
  3718. case BuiltinType::LongDouble:
  3719. // Mingw64 GCC uses the old 80 bit extended precision floating point
  3720. // unit. It passes them indirectly through memory.
  3721. if (IsMingw64) {
  3722. const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
  3723. if (LDF == &llvm::APFloat::x87DoubleExtended())
  3724. return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
  3725. }
  3726. break;
  3727. case BuiltinType::Int128:
  3728. case BuiltinType::UInt128:
  3729. // If it's a parameter type, the normal ABI rule is that arguments larger
  3730. // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
  3731. // even though it isn't particularly efficient.
  3732. if (!IsReturnType)
  3733. return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
  3734. // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
  3735. // Clang matches them for compatibility.
  3736. return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
  3737. llvm::Type::getInt64Ty(getVMContext()), 2));
  3738. default:
  3739. break;
  3740. }
  3741. }
  3742. if (Ty->isBitIntType()) {
  3743. // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
  3744. // not 1, 2, 4, or 8 bytes, must be passed by reference."
  3745. // However, non-power-of-two bit-precise integers will be passed as 1, 2, 4,
  3746. // or 8 bytes anyway as long is it fits in them, so we don't have to check
  3747. // the power of 2.
  3748. if (Width <= 64)
  3749. return ABIArgInfo::getDirect();
  3750. return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
  3751. }
  3752. return ABIArgInfo::getDirect();
  3753. }
  3754. void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
  3755. const unsigned CC = FI.getCallingConvention();
  3756. bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
  3757. bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
  3758. // If __attribute__((sysv_abi)) is in use, use the SysV argument
  3759. // classification rules.
  3760. if (CC == llvm::CallingConv::X86_64_SysV) {
  3761. X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
  3762. SysVABIInfo.computeInfo(FI);
  3763. return;
  3764. }
  3765. unsigned FreeSSERegs = 0;
  3766. if (IsVectorCall) {
  3767. // We can use up to 4 SSE return registers with vectorcall.
  3768. FreeSSERegs = 4;
  3769. } else if (IsRegCall) {
  3770. // RegCall gives us 16 SSE registers.
  3771. FreeSSERegs = 16;
  3772. }
  3773. if (!getCXXABI().classifyReturnType(FI))
  3774. FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
  3775. IsVectorCall, IsRegCall);
  3776. if (IsVectorCall) {
  3777. // We can use up to 6 SSE register parameters with vectorcall.
  3778. FreeSSERegs = 6;
  3779. } else if (IsRegCall) {
  3780. // RegCall gives us 16 SSE registers, we can reuse the return registers.
  3781. FreeSSERegs = 16;
  3782. }
  3783. unsigned ArgNum = 0;
  3784. unsigned ZeroSSERegs = 0;
  3785. for (auto &I : FI.arguments()) {
  3786. // Vectorcall in x64 only permits the first 6 arguments to be passed as
  3787. // XMM/YMM registers. After the sixth argument, pretend no vector
  3788. // registers are left.
  3789. unsigned *MaybeFreeSSERegs =
  3790. (IsVectorCall && ArgNum >= 6) ? &ZeroSSERegs : &FreeSSERegs;
  3791. I.info =
  3792. classify(I.type, *MaybeFreeSSERegs, false, IsVectorCall, IsRegCall);
  3793. ++ArgNum;
  3794. }
  3795. if (IsVectorCall) {
  3796. // For vectorcall, assign aggregate HVAs to any free vector registers in a
  3797. // second pass.
  3798. for (auto &I : FI.arguments())
  3799. I.info = reclassifyHvaArgForVectorCall(I.type, FreeSSERegs, I.info);
  3800. }
  3801. }
  3802. Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  3803. QualType Ty) const {
  3804. // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
  3805. // not 1, 2, 4, or 8 bytes, must be passed by reference."
  3806. uint64_t Width = getContext().getTypeSize(Ty);
  3807. bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
  3808. return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
  3809. CGF.getContext().getTypeInfoInChars(Ty),
  3810. CharUnits::fromQuantity(8),
  3811. /*allowHigherAlign*/ false);
  3812. }
  3813. static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  3814. llvm::Value *Address, bool Is64Bit,
  3815. bool IsAIX) {
  3816. // This is calculated from the LLVM and GCC tables and verified
  3817. // against gcc output. AFAIK all PPC ABIs use the same encoding.
  3818. CodeGen::CGBuilderTy &Builder = CGF.Builder;
  3819. llvm::IntegerType *i8 = CGF.Int8Ty;
  3820. llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
  3821. llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
  3822. llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
  3823. // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers
  3824. AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31);
  3825. // 32-63: fp0-31, the 8-byte floating-point registers
  3826. AssignToArrayRange(Builder, Address, Eight8, 32, 63);
  3827. // 64-67 are various 4-byte or 8-byte special-purpose registers:
  3828. // 64: mq
  3829. // 65: lr
  3830. // 66: ctr
  3831. // 67: ap
  3832. AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67);
  3833. // 68-76 are various 4-byte special-purpose registers:
  3834. // 68-75 cr0-7
  3835. // 76: xer
  3836. AssignToArrayRange(Builder, Address, Four8, 68, 76);
  3837. // 77-108: v0-31, the 16-byte vector registers
  3838. AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
  3839. // 109: vrsave
  3840. // 110: vscr
  3841. AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110);
  3842. // AIX does not utilize the rest of the registers.
  3843. if (IsAIX)
  3844. return false;
  3845. // 111: spe_acc
  3846. // 112: spefscr
  3847. // 113: sfp
  3848. AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113);
  3849. if (!Is64Bit)
  3850. return false;
  3851. // TODO: Need to verify if these registers are used on 64 bit AIX with Power8
  3852. // or above CPU.
  3853. // 64-bit only registers:
  3854. // 114: tfhar
  3855. // 115: tfiar
  3856. // 116: texasr
  3857. AssignToArrayRange(Builder, Address, Eight8, 114, 116);
  3858. return false;
  3859. }
  3860. // AIX
  3861. namespace {
  3862. /// AIXABIInfo - The AIX XCOFF ABI information.
  3863. class AIXABIInfo : public ABIInfo {
  3864. const bool Is64Bit;
  3865. const unsigned PtrByteSize;
  3866. CharUnits getParamTypeAlignment(QualType Ty) const;
  3867. public:
  3868. AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
  3869. : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {}
  3870. bool isPromotableTypeForABI(QualType Ty) const;
  3871. ABIArgInfo classifyReturnType(QualType RetTy) const;
  3872. ABIArgInfo classifyArgumentType(QualType Ty) const;
  3873. void computeInfo(CGFunctionInfo &FI) const override {
  3874. if (!getCXXABI().classifyReturnType(FI))
  3875. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  3876. for (auto &I : FI.arguments())
  3877. I.info = classifyArgumentType(I.type);
  3878. }
  3879. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  3880. QualType Ty) const override;
  3881. };
  3882. class AIXTargetCodeGenInfo : public TargetCodeGenInfo {
  3883. const bool Is64Bit;
  3884. public:
  3885. AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit)
  3886. : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)),
  3887. Is64Bit(Is64Bit) {}
  3888. int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
  3889. return 1; // r1 is the dedicated stack pointer
  3890. }
  3891. bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  3892. llvm::Value *Address) const override;
  3893. };
  3894. } // namespace
  3895. // Return true if the ABI requires Ty to be passed sign- or zero-
  3896. // extended to 32/64 bits.
  3897. bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const {
  3898. // Treat an enum type as its underlying type.
  3899. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  3900. Ty = EnumTy->getDecl()->getIntegerType();
  3901. // Promotable integer types are required to be promoted by the ABI.
  3902. if (Ty->isPromotableIntegerType())
  3903. return true;
  3904. if (!Is64Bit)
  3905. return false;
  3906. // For 64 bit mode, in addition to the usual promotable integer types, we also
  3907. // need to extend all 32-bit types, since the ABI requires promotion to 64
  3908. // bits.
  3909. if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
  3910. switch (BT->getKind()) {
  3911. case BuiltinType::Int:
  3912. case BuiltinType::UInt:
  3913. return true;
  3914. default:
  3915. break;
  3916. }
  3917. return false;
  3918. }
  3919. ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const {
  3920. if (RetTy->isAnyComplexType())
  3921. return ABIArgInfo::getDirect();
  3922. if (RetTy->isVectorType())
  3923. return ABIArgInfo::getDirect();
  3924. if (RetTy->isVoidType())
  3925. return ABIArgInfo::getIgnore();
  3926. if (isAggregateTypeForABI(RetTy))
  3927. return getNaturalAlignIndirect(RetTy);
  3928. return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
  3929. : ABIArgInfo::getDirect());
  3930. }
  3931. ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const {
  3932. Ty = useFirstFieldIfTransparentUnion(Ty);
  3933. if (Ty->isAnyComplexType())
  3934. return ABIArgInfo::getDirect();
  3935. if (Ty->isVectorType())
  3936. return ABIArgInfo::getDirect();
  3937. if (isAggregateTypeForABI(Ty)) {
  3938. // Records with non-trivial destructors/copy-constructors should not be
  3939. // passed by value.
  3940. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
  3941. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  3942. CharUnits CCAlign = getParamTypeAlignment(Ty);
  3943. CharUnits TyAlign = getContext().getTypeAlignInChars(Ty);
  3944. return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true,
  3945. /*Realign*/ TyAlign > CCAlign);
  3946. }
  3947. return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
  3948. : ABIArgInfo::getDirect());
  3949. }
  3950. CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const {
  3951. // Complex types are passed just like their elements.
  3952. if (const ComplexType *CTy = Ty->getAs<ComplexType>())
  3953. Ty = CTy->getElementType();
  3954. if (Ty->isVectorType())
  3955. return CharUnits::fromQuantity(16);
  3956. // If the structure contains a vector type, the alignment is 16.
  3957. if (isRecordWithSIMDVectorType(getContext(), Ty))
  3958. return CharUnits::fromQuantity(16);
  3959. return CharUnits::fromQuantity(PtrByteSize);
  3960. }
  3961. Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  3962. QualType Ty) const {
  3963. auto TypeInfo = getContext().getTypeInfoInChars(Ty);
  3964. TypeInfo.Align = getParamTypeAlignment(Ty);
  3965. CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize);
  3966. // If we have a complex type and the base type is smaller than the register
  3967. // size, the ABI calls for the real and imaginary parts to be right-adjusted
  3968. // in separate words in 32bit mode or doublewords in 64bit mode. However,
  3969. // Clang expects us to produce a pointer to a structure with the two parts
  3970. // packed tightly. So generate loads of the real and imaginary parts relative
  3971. // to the va_list pointer, and store them to a temporary structure. We do the
  3972. // same as the PPC64ABI here.
  3973. if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
  3974. CharUnits EltSize = TypeInfo.Width / 2;
  3975. if (EltSize < SlotSize)
  3976. return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy);
  3977. }
  3978. return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo,
  3979. SlotSize, /*AllowHigher*/ true);
  3980. }
  3981. bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable(
  3982. CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const {
  3983. return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true);
  3984. }
  3985. // PowerPC-32
  3986. namespace {
  3987. /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
  3988. class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
  3989. bool IsSoftFloatABI;
  3990. bool IsRetSmallStructInRegABI;
  3991. CharUnits getParamTypeAlignment(QualType Ty) const;
  3992. public:
  3993. PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI,
  3994. bool RetSmallStructInRegABI)
  3995. : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI),
  3996. IsRetSmallStructInRegABI(RetSmallStructInRegABI) {}
  3997. ABIArgInfo classifyReturnType(QualType RetTy) const;
  3998. void computeInfo(CGFunctionInfo &FI) const override {
  3999. if (!getCXXABI().classifyReturnType(FI))
  4000. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  4001. for (auto &I : FI.arguments())
  4002. I.info = classifyArgumentType(I.type);
  4003. }
  4004. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  4005. QualType Ty) const override;
  4006. };
  4007. class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
  4008. public:
  4009. PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI,
  4010. bool RetSmallStructInRegABI)
  4011. : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>(
  4012. CGT, SoftFloatABI, RetSmallStructInRegABI)) {}
  4013. static bool isStructReturnInRegABI(const llvm::Triple &Triple,
  4014. const CodeGenOptions &Opts);
  4015. int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
  4016. // This is recovered from gcc output.
  4017. return 1; // r1 is the dedicated stack pointer
  4018. }
  4019. bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  4020. llvm::Value *Address) const override;
  4021. };
  4022. }
  4023. CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
  4024. // Complex types are passed just like their elements.
  4025. if (const ComplexType *CTy = Ty->getAs<ComplexType>())
  4026. Ty = CTy->getElementType();
  4027. if (Ty->isVectorType())
  4028. return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
  4029. : 4);
  4030. // For single-element float/vector structs, we consider the whole type
  4031. // to have the same alignment requirements as its single element.
  4032. const Type *AlignTy = nullptr;
  4033. if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
  4034. const BuiltinType *BT = EltType->getAs<BuiltinType>();
  4035. if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
  4036. (BT && BT->isFloatingPoint()))
  4037. AlignTy = EltType;
  4038. }
  4039. if (AlignTy)
  4040. return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
  4041. return CharUnits::fromQuantity(4);
  4042. }
  4043. ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
  4044. uint64_t Size;
  4045. // -msvr4-struct-return puts small aggregates in GPR3 and GPR4.
  4046. if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI &&
  4047. (Size = getContext().getTypeSize(RetTy)) <= 64) {
  4048. // System V ABI (1995), page 3-22, specified:
  4049. // > A structure or union whose size is less than or equal to 8 bytes
  4050. // > shall be returned in r3 and r4, as if it were first stored in the
  4051. // > 8-byte aligned memory area and then the low addressed word were
  4052. // > loaded into r3 and the high-addressed word into r4. Bits beyond
  4053. // > the last member of the structure or union are not defined.
  4054. //
  4055. // GCC for big-endian PPC32 inserts the pad before the first member,
  4056. // not "beyond the last member" of the struct. To stay compatible
  4057. // with GCC, we coerce the struct to an integer of the same size.
  4058. // LLVM will extend it and return i32 in r3, or i64 in r3:r4.
  4059. if (Size == 0)
  4060. return ABIArgInfo::getIgnore();
  4061. else {
  4062. llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size);
  4063. return ABIArgInfo::getDirect(CoerceTy);
  4064. }
  4065. }
  4066. return DefaultABIInfo::classifyReturnType(RetTy);
  4067. }
  4068. // TODO: this implementation is now likely redundant with
  4069. // DefaultABIInfo::EmitVAArg.
  4070. Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
  4071. QualType Ty) const {
  4072. if (getTarget().getTriple().isOSDarwin()) {
  4073. auto TI = getContext().getTypeInfoInChars(Ty);
  4074. TI.Align = getParamTypeAlignment(Ty);
  4075. CharUnits SlotSize = CharUnits::fromQuantity(4);
  4076. return emitVoidPtrVAArg(CGF, VAList, Ty,
  4077. classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
  4078. /*AllowHigherAlign=*/true);
  4079. }
  4080. const unsigned OverflowLimit = 8;
  4081. if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
  4082. // TODO: Implement this. For now ignore.
  4083. (void)CTy;
  4084. return Address::invalid(); // FIXME?
  4085. }
  4086. // struct __va_list_tag {
  4087. // unsigned char gpr;
  4088. // unsigned char fpr;
  4089. // unsigned short reserved;
  4090. // void *overflow_arg_area;
  4091. // void *reg_save_area;
  4092. // };
  4093. bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
  4094. bool isInt = !Ty->isFloatingType();
  4095. bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
  4096. // All aggregates are passed indirectly? That doesn't seem consistent
  4097. // with the argument-lowering code.
  4098. bool isIndirect = isAggregateTypeForABI(Ty);
  4099. CGBuilderTy &Builder = CGF.Builder;
  4100. // The calling convention either uses 1-2 GPRs or 1 FPR.
  4101. Address NumRegsAddr = Address::invalid();
  4102. if (isInt || IsSoftFloatABI) {
  4103. NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
  4104. } else {
  4105. NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
  4106. }
  4107. llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
  4108. // "Align" the register count when TY is i64.
  4109. if (isI64 || (isF64 && IsSoftFloatABI)) {
  4110. NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
  4111. NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
  4112. }
  4113. llvm::Value *CC =
  4114. Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
  4115. llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
  4116. llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
  4117. llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
  4118. Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
  4119. llvm::Type *DirectTy = CGF.ConvertType(Ty);
  4120. if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
  4121. // Case 1: consume registers.
  4122. Address RegAddr = Address::invalid();
  4123. {
  4124. CGF.EmitBlock(UsingRegs);
  4125. Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
  4126. RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
  4127. CharUnits::fromQuantity(8));
  4128. assert(RegAddr.getElementType() == CGF.Int8Ty);
  4129. // Floating-point registers start after the general-purpose registers.
  4130. if (!(isInt || IsSoftFloatABI)) {
  4131. RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
  4132. CharUnits::fromQuantity(32));
  4133. }
  4134. // Get the address of the saved value by scaling the number of
  4135. // registers we've used by the number of
  4136. CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
  4137. llvm::Value *RegOffset =
  4138. Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
  4139. RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
  4140. RegAddr.getPointer(), RegOffset),
  4141. RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
  4142. RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
  4143. // Increase the used-register count.
  4144. NumRegs =
  4145. Builder.CreateAdd(NumRegs,
  4146. Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
  4147. Builder.CreateStore(NumRegs, NumRegsAddr);
  4148. CGF.EmitBranch(Cont);
  4149. }
  4150. // Case 2: consume space in the overflow area.
  4151. Address MemAddr = Address::invalid();
  4152. {
  4153. CGF.EmitBlock(UsingOverflow);
  4154. Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
  4155. // Everything in the overflow area is rounded up to a size of at least 4.
  4156. CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
  4157. CharUnits Size;
  4158. if (!isIndirect) {
  4159. auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
  4160. Size = TypeInfo.Width.alignTo(OverflowAreaAlign);
  4161. } else {
  4162. Size = CGF.getPointerSize();
  4163. }
  4164. Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
  4165. Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
  4166. OverflowAreaAlign);
  4167. // Round up address of argument to alignment
  4168. CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
  4169. if (Align > OverflowAreaAlign) {
  4170. llvm::Value *Ptr = OverflowArea.getPointer();
  4171. OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
  4172. Align);
  4173. }
  4174. MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
  4175. // Increase the overflow area.
  4176. OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
  4177. Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
  4178. CGF.EmitBranch(Cont);
  4179. }
  4180. CGF.EmitBlock(Cont);
  4181. // Merge the cases with a phi.
  4182. Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
  4183. "vaarg.addr");
  4184. // Load the pointer if the argument was passed indirectly.
  4185. if (isIndirect) {
  4186. Result = Address(Builder.CreateLoad(Result, "aggr"),
  4187. getContext().getTypeAlignInChars(Ty));
  4188. }
  4189. return Result;
  4190. }
  4191. bool PPC32TargetCodeGenInfo::isStructReturnInRegABI(
  4192. const llvm::Triple &Triple, const CodeGenOptions &Opts) {
  4193. assert(Triple.isPPC32());
  4194. switch (Opts.getStructReturnConvention()) {
  4195. case CodeGenOptions::SRCK_Default:
  4196. break;
  4197. case CodeGenOptions::SRCK_OnStack: // -maix-struct-return
  4198. return false;
  4199. case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return
  4200. return true;
  4201. }
  4202. if (Triple.isOSBinFormatELF() && !Triple.isOSLinux())
  4203. return true;
  4204. return false;
  4205. }
  4206. bool
  4207. PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  4208. llvm::Value *Address) const {
  4209. return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false,
  4210. /*IsAIX*/ false);
  4211. }
  4212. // PowerPC-64
  4213. namespace {
  4214. /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
  4215. class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
  4216. public:
  4217. enum ABIKind {
  4218. ELFv1 = 0,
  4219. ELFv2
  4220. };
  4221. private:
  4222. static const unsigned GPRBits = 64;
  4223. ABIKind Kind;
  4224. bool IsSoftFloatABI;
  4225. public:
  4226. PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind,
  4227. bool SoftFloatABI)
  4228. : SwiftABIInfo(CGT), Kind(Kind), IsSoftFloatABI(SoftFloatABI) {}
  4229. bool isPromotableTypeForABI(QualType Ty) const;
  4230. CharUnits getParamTypeAlignment(QualType Ty) const;
  4231. ABIArgInfo classifyReturnType(QualType RetTy) const;
  4232. ABIArgInfo classifyArgumentType(QualType Ty) const;
  4233. bool isHomogeneousAggregateBaseType(QualType Ty) const override;
  4234. bool isHomogeneousAggregateSmallEnough(const Type *Ty,
  4235. uint64_t Members) const override;
  4236. // TODO: We can add more logic to computeInfo to improve performance.
  4237. // Example: For aggregate arguments that fit in a register, we could
  4238. // use getDirectInReg (as is done below for structs containing a single
  4239. // floating-point value) to avoid pushing them to memory on function
  4240. // entry. This would require changing the logic in PPCISelLowering
  4241. // when lowering the parameters in the caller and args in the callee.
  4242. void computeInfo(CGFunctionInfo &FI) const override {
  4243. if (!getCXXABI().classifyReturnType(FI))
  4244. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  4245. for (auto &I : FI.arguments()) {
  4246. // We rely on the default argument classification for the most part.
  4247. // One exception: An aggregate containing a single floating-point
  4248. // or vector item must be passed in a register if one is available.
  4249. const Type *T = isSingleElementStruct(I.type, getContext());
  4250. if (T) {
  4251. const BuiltinType *BT = T->getAs<BuiltinType>();
  4252. if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
  4253. (BT && BT->isFloatingPoint())) {
  4254. QualType QT(T, 0);
  4255. I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
  4256. continue;
  4257. }
  4258. }
  4259. I.info = classifyArgumentType(I.type);
  4260. }
  4261. }
  4262. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  4263. QualType Ty) const override;
  4264. bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
  4265. bool asReturnValue) const override {
  4266. return occupiesMoreThan(CGT, scalars, /*total*/ 4);
  4267. }
  4268. bool isSwiftErrorInRegister() const override {
  4269. return false;
  4270. }
  4271. };
  4272. class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
  4273. public:
  4274. PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
  4275. PPC64_SVR4_ABIInfo::ABIKind Kind,
  4276. bool SoftFloatABI)
  4277. : TargetCodeGenInfo(
  4278. std::make_unique<PPC64_SVR4_ABIInfo>(CGT, Kind, SoftFloatABI)) {}
  4279. int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
  4280. // This is recovered from gcc output.
  4281. return 1; // r1 is the dedicated stack pointer
  4282. }
  4283. bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  4284. llvm::Value *Address) const override;
  4285. };
  4286. class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
  4287. public:
  4288. PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
  4289. int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
  4290. // This is recovered from gcc output.
  4291. return 1; // r1 is the dedicated stack pointer
  4292. }
  4293. bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  4294. llvm::Value *Address) const override;
  4295. };
  4296. }
  4297. // Return true if the ABI requires Ty to be passed sign- or zero-
  4298. // extended to 64 bits.
  4299. bool
  4300. PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
  4301. // Treat an enum type as its underlying type.
  4302. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  4303. Ty = EnumTy->getDecl()->getIntegerType();
  4304. // Promotable integer types are required to be promoted by the ABI.
  4305. if (isPromotableIntegerTypeForABI(Ty))
  4306. return true;
  4307. // In addition to the usual promotable integer types, we also need to
  4308. // extend all 32-bit types, since the ABI requires promotion to 64 bits.
  4309. if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
  4310. switch (BT->getKind()) {
  4311. case BuiltinType::Int:
  4312. case BuiltinType::UInt:
  4313. return true;
  4314. default:
  4315. break;
  4316. }
  4317. if (const auto *EIT = Ty->getAs<BitIntType>())
  4318. if (EIT->getNumBits() < 64)
  4319. return true;
  4320. return false;
  4321. }
  4322. /// isAlignedParamType - Determine whether a type requires 16-byte or
  4323. /// higher alignment in the parameter area. Always returns at least 8.
  4324. CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
  4325. // Complex types are passed just like their elements.
  4326. if (const ComplexType *CTy = Ty->getAs<ComplexType>())
  4327. Ty = CTy->getElementType();
  4328. auto FloatUsesVector = [this](QualType Ty){
  4329. return Ty->isRealFloatingType() && &getContext().getFloatTypeSemantics(
  4330. Ty) == &llvm::APFloat::IEEEquad();
  4331. };
  4332. // Only vector types of size 16 bytes need alignment (larger types are
  4333. // passed via reference, smaller types are not aligned).
  4334. if (Ty->isVectorType()) {
  4335. return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
  4336. } else if (FloatUsesVector(Ty)) {
  4337. // According to ABI document section 'Optional Save Areas': If extended
  4338. // precision floating-point values in IEEE BINARY 128 QUADRUPLE PRECISION
  4339. // format are supported, map them to a single quadword, quadword aligned.
  4340. return CharUnits::fromQuantity(16);
  4341. }
  4342. // For single-element float/vector structs, we consider the whole type
  4343. // to have the same alignment requirements as its single element.
  4344. const Type *AlignAsType = nullptr;
  4345. const Type *EltType = isSingleElementStruct(Ty, getContext());
  4346. if (EltType) {
  4347. const BuiltinType *BT = EltType->getAs<BuiltinType>();
  4348. if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
  4349. (BT && BT->isFloatingPoint()))
  4350. AlignAsType = EltType;
  4351. }
  4352. // Likewise for ELFv2 homogeneous aggregates.
  4353. const Type *Base = nullptr;
  4354. uint64_t Members = 0;
  4355. if (!AlignAsType && Kind == ELFv2 &&
  4356. isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
  4357. AlignAsType = Base;
  4358. // With special case aggregates, only vector base types need alignment.
  4359. if (AlignAsType) {
  4360. bool UsesVector = AlignAsType->isVectorType() ||
  4361. FloatUsesVector(QualType(AlignAsType, 0));
  4362. return CharUnits::fromQuantity(UsesVector ? 16 : 8);
  4363. }
  4364. // Otherwise, we only need alignment for any aggregate type that
  4365. // has an alignment requirement of >= 16 bytes.
  4366. if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
  4367. return CharUnits::fromQuantity(16);
  4368. }
  4369. return CharUnits::fromQuantity(8);
  4370. }
  4371. /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
  4372. /// aggregate. Base is set to the base element type, and Members is set
  4373. /// to the number of base elements.
  4374. bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
  4375. uint64_t &Members) const {
  4376. if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
  4377. uint64_t NElements = AT->getSize().getZExtValue();
  4378. if (NElements == 0)
  4379. return false;
  4380. if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
  4381. return false;
  4382. Members *= NElements;
  4383. } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
  4384. const RecordDecl *RD = RT->getDecl();
  4385. if (RD->hasFlexibleArrayMember())
  4386. return false;
  4387. Members = 0;
  4388. // If this is a C++ record, check the properties of the record such as
  4389. // bases and ABI specific restrictions
  4390. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4391. if (!getCXXABI().isPermittedToBeHomogeneousAggregate(CXXRD))
  4392. return false;
  4393. for (const auto &I : CXXRD->bases()) {
  4394. // Ignore empty records.
  4395. if (isEmptyRecord(getContext(), I.getType(), true))
  4396. continue;
  4397. uint64_t FldMembers;
  4398. if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
  4399. return false;
  4400. Members += FldMembers;
  4401. }
  4402. }
  4403. for (const auto *FD : RD->fields()) {
  4404. // Ignore (non-zero arrays of) empty records.
  4405. QualType FT = FD->getType();
  4406. while (const ConstantArrayType *AT =
  4407. getContext().getAsConstantArrayType(FT)) {
  4408. if (AT->getSize().getZExtValue() == 0)
  4409. return false;
  4410. FT = AT->getElementType();
  4411. }
  4412. if (isEmptyRecord(getContext(), FT, true))
  4413. continue;
  4414. // For compatibility with GCC, ignore empty bitfields in C++ mode.
  4415. if (getContext().getLangOpts().CPlusPlus &&
  4416. FD->isZeroLengthBitField(getContext()))
  4417. continue;
  4418. uint64_t FldMembers;
  4419. if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
  4420. return false;
  4421. Members = (RD->isUnion() ?
  4422. std::max(Members, FldMembers) : Members + FldMembers);
  4423. }
  4424. if (!Base)
  4425. return false;
  4426. // Ensure there is no padding.
  4427. if (getContext().getTypeSize(Base) * Members !=
  4428. getContext().getTypeSize(Ty))
  4429. return false;
  4430. } else {
  4431. Members = 1;
  4432. if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
  4433. Members = 2;
  4434. Ty = CT->getElementType();
  4435. }
  4436. // Most ABIs only support float, double, and some vector type widths.
  4437. if (!isHomogeneousAggregateBaseType(Ty))
  4438. return false;
  4439. // The base type must be the same for all members. Types that
  4440. // agree in both total size and mode (float vs. vector) are
  4441. // treated as being equivalent here.
  4442. const Type *TyPtr = Ty.getTypePtr();
  4443. if (!Base) {
  4444. Base = TyPtr;
  4445. // If it's a non-power-of-2 vector, its size is already a power-of-2,
  4446. // so make sure to widen it explicitly.
  4447. if (const VectorType *VT = Base->getAs<VectorType>()) {
  4448. QualType EltTy = VT->getElementType();
  4449. unsigned NumElements =
  4450. getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
  4451. Base = getContext()
  4452. .getVectorType(EltTy, NumElements, VT->getVectorKind())
  4453. .getTypePtr();
  4454. }
  4455. }
  4456. if (Base->isVectorType() != TyPtr->isVectorType() ||
  4457. getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
  4458. return false;
  4459. }
  4460. return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
  4461. }
  4462. bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
  4463. // Homogeneous aggregates for ELFv2 must have base types of float,
  4464. // double, long double, or 128-bit vectors.
  4465. if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
  4466. if (BT->getKind() == BuiltinType::Float ||
  4467. BT->getKind() == BuiltinType::Double ||
  4468. BT->getKind() == BuiltinType::LongDouble ||
  4469. BT->getKind() == BuiltinType::Ibm128 ||
  4470. (getContext().getTargetInfo().hasFloat128Type() &&
  4471. (BT->getKind() == BuiltinType::Float128))) {
  4472. if (IsSoftFloatABI)
  4473. return false;
  4474. return true;
  4475. }
  4476. }
  4477. if (const VectorType *VT = Ty->getAs<VectorType>()) {
  4478. if (getContext().getTypeSize(VT) == 128)
  4479. return true;
  4480. }
  4481. return false;
  4482. }
  4483. bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
  4484. const Type *Base, uint64_t Members) const {
  4485. // Vector and fp128 types require one register, other floating point types
  4486. // require one or two registers depending on their size.
  4487. uint32_t NumRegs =
  4488. ((getContext().getTargetInfo().hasFloat128Type() &&
  4489. Base->isFloat128Type()) ||
  4490. Base->isVectorType()) ? 1
  4491. : (getContext().getTypeSize(Base) + 63) / 64;
  4492. // Homogeneous Aggregates may occupy at most 8 registers.
  4493. return Members * NumRegs <= 8;
  4494. }
  4495. ABIArgInfo
  4496. PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
  4497. Ty = useFirstFieldIfTransparentUnion(Ty);
  4498. if (Ty->isAnyComplexType())
  4499. return ABIArgInfo::getDirect();
  4500. // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
  4501. // or via reference (larger than 16 bytes).
  4502. if (Ty->isVectorType()) {
  4503. uint64_t Size = getContext().getTypeSize(Ty);
  4504. if (Size > 128)
  4505. return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
  4506. else if (Size < 128) {
  4507. llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
  4508. return ABIArgInfo::getDirect(CoerceTy);
  4509. }
  4510. }
  4511. if (const auto *EIT = Ty->getAs<BitIntType>())
  4512. if (EIT->getNumBits() > 128)
  4513. return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
  4514. if (isAggregateTypeForABI(Ty)) {
  4515. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
  4516. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  4517. uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
  4518. uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
  4519. // ELFv2 homogeneous aggregates are passed as array types.
  4520. const Type *Base = nullptr;
  4521. uint64_t Members = 0;
  4522. if (Kind == ELFv2 &&
  4523. isHomogeneousAggregate(Ty, Base, Members)) {
  4524. llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
  4525. llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
  4526. return ABIArgInfo::getDirect(CoerceTy);
  4527. }
  4528. // If an aggregate may end up fully in registers, we do not
  4529. // use the ByVal method, but pass the aggregate as array.
  4530. // This is usually beneficial since we avoid forcing the
  4531. // back-end to store the argument to memory.
  4532. uint64_t Bits = getContext().getTypeSize(Ty);
  4533. if (Bits > 0 && Bits <= 8 * GPRBits) {
  4534. llvm::Type *CoerceTy;
  4535. // Types up to 8 bytes are passed as integer type (which will be
  4536. // properly aligned in the argument save area doubleword).
  4537. if (Bits <= GPRBits)
  4538. CoerceTy =
  4539. llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
  4540. // Larger types are passed as arrays, with the base type selected
  4541. // according to the required alignment in the save area.
  4542. else {
  4543. uint64_t RegBits = ABIAlign * 8;
  4544. uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
  4545. llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
  4546. CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
  4547. }
  4548. return ABIArgInfo::getDirect(CoerceTy);
  4549. }
  4550. // All other aggregates are passed ByVal.
  4551. return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
  4552. /*ByVal=*/true,
  4553. /*Realign=*/TyAlign > ABIAlign);
  4554. }
  4555. return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
  4556. : ABIArgInfo::getDirect());
  4557. }
  4558. ABIArgInfo
  4559. PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
  4560. if (RetTy->isVoidType())
  4561. return ABIArgInfo::getIgnore();
  4562. if (RetTy->isAnyComplexType())
  4563. return ABIArgInfo::getDirect();
  4564. // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
  4565. // or via reference (larger than 16 bytes).
  4566. if (RetTy->isVectorType()) {
  4567. uint64_t Size = getContext().getTypeSize(RetTy);
  4568. if (Size > 128)
  4569. return getNaturalAlignIndirect(RetTy);
  4570. else if (Size < 128) {
  4571. llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
  4572. return ABIArgInfo::getDirect(CoerceTy);
  4573. }
  4574. }
  4575. if (const auto *EIT = RetTy->getAs<BitIntType>())
  4576. if (EIT->getNumBits() > 128)
  4577. return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
  4578. if (isAggregateTypeForABI(RetTy)) {
  4579. // ELFv2 homogeneous aggregates are returned as array types.
  4580. const Type *Base = nullptr;
  4581. uint64_t Members = 0;
  4582. if (Kind == ELFv2 &&
  4583. isHomogeneousAggregate(RetTy, Base, Members)) {
  4584. llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
  4585. llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
  4586. return ABIArgInfo::getDirect(CoerceTy);
  4587. }
  4588. // ELFv2 small aggregates are returned in up to two registers.
  4589. uint64_t Bits = getContext().getTypeSize(RetTy);
  4590. if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
  4591. if (Bits == 0)
  4592. return ABIArgInfo::getIgnore();
  4593. llvm::Type *CoerceTy;
  4594. if (Bits > GPRBits) {
  4595. CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
  4596. CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
  4597. } else
  4598. CoerceTy =
  4599. llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
  4600. return ABIArgInfo::getDirect(CoerceTy);
  4601. }
  4602. // All other aggregates are returned indirectly.
  4603. return getNaturalAlignIndirect(RetTy);
  4604. }
  4605. return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
  4606. : ABIArgInfo::getDirect());
  4607. }
  4608. // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
  4609. Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  4610. QualType Ty) const {
  4611. auto TypeInfo = getContext().getTypeInfoInChars(Ty);
  4612. TypeInfo.Align = getParamTypeAlignment(Ty);
  4613. CharUnits SlotSize = CharUnits::fromQuantity(8);
  4614. // If we have a complex type and the base type is smaller than 8 bytes,
  4615. // the ABI calls for the real and imaginary parts to be right-adjusted
  4616. // in separate doublewords. However, Clang expects us to produce a
  4617. // pointer to a structure with the two parts packed tightly. So generate
  4618. // loads of the real and imaginary parts relative to the va_list pointer,
  4619. // and store them to a temporary structure.
  4620. if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
  4621. CharUnits EltSize = TypeInfo.Width / 2;
  4622. if (EltSize < SlotSize)
  4623. return complexTempStructure(CGF, VAListAddr, Ty, SlotSize, EltSize, CTy);
  4624. }
  4625. // Otherwise, just use the general rule.
  4626. return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
  4627. TypeInfo, SlotSize, /*AllowHigher*/ true);
  4628. }
  4629. bool
  4630. PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
  4631. CodeGen::CodeGenFunction &CGF,
  4632. llvm::Value *Address) const {
  4633. return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
  4634. /*IsAIX*/ false);
  4635. }
  4636. bool
  4637. PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  4638. llvm::Value *Address) const {
  4639. return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true,
  4640. /*IsAIX*/ false);
  4641. }
  4642. //===----------------------------------------------------------------------===//
  4643. // AArch64 ABI Implementation
  4644. //===----------------------------------------------------------------------===//
  4645. namespace {
  4646. class AArch64ABIInfo : public SwiftABIInfo {
  4647. public:
  4648. enum ABIKind {
  4649. AAPCS = 0,
  4650. DarwinPCS,
  4651. Win64
  4652. };
  4653. private:
  4654. ABIKind Kind;
  4655. public:
  4656. AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
  4657. : SwiftABIInfo(CGT), Kind(Kind) {}
  4658. private:
  4659. ABIKind getABIKind() const { return Kind; }
  4660. bool isDarwinPCS() const { return Kind == DarwinPCS; }
  4661. ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
  4662. ABIArgInfo classifyArgumentType(QualType RetTy, bool IsVariadic,
  4663. unsigned CallingConvention) const;
  4664. ABIArgInfo coerceIllegalVector(QualType Ty) const;
  4665. bool isHomogeneousAggregateBaseType(QualType Ty) const override;
  4666. bool isHomogeneousAggregateSmallEnough(const Type *Ty,
  4667. uint64_t Members) const override;
  4668. bool isIllegalVectorType(QualType Ty) const;
  4669. void computeInfo(CGFunctionInfo &FI) const override {
  4670. if (!::classifyReturnType(getCXXABI(), FI, *this))
  4671. FI.getReturnInfo() =
  4672. classifyReturnType(FI.getReturnType(), FI.isVariadic());
  4673. for (auto &it : FI.arguments())
  4674. it.info = classifyArgumentType(it.type, FI.isVariadic(),
  4675. FI.getCallingConvention());
  4676. }
  4677. Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
  4678. CodeGenFunction &CGF) const;
  4679. Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
  4680. CodeGenFunction &CGF) const;
  4681. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  4682. QualType Ty) const override {
  4683. llvm::Type *BaseTy = CGF.ConvertType(Ty);
  4684. if (isa<llvm::ScalableVectorType>(BaseTy))
  4685. llvm::report_fatal_error("Passing SVE types to variadic functions is "
  4686. "currently not supported");
  4687. return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
  4688. : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
  4689. : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
  4690. }
  4691. Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
  4692. QualType Ty) const override;
  4693. bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
  4694. bool asReturnValue) const override {
  4695. return occupiesMoreThan(CGT, scalars, /*total*/ 4);
  4696. }
  4697. bool isSwiftErrorInRegister() const override {
  4698. return true;
  4699. }
  4700. bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
  4701. unsigned elts) const override;
  4702. bool allowBFloatArgsAndRet() const override {
  4703. return getTarget().hasBFloat16Type();
  4704. }
  4705. };
  4706. class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
  4707. public:
  4708. AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
  4709. : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {}
  4710. StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
  4711. return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
  4712. }
  4713. int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
  4714. return 31;
  4715. }
  4716. bool doesReturnSlotInterfereWithArgs() const override { return false; }
  4717. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  4718. CodeGen::CodeGenModule &CGM) const override {
  4719. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
  4720. if (!FD)
  4721. return;
  4722. const auto *TA = FD->getAttr<TargetAttr>();
  4723. if (TA == nullptr)
  4724. return;
  4725. ParsedTargetAttr Attr = TA->parse();
  4726. if (Attr.BranchProtection.empty())
  4727. return;
  4728. TargetInfo::BranchProtectionInfo BPI;
  4729. StringRef Error;
  4730. (void)CGM.getTarget().validateBranchProtection(
  4731. Attr.BranchProtection, Attr.Architecture, BPI, Error);
  4732. assert(Error.empty());
  4733. auto *Fn = cast<llvm::Function>(GV);
  4734. static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
  4735. Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
  4736. if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) {
  4737. Fn->addFnAttr("sign-return-address-key",
  4738. BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey
  4739. ? "a_key"
  4740. : "b_key");
  4741. }
  4742. Fn->addFnAttr("branch-target-enforcement",
  4743. BPI.BranchTargetEnforcement ? "true" : "false");
  4744. }
  4745. bool isScalarizableAsmOperand(CodeGen::CodeGenFunction &CGF,
  4746. llvm::Type *Ty) const override {
  4747. if (CGF.getTarget().hasFeature("ls64")) {
  4748. auto *ST = dyn_cast<llvm::StructType>(Ty);
  4749. if (ST && ST->getNumElements() == 1) {
  4750. auto *AT = dyn_cast<llvm::ArrayType>(ST->getElementType(0));
  4751. if (AT && AT->getNumElements() == 8 &&
  4752. AT->getElementType()->isIntegerTy(64))
  4753. return true;
  4754. }
  4755. }
  4756. return TargetCodeGenInfo::isScalarizableAsmOperand(CGF, Ty);
  4757. }
  4758. };
  4759. class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
  4760. public:
  4761. WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
  4762. : AArch64TargetCodeGenInfo(CGT, K) {}
  4763. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  4764. CodeGen::CodeGenModule &CGM) const override;
  4765. void getDependentLibraryOption(llvm::StringRef Lib,
  4766. llvm::SmallString<24> &Opt) const override {
  4767. Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
  4768. }
  4769. void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
  4770. llvm::SmallString<32> &Opt) const override {
  4771. Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
  4772. }
  4773. };
  4774. void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
  4775. const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
  4776. AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
  4777. if (GV->isDeclaration())
  4778. return;
  4779. addStackProbeTargetAttributes(D, GV, CGM);
  4780. }
  4781. }
  4782. ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const {
  4783. assert(Ty->isVectorType() && "expected vector type!");
  4784. const auto *VT = Ty->castAs<VectorType>();
  4785. if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
  4786. assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
  4787. assert(VT->getElementType()->castAs<BuiltinType>()->getKind() ==
  4788. BuiltinType::UChar &&
  4789. "unexpected builtin type for SVE predicate!");
  4790. return ABIArgInfo::getDirect(llvm::ScalableVectorType::get(
  4791. llvm::Type::getInt1Ty(getVMContext()), 16));
  4792. }
  4793. if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) {
  4794. assert(VT->getElementType()->isBuiltinType() && "expected builtin type!");
  4795. const auto *BT = VT->getElementType()->castAs<BuiltinType>();
  4796. llvm::ScalableVectorType *ResType = nullptr;
  4797. switch (BT->getKind()) {
  4798. default:
  4799. llvm_unreachable("unexpected builtin type for SVE vector!");
  4800. case BuiltinType::SChar:
  4801. case BuiltinType::UChar:
  4802. ResType = llvm::ScalableVectorType::get(
  4803. llvm::Type::getInt8Ty(getVMContext()), 16);
  4804. break;
  4805. case BuiltinType::Short:
  4806. case BuiltinType::UShort:
  4807. ResType = llvm::ScalableVectorType::get(
  4808. llvm::Type::getInt16Ty(getVMContext()), 8);
  4809. break;
  4810. case BuiltinType::Int:
  4811. case BuiltinType::UInt:
  4812. ResType = llvm::ScalableVectorType::get(
  4813. llvm::Type::getInt32Ty(getVMContext()), 4);
  4814. break;
  4815. case BuiltinType::Long:
  4816. case BuiltinType::ULong:
  4817. ResType = llvm::ScalableVectorType::get(
  4818. llvm::Type::getInt64Ty(getVMContext()), 2);
  4819. break;
  4820. case BuiltinType::Half:
  4821. ResType = llvm::ScalableVectorType::get(
  4822. llvm::Type::getHalfTy(getVMContext()), 8);
  4823. break;
  4824. case BuiltinType::Float:
  4825. ResType = llvm::ScalableVectorType::get(
  4826. llvm::Type::getFloatTy(getVMContext()), 4);
  4827. break;
  4828. case BuiltinType::Double:
  4829. ResType = llvm::ScalableVectorType::get(
  4830. llvm::Type::getDoubleTy(getVMContext()), 2);
  4831. break;
  4832. case BuiltinType::BFloat16:
  4833. ResType = llvm::ScalableVectorType::get(
  4834. llvm::Type::getBFloatTy(getVMContext()), 8);
  4835. break;
  4836. }
  4837. return ABIArgInfo::getDirect(ResType);
  4838. }
  4839. uint64_t Size = getContext().getTypeSize(Ty);
  4840. // Android promotes <2 x i8> to i16, not i32
  4841. if (isAndroid() && (Size <= 16)) {
  4842. llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
  4843. return ABIArgInfo::getDirect(ResType);
  4844. }
  4845. if (Size <= 32) {
  4846. llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
  4847. return ABIArgInfo::getDirect(ResType);
  4848. }
  4849. if (Size == 64) {
  4850. auto *ResType =
  4851. llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
  4852. return ABIArgInfo::getDirect(ResType);
  4853. }
  4854. if (Size == 128) {
  4855. auto *ResType =
  4856. llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
  4857. return ABIArgInfo::getDirect(ResType);
  4858. }
  4859. return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
  4860. }
  4861. ABIArgInfo
  4862. AArch64ABIInfo::classifyArgumentType(QualType Ty, bool IsVariadic,
  4863. unsigned CallingConvention) const {
  4864. Ty = useFirstFieldIfTransparentUnion(Ty);
  4865. // Handle illegal vector types here.
  4866. if (isIllegalVectorType(Ty))
  4867. return coerceIllegalVector(Ty);
  4868. if (!isAggregateTypeForABI(Ty)) {
  4869. // Treat an enum type as its underlying type.
  4870. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  4871. Ty = EnumTy->getDecl()->getIntegerType();
  4872. if (const auto *EIT = Ty->getAs<BitIntType>())
  4873. if (EIT->getNumBits() > 128)
  4874. return getNaturalAlignIndirect(Ty);
  4875. return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS()
  4876. ? ABIArgInfo::getExtend(Ty)
  4877. : ABIArgInfo::getDirect());
  4878. }
  4879. // Structures with either a non-trivial destructor or a non-trivial
  4880. // copy constructor are always indirect.
  4881. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
  4882. return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
  4883. CGCXXABI::RAA_DirectInMemory);
  4884. }
  4885. // Empty records are always ignored on Darwin, but actually passed in C++ mode
  4886. // elsewhere for GNU compatibility.
  4887. uint64_t Size = getContext().getTypeSize(Ty);
  4888. bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
  4889. if (IsEmpty || Size == 0) {
  4890. if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
  4891. return ABIArgInfo::getIgnore();
  4892. // GNU C mode. The only argument that gets ignored is an empty one with size
  4893. // 0.
  4894. if (IsEmpty && Size == 0)
  4895. return ABIArgInfo::getIgnore();
  4896. return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
  4897. }
  4898. // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
  4899. const Type *Base = nullptr;
  4900. uint64_t Members = 0;
  4901. bool IsWin64 = Kind == Win64 || CallingConvention == llvm::CallingConv::Win64;
  4902. bool IsWinVariadic = IsWin64 && IsVariadic;
  4903. // In variadic functions on Windows, all composite types are treated alike,
  4904. // no special handling of HFAs/HVAs.
  4905. if (!IsWinVariadic && isHomogeneousAggregate(Ty, Base, Members)) {
  4906. if (Kind != AArch64ABIInfo::AAPCS)
  4907. return ABIArgInfo::getDirect(
  4908. llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
  4909. // For alignment adjusted HFAs, cap the argument alignment to 16, leave it
  4910. // default otherwise.
  4911. unsigned Align =
  4912. getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
  4913. unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity();
  4914. Align = (Align > BaseAlign && Align >= 16) ? 16 : 0;
  4915. return ABIArgInfo::getDirect(
  4916. llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members), 0,
  4917. nullptr, true, Align);
  4918. }
  4919. // Aggregates <= 16 bytes are passed directly in registers or on the stack.
  4920. if (Size <= 128) {
  4921. // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
  4922. // same size and alignment.
  4923. if (getTarget().isRenderScriptTarget()) {
  4924. return coerceToIntArray(Ty, getContext(), getVMContext());
  4925. }
  4926. unsigned Alignment;
  4927. if (Kind == AArch64ABIInfo::AAPCS) {
  4928. Alignment = getContext().getTypeUnadjustedAlign(Ty);
  4929. Alignment = Alignment < 128 ? 64 : 128;
  4930. } else {
  4931. Alignment = std::max(getContext().getTypeAlign(Ty),
  4932. (unsigned)getTarget().getPointerWidth(0));
  4933. }
  4934. Size = llvm::alignTo(Size, Alignment);
  4935. // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
  4936. // For aggregates with 16-byte alignment, we use i128.
  4937. llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
  4938. return ABIArgInfo::getDirect(
  4939. Size == Alignment ? BaseTy
  4940. : llvm::ArrayType::get(BaseTy, Size / Alignment));
  4941. }
  4942. return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
  4943. }
  4944. ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
  4945. bool IsVariadic) const {
  4946. if (RetTy->isVoidType())
  4947. return ABIArgInfo::getIgnore();
  4948. if (const auto *VT = RetTy->getAs<VectorType>()) {
  4949. if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
  4950. VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
  4951. return coerceIllegalVector(RetTy);
  4952. }
  4953. // Large vector types should be returned via memory.
  4954. if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
  4955. return getNaturalAlignIndirect(RetTy);
  4956. if (!isAggregateTypeForABI(RetTy)) {
  4957. // Treat an enum type as its underlying type.
  4958. if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
  4959. RetTy = EnumTy->getDecl()->getIntegerType();
  4960. if (const auto *EIT = RetTy->getAs<BitIntType>())
  4961. if (EIT->getNumBits() > 128)
  4962. return getNaturalAlignIndirect(RetTy);
  4963. return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS()
  4964. ? ABIArgInfo::getExtend(RetTy)
  4965. : ABIArgInfo::getDirect());
  4966. }
  4967. uint64_t Size = getContext().getTypeSize(RetTy);
  4968. if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
  4969. return ABIArgInfo::getIgnore();
  4970. const Type *Base = nullptr;
  4971. uint64_t Members = 0;
  4972. if (isHomogeneousAggregate(RetTy, Base, Members) &&
  4973. !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
  4974. IsVariadic))
  4975. // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
  4976. return ABIArgInfo::getDirect();
  4977. // Aggregates <= 16 bytes are returned directly in registers or on the stack.
  4978. if (Size <= 128) {
  4979. // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
  4980. // same size and alignment.
  4981. if (getTarget().isRenderScriptTarget()) {
  4982. return coerceToIntArray(RetTy, getContext(), getVMContext());
  4983. }
  4984. if (Size <= 64 && getDataLayout().isLittleEndian()) {
  4985. // Composite types are returned in lower bits of a 64-bit register for LE,
  4986. // and in higher bits for BE. However, integer types are always returned
  4987. // in lower bits for both LE and BE, and they are not rounded up to
  4988. // 64-bits. We can skip rounding up of composite types for LE, but not for
  4989. // BE, otherwise composite types will be indistinguishable from integer
  4990. // types.
  4991. return ABIArgInfo::getDirect(
  4992. llvm::IntegerType::get(getVMContext(), Size));
  4993. }
  4994. unsigned Alignment = getContext().getTypeAlign(RetTy);
  4995. Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
  4996. // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
  4997. // For aggregates with 16-byte alignment, we use i128.
  4998. if (Alignment < 128 && Size == 128) {
  4999. llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
  5000. return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
  5001. }
  5002. return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
  5003. }
  5004. return getNaturalAlignIndirect(RetTy);
  5005. }
  5006. /// isIllegalVectorType - check whether the vector type is legal for AArch64.
  5007. bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
  5008. if (const VectorType *VT = Ty->getAs<VectorType>()) {
  5009. // Check whether VT is a fixed-length SVE vector. These types are
  5010. // represented as scalable vectors in function args/return and must be
  5011. // coerced from fixed vectors.
  5012. if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector ||
  5013. VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
  5014. return true;
  5015. // Check whether VT is legal.
  5016. unsigned NumElements = VT->getNumElements();
  5017. uint64_t Size = getContext().getTypeSize(VT);
  5018. // NumElements should be power of 2.
  5019. if (!llvm::isPowerOf2_32(NumElements))
  5020. return true;
  5021. // arm64_32 has to be compatible with the ARM logic here, which allows huge
  5022. // vectors for some reason.
  5023. llvm::Triple Triple = getTarget().getTriple();
  5024. if (Triple.getArch() == llvm::Triple::aarch64_32 &&
  5025. Triple.isOSBinFormatMachO())
  5026. return Size <= 32;
  5027. return Size != 64 && (Size != 128 || NumElements == 1);
  5028. }
  5029. return false;
  5030. }
  5031. bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
  5032. llvm::Type *eltTy,
  5033. unsigned elts) const {
  5034. if (!llvm::isPowerOf2_32(elts))
  5035. return false;
  5036. if (totalSize.getQuantity() != 8 &&
  5037. (totalSize.getQuantity() != 16 || elts == 1))
  5038. return false;
  5039. return true;
  5040. }
  5041. bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
  5042. // Homogeneous aggregates for AAPCS64 must have base types of a floating
  5043. // point type or a short-vector type. This is the same as the 32-bit ABI,
  5044. // but with the difference that any floating-point type is allowed,
  5045. // including __fp16.
  5046. if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
  5047. if (BT->isFloatingPoint())
  5048. return true;
  5049. } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
  5050. unsigned VecSize = getContext().getTypeSize(VT);
  5051. if (VecSize == 64 || VecSize == 128)
  5052. return true;
  5053. }
  5054. return false;
  5055. }
  5056. bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
  5057. uint64_t Members) const {
  5058. return Members <= 4;
  5059. }
  5060. Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
  5061. CodeGenFunction &CGF) const {
  5062. ABIArgInfo AI = classifyArgumentType(Ty, /*IsVariadic=*/true,
  5063. CGF.CurFnInfo->getCallingConvention());
  5064. bool IsIndirect = AI.isIndirect();
  5065. llvm::Type *BaseTy = CGF.ConvertType(Ty);
  5066. if (IsIndirect)
  5067. BaseTy = llvm::PointerType::getUnqual(BaseTy);
  5068. else if (AI.getCoerceToType())
  5069. BaseTy = AI.getCoerceToType();
  5070. unsigned NumRegs = 1;
  5071. if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
  5072. BaseTy = ArrTy->getElementType();
  5073. NumRegs = ArrTy->getNumElements();
  5074. }
  5075. bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
  5076. // The AArch64 va_list type and handling is specified in the Procedure Call
  5077. // Standard, section B.4:
  5078. //
  5079. // struct {
  5080. // void *__stack;
  5081. // void *__gr_top;
  5082. // void *__vr_top;
  5083. // int __gr_offs;
  5084. // int __vr_offs;
  5085. // };
  5086. llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
  5087. llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
  5088. llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
  5089. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
  5090. CharUnits TySize = getContext().getTypeSizeInChars(Ty);
  5091. CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
  5092. Address reg_offs_p = Address::invalid();
  5093. llvm::Value *reg_offs = nullptr;
  5094. int reg_top_index;
  5095. int RegSize = IsIndirect ? 8 : TySize.getQuantity();
  5096. if (!IsFPR) {
  5097. // 3 is the field number of __gr_offs
  5098. reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
  5099. reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
  5100. reg_top_index = 1; // field number for __gr_top
  5101. RegSize = llvm::alignTo(RegSize, 8);
  5102. } else {
  5103. // 4 is the field number of __vr_offs.
  5104. reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
  5105. reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
  5106. reg_top_index = 2; // field number for __vr_top
  5107. RegSize = 16 * NumRegs;
  5108. }
  5109. //=======================================
  5110. // Find out where argument was passed
  5111. //=======================================
  5112. // If reg_offs >= 0 we're already using the stack for this type of
  5113. // argument. We don't want to keep updating reg_offs (in case it overflows,
  5114. // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
  5115. // whatever they get).
  5116. llvm::Value *UsingStack = nullptr;
  5117. UsingStack = CGF.Builder.CreateICmpSGE(
  5118. reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
  5119. CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
  5120. // Otherwise, at least some kind of argument could go in these registers, the
  5121. // question is whether this particular type is too big.
  5122. CGF.EmitBlock(MaybeRegBlock);
  5123. // Integer arguments may need to correct register alignment (for example a
  5124. // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
  5125. // align __gr_offs to calculate the potential address.
  5126. if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
  5127. int Align = TyAlign.getQuantity();
  5128. reg_offs = CGF.Builder.CreateAdd(
  5129. reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
  5130. "align_regoffs");
  5131. reg_offs = CGF.Builder.CreateAnd(
  5132. reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
  5133. "aligned_regoffs");
  5134. }
  5135. // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
  5136. // The fact that this is done unconditionally reflects the fact that
  5137. // allocating an argument to the stack also uses up all the remaining
  5138. // registers of the appropriate kind.
  5139. llvm::Value *NewOffset = nullptr;
  5140. NewOffset = CGF.Builder.CreateAdd(
  5141. reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
  5142. CGF.Builder.CreateStore(NewOffset, reg_offs_p);
  5143. // Now we're in a position to decide whether this argument really was in
  5144. // registers or not.
  5145. llvm::Value *InRegs = nullptr;
  5146. InRegs = CGF.Builder.CreateICmpSLE(
  5147. NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
  5148. CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
  5149. //=======================================
  5150. // Argument was in registers
  5151. //=======================================
  5152. // Now we emit the code for if the argument was originally passed in
  5153. // registers. First start the appropriate block:
  5154. CGF.EmitBlock(InRegBlock);
  5155. llvm::Value *reg_top = nullptr;
  5156. Address reg_top_p =
  5157. CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
  5158. reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
  5159. Address BaseAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, reg_top, reg_offs),
  5160. CharUnits::fromQuantity(IsFPR ? 16 : 8));
  5161. Address RegAddr = Address::invalid();
  5162. llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
  5163. if (IsIndirect) {
  5164. // If it's been passed indirectly (actually a struct), whatever we find from
  5165. // stored registers or on the stack will actually be a struct **.
  5166. MemTy = llvm::PointerType::getUnqual(MemTy);
  5167. }
  5168. const Type *Base = nullptr;
  5169. uint64_t NumMembers = 0;
  5170. bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
  5171. if (IsHFA && NumMembers > 1) {
  5172. // Homogeneous aggregates passed in registers will have their elements split
  5173. // and stored 16-bytes apart regardless of size (they're notionally in qN,
  5174. // qN+1, ...). We reload and store into a temporary local variable
  5175. // contiguously.
  5176. assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
  5177. auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
  5178. llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
  5179. llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
  5180. Address Tmp = CGF.CreateTempAlloca(HFATy,
  5181. std::max(TyAlign, BaseTyInfo.Align));
  5182. // On big-endian platforms, the value will be right-aligned in its slot.
  5183. int Offset = 0;
  5184. if (CGF.CGM.getDataLayout().isBigEndian() &&
  5185. BaseTyInfo.Width.getQuantity() < 16)
  5186. Offset = 16 - BaseTyInfo.Width.getQuantity();
  5187. for (unsigned i = 0; i < NumMembers; ++i) {
  5188. CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
  5189. Address LoadAddr =
  5190. CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
  5191. LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
  5192. Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
  5193. llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
  5194. CGF.Builder.CreateStore(Elem, StoreAddr);
  5195. }
  5196. RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
  5197. } else {
  5198. // Otherwise the object is contiguous in memory.
  5199. // It might be right-aligned in its slot.
  5200. CharUnits SlotSize = BaseAddr.getAlignment();
  5201. if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
  5202. (IsHFA || !isAggregateTypeForABI(Ty)) &&
  5203. TySize < SlotSize) {
  5204. CharUnits Offset = SlotSize - TySize;
  5205. BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
  5206. }
  5207. RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
  5208. }
  5209. CGF.EmitBranch(ContBlock);
  5210. //=======================================
  5211. // Argument was on the stack
  5212. //=======================================
  5213. CGF.EmitBlock(OnStackBlock);
  5214. Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
  5215. llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
  5216. // Again, stack arguments may need realignment. In this case both integer and
  5217. // floating-point ones might be affected.
  5218. if (!IsIndirect && TyAlign.getQuantity() > 8) {
  5219. int Align = TyAlign.getQuantity();
  5220. OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
  5221. OnStackPtr = CGF.Builder.CreateAdd(
  5222. OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
  5223. "align_stack");
  5224. OnStackPtr = CGF.Builder.CreateAnd(
  5225. OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
  5226. "align_stack");
  5227. OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
  5228. }
  5229. Address OnStackAddr(OnStackPtr,
  5230. std::max(CharUnits::fromQuantity(8), TyAlign));
  5231. // All stack slots are multiples of 8 bytes.
  5232. CharUnits StackSlotSize = CharUnits::fromQuantity(8);
  5233. CharUnits StackSize;
  5234. if (IsIndirect)
  5235. StackSize = StackSlotSize;
  5236. else
  5237. StackSize = TySize.alignTo(StackSlotSize);
  5238. llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
  5239. llvm::Value *NewStack = CGF.Builder.CreateInBoundsGEP(
  5240. CGF.Int8Ty, OnStackPtr, StackSizeC, "new_stack");
  5241. // Write the new value of __stack for the next call to va_arg
  5242. CGF.Builder.CreateStore(NewStack, stack_p);
  5243. if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
  5244. TySize < StackSlotSize) {
  5245. CharUnits Offset = StackSlotSize - TySize;
  5246. OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
  5247. }
  5248. OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
  5249. CGF.EmitBranch(ContBlock);
  5250. //=======================================
  5251. // Tidy up
  5252. //=======================================
  5253. CGF.EmitBlock(ContBlock);
  5254. Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
  5255. OnStackAddr, OnStackBlock, "vaargs.addr");
  5256. if (IsIndirect)
  5257. return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
  5258. TyAlign);
  5259. return ResAddr;
  5260. }
  5261. Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
  5262. CodeGenFunction &CGF) const {
  5263. // The backend's lowering doesn't support va_arg for aggregates or
  5264. // illegal vector types. Lower VAArg here for these cases and use
  5265. // the LLVM va_arg instruction for everything else.
  5266. if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
  5267. return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
  5268. uint64_t PointerSize = getTarget().getPointerWidth(0) / 8;
  5269. CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
  5270. // Empty records are ignored for parameter passing purposes.
  5271. if (isEmptyRecord(getContext(), Ty, true)) {
  5272. Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
  5273. Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
  5274. return Addr;
  5275. }
  5276. // The size of the actual thing passed, which might end up just
  5277. // being a pointer for indirect types.
  5278. auto TyInfo = getContext().getTypeInfoInChars(Ty);
  5279. // Arguments bigger than 16 bytes which aren't homogeneous
  5280. // aggregates should be passed indirectly.
  5281. bool IsIndirect = false;
  5282. if (TyInfo.Width.getQuantity() > 16) {
  5283. const Type *Base = nullptr;
  5284. uint64_t Members = 0;
  5285. IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
  5286. }
  5287. return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
  5288. TyInfo, SlotSize, /*AllowHigherAlign*/ true);
  5289. }
  5290. Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
  5291. QualType Ty) const {
  5292. bool IsIndirect = false;
  5293. // Composites larger than 16 bytes are passed by reference.
  5294. if (isAggregateTypeForABI(Ty) && getContext().getTypeSize(Ty) > 128)
  5295. IsIndirect = true;
  5296. return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
  5297. CGF.getContext().getTypeInfoInChars(Ty),
  5298. CharUnits::fromQuantity(8),
  5299. /*allowHigherAlign*/ false);
  5300. }
  5301. //===----------------------------------------------------------------------===//
  5302. // ARM ABI Implementation
  5303. //===----------------------------------------------------------------------===//
  5304. namespace {
  5305. class ARMABIInfo : public SwiftABIInfo {
  5306. public:
  5307. enum ABIKind {
  5308. APCS = 0,
  5309. AAPCS = 1,
  5310. AAPCS_VFP = 2,
  5311. AAPCS16_VFP = 3,
  5312. };
  5313. private:
  5314. ABIKind Kind;
  5315. bool IsFloatABISoftFP;
  5316. public:
  5317. ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
  5318. : SwiftABIInfo(CGT), Kind(_Kind) {
  5319. setCCs();
  5320. IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" ||
  5321. CGT.getCodeGenOpts().FloatABI == ""; // default
  5322. }
  5323. bool isEABI() const {
  5324. switch (getTarget().getTriple().getEnvironment()) {
  5325. case llvm::Triple::Android:
  5326. case llvm::Triple::EABI:
  5327. case llvm::Triple::EABIHF:
  5328. case llvm::Triple::GNUEABI:
  5329. case llvm::Triple::GNUEABIHF:
  5330. case llvm::Triple::MuslEABI:
  5331. case llvm::Triple::MuslEABIHF:
  5332. return true;
  5333. default:
  5334. return false;
  5335. }
  5336. }
  5337. bool isEABIHF() const {
  5338. switch (getTarget().getTriple().getEnvironment()) {
  5339. case llvm::Triple::EABIHF:
  5340. case llvm::Triple::GNUEABIHF:
  5341. case llvm::Triple::MuslEABIHF:
  5342. return true;
  5343. default:
  5344. return false;
  5345. }
  5346. }
  5347. ABIKind getABIKind() const { return Kind; }
  5348. bool allowBFloatArgsAndRet() const override {
  5349. return !IsFloatABISoftFP && getTarget().hasBFloat16Type();
  5350. }
  5351. private:
  5352. ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
  5353. unsigned functionCallConv) const;
  5354. ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
  5355. unsigned functionCallConv) const;
  5356. ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
  5357. uint64_t Members) const;
  5358. ABIArgInfo coerceIllegalVector(QualType Ty) const;
  5359. bool isIllegalVectorType(QualType Ty) const;
  5360. bool containsAnyFP16Vectors(QualType Ty) const;
  5361. bool isHomogeneousAggregateBaseType(QualType Ty) const override;
  5362. bool isHomogeneousAggregateSmallEnough(const Type *Ty,
  5363. uint64_t Members) const override;
  5364. bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
  5365. void computeInfo(CGFunctionInfo &FI) const override;
  5366. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  5367. QualType Ty) const override;
  5368. llvm::CallingConv::ID getLLVMDefaultCC() const;
  5369. llvm::CallingConv::ID getABIDefaultCC() const;
  5370. void setCCs();
  5371. bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
  5372. bool asReturnValue) const override {
  5373. return occupiesMoreThan(CGT, scalars, /*total*/ 4);
  5374. }
  5375. bool isSwiftErrorInRegister() const override {
  5376. return true;
  5377. }
  5378. bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
  5379. unsigned elts) const override;
  5380. };
  5381. class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
  5382. public:
  5383. ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
  5384. : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {}
  5385. const ARMABIInfo &getABIInfo() const {
  5386. return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
  5387. }
  5388. int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
  5389. return 13;
  5390. }
  5391. StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
  5392. return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
  5393. }
  5394. bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  5395. llvm::Value *Address) const override {
  5396. llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
  5397. // 0-15 are the 16 integer registers.
  5398. AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
  5399. return false;
  5400. }
  5401. unsigned getSizeOfUnwindException() const override {
  5402. if (getABIInfo().isEABI()) return 88;
  5403. return TargetCodeGenInfo::getSizeOfUnwindException();
  5404. }
  5405. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  5406. CodeGen::CodeGenModule &CGM) const override {
  5407. if (GV->isDeclaration())
  5408. return;
  5409. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
  5410. if (!FD)
  5411. return;
  5412. auto *Fn = cast<llvm::Function>(GV);
  5413. if (const auto *TA = FD->getAttr<TargetAttr>()) {
  5414. ParsedTargetAttr Attr = TA->parse();
  5415. if (!Attr.BranchProtection.empty()) {
  5416. TargetInfo::BranchProtectionInfo BPI;
  5417. StringRef DiagMsg;
  5418. StringRef Arch = Attr.Architecture.empty()
  5419. ? CGM.getTarget().getTargetOpts().CPU
  5420. : Attr.Architecture;
  5421. if (!CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
  5422. Arch, BPI, DiagMsg)) {
  5423. CGM.getDiags().Report(
  5424. D->getLocation(),
  5425. diag::warn_target_unsupported_branch_protection_attribute)
  5426. << Arch;
  5427. } else {
  5428. static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"};
  5429. assert(static_cast<unsigned>(BPI.SignReturnAddr) <= 2 &&
  5430. "Unexpected SignReturnAddressScopeKind");
  5431. Fn->addFnAttr(
  5432. "sign-return-address",
  5433. SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]);
  5434. Fn->addFnAttr("branch-target-enforcement",
  5435. BPI.BranchTargetEnforcement ? "true" : "false");
  5436. }
  5437. } else if (CGM.getLangOpts().BranchTargetEnforcement ||
  5438. CGM.getLangOpts().hasSignReturnAddress()) {
  5439. // If the Branch Protection attribute is missing, validate the target
  5440. // Architecture attribute against Branch Protection command line
  5441. // settings.
  5442. if (!CGM.getTarget().isBranchProtectionSupportedArch(Attr.Architecture))
  5443. CGM.getDiags().Report(
  5444. D->getLocation(),
  5445. diag::warn_target_unsupported_branch_protection_attribute)
  5446. << Attr.Architecture;
  5447. }
  5448. }
  5449. const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
  5450. if (!Attr)
  5451. return;
  5452. const char *Kind;
  5453. switch (Attr->getInterrupt()) {
  5454. case ARMInterruptAttr::Generic: Kind = ""; break;
  5455. case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
  5456. case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
  5457. case ARMInterruptAttr::SWI: Kind = "SWI"; break;
  5458. case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
  5459. case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
  5460. }
  5461. Fn->addFnAttr("interrupt", Kind);
  5462. ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
  5463. if (ABI == ARMABIInfo::APCS)
  5464. return;
  5465. // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
  5466. // however this is not necessarily true on taking any interrupt. Instruct
  5467. // the backend to perform a realignment as part of the function prologue.
  5468. llvm::AttrBuilder B(Fn->getContext());
  5469. B.addStackAlignmentAttr(8);
  5470. Fn->addFnAttrs(B);
  5471. }
  5472. };
  5473. class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
  5474. public:
  5475. WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
  5476. : ARMTargetCodeGenInfo(CGT, K) {}
  5477. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  5478. CodeGen::CodeGenModule &CGM) const override;
  5479. void getDependentLibraryOption(llvm::StringRef Lib,
  5480. llvm::SmallString<24> &Opt) const override {
  5481. Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
  5482. }
  5483. void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
  5484. llvm::SmallString<32> &Opt) const override {
  5485. Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
  5486. }
  5487. };
  5488. void WindowsARMTargetCodeGenInfo::setTargetAttributes(
  5489. const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
  5490. ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
  5491. if (GV->isDeclaration())
  5492. return;
  5493. addStackProbeTargetAttributes(D, GV, CGM);
  5494. }
  5495. }
  5496. void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
  5497. if (!::classifyReturnType(getCXXABI(), FI, *this))
  5498. FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
  5499. FI.getCallingConvention());
  5500. for (auto &I : FI.arguments())
  5501. I.info = classifyArgumentType(I.type, FI.isVariadic(),
  5502. FI.getCallingConvention());
  5503. // Always honor user-specified calling convention.
  5504. if (FI.getCallingConvention() != llvm::CallingConv::C)
  5505. return;
  5506. llvm::CallingConv::ID cc = getRuntimeCC();
  5507. if (cc != llvm::CallingConv::C)
  5508. FI.setEffectiveCallingConvention(cc);
  5509. }
  5510. /// Return the default calling convention that LLVM will use.
  5511. llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
  5512. // The default calling convention that LLVM will infer.
  5513. if (isEABIHF() || getTarget().getTriple().isWatchABI())
  5514. return llvm::CallingConv::ARM_AAPCS_VFP;
  5515. else if (isEABI())
  5516. return llvm::CallingConv::ARM_AAPCS;
  5517. else
  5518. return llvm::CallingConv::ARM_APCS;
  5519. }
  5520. /// Return the calling convention that our ABI would like us to use
  5521. /// as the C calling convention.
  5522. llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
  5523. switch (getABIKind()) {
  5524. case APCS: return llvm::CallingConv::ARM_APCS;
  5525. case AAPCS: return llvm::CallingConv::ARM_AAPCS;
  5526. case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
  5527. case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
  5528. }
  5529. llvm_unreachable("bad ABI kind");
  5530. }
  5531. void ARMABIInfo::setCCs() {
  5532. assert(getRuntimeCC() == llvm::CallingConv::C);
  5533. // Don't muddy up the IR with a ton of explicit annotations if
  5534. // they'd just match what LLVM will infer from the triple.
  5535. llvm::CallingConv::ID abiCC = getABIDefaultCC();
  5536. if (abiCC != getLLVMDefaultCC())
  5537. RuntimeCC = abiCC;
  5538. }
  5539. ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
  5540. uint64_t Size = getContext().getTypeSize(Ty);
  5541. if (Size <= 32) {
  5542. llvm::Type *ResType =
  5543. llvm::Type::getInt32Ty(getVMContext());
  5544. return ABIArgInfo::getDirect(ResType);
  5545. }
  5546. if (Size == 64 || Size == 128) {
  5547. auto *ResType = llvm::FixedVectorType::get(
  5548. llvm::Type::getInt32Ty(getVMContext()), Size / 32);
  5549. return ABIArgInfo::getDirect(ResType);
  5550. }
  5551. return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
  5552. }
  5553. ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
  5554. const Type *Base,
  5555. uint64_t Members) const {
  5556. assert(Base && "Base class should be set for homogeneous aggregate");
  5557. // Base can be a floating-point or a vector.
  5558. if (const VectorType *VT = Base->getAs<VectorType>()) {
  5559. // FP16 vectors should be converted to integer vectors
  5560. if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
  5561. uint64_t Size = getContext().getTypeSize(VT);
  5562. auto *NewVecTy = llvm::FixedVectorType::get(
  5563. llvm::Type::getInt32Ty(getVMContext()), Size / 32);
  5564. llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
  5565. return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
  5566. }
  5567. }
  5568. unsigned Align = 0;
  5569. if (getABIKind() == ARMABIInfo::AAPCS ||
  5570. getABIKind() == ARMABIInfo::AAPCS_VFP) {
  5571. // For alignment adjusted HFAs, cap the argument alignment to 8, leave it
  5572. // default otherwise.
  5573. Align = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
  5574. unsigned BaseAlign = getContext().getTypeAlignInChars(Base).getQuantity();
  5575. Align = (Align > BaseAlign && Align >= 8) ? 8 : 0;
  5576. }
  5577. return ABIArgInfo::getDirect(nullptr, 0, nullptr, false, Align);
  5578. }
  5579. ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
  5580. unsigned functionCallConv) const {
  5581. // 6.1.2.1 The following argument types are VFP CPRCs:
  5582. // A single-precision floating-point type (including promoted
  5583. // half-precision types); A double-precision floating-point type;
  5584. // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
  5585. // with a Base Type of a single- or double-precision floating-point type,
  5586. // 64-bit containerized vectors or 128-bit containerized vectors with one
  5587. // to four Elements.
  5588. // Variadic functions should always marshal to the base standard.
  5589. bool IsAAPCS_VFP =
  5590. !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
  5591. Ty = useFirstFieldIfTransparentUnion(Ty);
  5592. // Handle illegal vector types here.
  5593. if (isIllegalVectorType(Ty))
  5594. return coerceIllegalVector(Ty);
  5595. if (!isAggregateTypeForABI(Ty)) {
  5596. // Treat an enum type as its underlying type.
  5597. if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
  5598. Ty = EnumTy->getDecl()->getIntegerType();
  5599. }
  5600. if (const auto *EIT = Ty->getAs<BitIntType>())
  5601. if (EIT->getNumBits() > 64)
  5602. return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
  5603. return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
  5604. : ABIArgInfo::getDirect());
  5605. }
  5606. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
  5607. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  5608. }
  5609. // Ignore empty records.
  5610. if (isEmptyRecord(getContext(), Ty, true))
  5611. return ABIArgInfo::getIgnore();
  5612. if (IsAAPCS_VFP) {
  5613. // Homogeneous Aggregates need to be expanded when we can fit the aggregate
  5614. // into VFP registers.
  5615. const Type *Base = nullptr;
  5616. uint64_t Members = 0;
  5617. if (isHomogeneousAggregate(Ty, Base, Members))
  5618. return classifyHomogeneousAggregate(Ty, Base, Members);
  5619. } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
  5620. // WatchOS does have homogeneous aggregates. Note that we intentionally use
  5621. // this convention even for a variadic function: the backend will use GPRs
  5622. // if needed.
  5623. const Type *Base = nullptr;
  5624. uint64_t Members = 0;
  5625. if (isHomogeneousAggregate(Ty, Base, Members)) {
  5626. assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
  5627. llvm::Type *Ty =
  5628. llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
  5629. return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
  5630. }
  5631. }
  5632. if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
  5633. getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
  5634. // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
  5635. // bigger than 128-bits, they get placed in space allocated by the caller,
  5636. // and a pointer is passed.
  5637. return ABIArgInfo::getIndirect(
  5638. CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
  5639. }
  5640. // Support byval for ARM.
  5641. // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
  5642. // most 8-byte. We realign the indirect argument if type alignment is bigger
  5643. // than ABI alignment.
  5644. uint64_t ABIAlign = 4;
  5645. uint64_t TyAlign;
  5646. if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
  5647. getABIKind() == ARMABIInfo::AAPCS) {
  5648. TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
  5649. ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
  5650. } else {
  5651. TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
  5652. }
  5653. if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
  5654. assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
  5655. return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
  5656. /*ByVal=*/true,
  5657. /*Realign=*/TyAlign > ABIAlign);
  5658. }
  5659. // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
  5660. // same size and alignment.
  5661. if (getTarget().isRenderScriptTarget()) {
  5662. return coerceToIntArray(Ty, getContext(), getVMContext());
  5663. }
  5664. // Otherwise, pass by coercing to a structure of the appropriate size.
  5665. llvm::Type* ElemTy;
  5666. unsigned SizeRegs;
  5667. // FIXME: Try to match the types of the arguments more accurately where
  5668. // we can.
  5669. if (TyAlign <= 4) {
  5670. ElemTy = llvm::Type::getInt32Ty(getVMContext());
  5671. SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
  5672. } else {
  5673. ElemTy = llvm::Type::getInt64Ty(getVMContext());
  5674. SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
  5675. }
  5676. return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
  5677. }
  5678. static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
  5679. llvm::LLVMContext &VMContext) {
  5680. // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
  5681. // is called integer-like if its size is less than or equal to one word, and
  5682. // the offset of each of its addressable sub-fields is zero.
  5683. uint64_t Size = Context.getTypeSize(Ty);
  5684. // Check that the type fits in a word.
  5685. if (Size > 32)
  5686. return false;
  5687. // FIXME: Handle vector types!
  5688. if (Ty->isVectorType())
  5689. return false;
  5690. // Float types are never treated as "integer like".
  5691. if (Ty->isRealFloatingType())
  5692. return false;
  5693. // If this is a builtin or pointer type then it is ok.
  5694. if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
  5695. return true;
  5696. // Small complex integer types are "integer like".
  5697. if (const ComplexType *CT = Ty->getAs<ComplexType>())
  5698. return isIntegerLikeType(CT->getElementType(), Context, VMContext);
  5699. // Single element and zero sized arrays should be allowed, by the definition
  5700. // above, but they are not.
  5701. // Otherwise, it must be a record type.
  5702. const RecordType *RT = Ty->getAs<RecordType>();
  5703. if (!RT) return false;
  5704. // Ignore records with flexible arrays.
  5705. const RecordDecl *RD = RT->getDecl();
  5706. if (RD->hasFlexibleArrayMember())
  5707. return false;
  5708. // Check that all sub-fields are at offset 0, and are themselves "integer
  5709. // like".
  5710. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  5711. bool HadField = false;
  5712. unsigned idx = 0;
  5713. for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
  5714. i != e; ++i, ++idx) {
  5715. const FieldDecl *FD = *i;
  5716. // Bit-fields are not addressable, we only need to verify they are "integer
  5717. // like". We still have to disallow a subsequent non-bitfield, for example:
  5718. // struct { int : 0; int x }
  5719. // is non-integer like according to gcc.
  5720. if (FD->isBitField()) {
  5721. if (!RD->isUnion())
  5722. HadField = true;
  5723. if (!isIntegerLikeType(FD->getType(), Context, VMContext))
  5724. return false;
  5725. continue;
  5726. }
  5727. // Check if this field is at offset 0.
  5728. if (Layout.getFieldOffset(idx) != 0)
  5729. return false;
  5730. if (!isIntegerLikeType(FD->getType(), Context, VMContext))
  5731. return false;
  5732. // Only allow at most one field in a structure. This doesn't match the
  5733. // wording above, but follows gcc in situations with a field following an
  5734. // empty structure.
  5735. if (!RD->isUnion()) {
  5736. if (HadField)
  5737. return false;
  5738. HadField = true;
  5739. }
  5740. }
  5741. return true;
  5742. }
  5743. ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
  5744. unsigned functionCallConv) const {
  5745. // Variadic functions should always marshal to the base standard.
  5746. bool IsAAPCS_VFP =
  5747. !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
  5748. if (RetTy->isVoidType())
  5749. return ABIArgInfo::getIgnore();
  5750. if (const VectorType *VT = RetTy->getAs<VectorType>()) {
  5751. // Large vector types should be returned via memory.
  5752. if (getContext().getTypeSize(RetTy) > 128)
  5753. return getNaturalAlignIndirect(RetTy);
  5754. // TODO: FP16/BF16 vectors should be converted to integer vectors
  5755. // This check is similar to isIllegalVectorType - refactor?
  5756. if ((!getTarget().hasLegalHalfType() &&
  5757. (VT->getElementType()->isFloat16Type() ||
  5758. VT->getElementType()->isHalfType())) ||
  5759. (IsFloatABISoftFP &&
  5760. VT->getElementType()->isBFloat16Type()))
  5761. return coerceIllegalVector(RetTy);
  5762. }
  5763. if (!isAggregateTypeForABI(RetTy)) {
  5764. // Treat an enum type as its underlying type.
  5765. if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
  5766. RetTy = EnumTy->getDecl()->getIntegerType();
  5767. if (const auto *EIT = RetTy->getAs<BitIntType>())
  5768. if (EIT->getNumBits() > 64)
  5769. return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
  5770. return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
  5771. : ABIArgInfo::getDirect();
  5772. }
  5773. // Are we following APCS?
  5774. if (getABIKind() == APCS) {
  5775. if (isEmptyRecord(getContext(), RetTy, false))
  5776. return ABIArgInfo::getIgnore();
  5777. // Complex types are all returned as packed integers.
  5778. //
  5779. // FIXME: Consider using 2 x vector types if the back end handles them
  5780. // correctly.
  5781. if (RetTy->isAnyComplexType())
  5782. return ABIArgInfo::getDirect(llvm::IntegerType::get(
  5783. getVMContext(), getContext().getTypeSize(RetTy)));
  5784. // Integer like structures are returned in r0.
  5785. if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
  5786. // Return in the smallest viable integer type.
  5787. uint64_t Size = getContext().getTypeSize(RetTy);
  5788. if (Size <= 8)
  5789. return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
  5790. if (Size <= 16)
  5791. return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
  5792. return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
  5793. }
  5794. // Otherwise return in memory.
  5795. return getNaturalAlignIndirect(RetTy);
  5796. }
  5797. // Otherwise this is an AAPCS variant.
  5798. if (isEmptyRecord(getContext(), RetTy, true))
  5799. return ABIArgInfo::getIgnore();
  5800. // Check for homogeneous aggregates with AAPCS-VFP.
  5801. if (IsAAPCS_VFP) {
  5802. const Type *Base = nullptr;
  5803. uint64_t Members = 0;
  5804. if (isHomogeneousAggregate(RetTy, Base, Members))
  5805. return classifyHomogeneousAggregate(RetTy, Base, Members);
  5806. }
  5807. // Aggregates <= 4 bytes are returned in r0; other aggregates
  5808. // are returned indirectly.
  5809. uint64_t Size = getContext().getTypeSize(RetTy);
  5810. if (Size <= 32) {
  5811. // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
  5812. // same size and alignment.
  5813. if (getTarget().isRenderScriptTarget()) {
  5814. return coerceToIntArray(RetTy, getContext(), getVMContext());
  5815. }
  5816. if (getDataLayout().isBigEndian())
  5817. // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
  5818. return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
  5819. // Return in the smallest viable integer type.
  5820. if (Size <= 8)
  5821. return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
  5822. if (Size <= 16)
  5823. return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
  5824. return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
  5825. } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
  5826. llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
  5827. llvm::Type *CoerceTy =
  5828. llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
  5829. return ABIArgInfo::getDirect(CoerceTy);
  5830. }
  5831. return getNaturalAlignIndirect(RetTy);
  5832. }
  5833. /// isIllegalVector - check whether Ty is an illegal vector type.
  5834. bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
  5835. if (const VectorType *VT = Ty->getAs<VectorType> ()) {
  5836. // On targets that don't support half, fp16 or bfloat, they are expanded
  5837. // into float, and we don't want the ABI to depend on whether or not they
  5838. // are supported in hardware. Thus return false to coerce vectors of these
  5839. // types into integer vectors.
  5840. // We do not depend on hasLegalHalfType for bfloat as it is a
  5841. // separate IR type.
  5842. if ((!getTarget().hasLegalHalfType() &&
  5843. (VT->getElementType()->isFloat16Type() ||
  5844. VT->getElementType()->isHalfType())) ||
  5845. (IsFloatABISoftFP &&
  5846. VT->getElementType()->isBFloat16Type()))
  5847. return true;
  5848. if (isAndroid()) {
  5849. // Android shipped using Clang 3.1, which supported a slightly different
  5850. // vector ABI. The primary differences were that 3-element vector types
  5851. // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
  5852. // accepts that legacy behavior for Android only.
  5853. // Check whether VT is legal.
  5854. unsigned NumElements = VT->getNumElements();
  5855. // NumElements should be power of 2 or equal to 3.
  5856. if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
  5857. return true;
  5858. } else {
  5859. // Check whether VT is legal.
  5860. unsigned NumElements = VT->getNumElements();
  5861. uint64_t Size = getContext().getTypeSize(VT);
  5862. // NumElements should be power of 2.
  5863. if (!llvm::isPowerOf2_32(NumElements))
  5864. return true;
  5865. // Size should be greater than 32 bits.
  5866. return Size <= 32;
  5867. }
  5868. }
  5869. return false;
  5870. }
  5871. /// Return true if a type contains any 16-bit floating point vectors
  5872. bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
  5873. if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
  5874. uint64_t NElements = AT->getSize().getZExtValue();
  5875. if (NElements == 0)
  5876. return false;
  5877. return containsAnyFP16Vectors(AT->getElementType());
  5878. } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
  5879. const RecordDecl *RD = RT->getDecl();
  5880. // If this is a C++ record, check the bases first.
  5881. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  5882. if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
  5883. return containsAnyFP16Vectors(B.getType());
  5884. }))
  5885. return true;
  5886. if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
  5887. return FD && containsAnyFP16Vectors(FD->getType());
  5888. }))
  5889. return true;
  5890. return false;
  5891. } else {
  5892. if (const VectorType *VT = Ty->getAs<VectorType>())
  5893. return (VT->getElementType()->isFloat16Type() ||
  5894. VT->getElementType()->isBFloat16Type() ||
  5895. VT->getElementType()->isHalfType());
  5896. return false;
  5897. }
  5898. }
  5899. bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
  5900. llvm::Type *eltTy,
  5901. unsigned numElts) const {
  5902. if (!llvm::isPowerOf2_32(numElts))
  5903. return false;
  5904. unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
  5905. if (size > 64)
  5906. return false;
  5907. if (vectorSize.getQuantity() != 8 &&
  5908. (vectorSize.getQuantity() != 16 || numElts == 1))
  5909. return false;
  5910. return true;
  5911. }
  5912. bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
  5913. // Homogeneous aggregates for AAPCS-VFP must have base types of float,
  5914. // double, or 64-bit or 128-bit vectors.
  5915. if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
  5916. if (BT->getKind() == BuiltinType::Float ||
  5917. BT->getKind() == BuiltinType::Double ||
  5918. BT->getKind() == BuiltinType::LongDouble)
  5919. return true;
  5920. } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
  5921. unsigned VecSize = getContext().getTypeSize(VT);
  5922. if (VecSize == 64 || VecSize == 128)
  5923. return true;
  5924. }
  5925. return false;
  5926. }
  5927. bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
  5928. uint64_t Members) const {
  5929. return Members <= 4;
  5930. }
  5931. bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
  5932. bool acceptHalf) const {
  5933. // Give precedence to user-specified calling conventions.
  5934. if (callConvention != llvm::CallingConv::C)
  5935. return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
  5936. else
  5937. return (getABIKind() == AAPCS_VFP) ||
  5938. (acceptHalf && (getABIKind() == AAPCS16_VFP));
  5939. }
  5940. Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  5941. QualType Ty) const {
  5942. CharUnits SlotSize = CharUnits::fromQuantity(4);
  5943. // Empty records are ignored for parameter passing purposes.
  5944. if (isEmptyRecord(getContext(), Ty, true)) {
  5945. Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
  5946. Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
  5947. return Addr;
  5948. }
  5949. CharUnits TySize = getContext().getTypeSizeInChars(Ty);
  5950. CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
  5951. // Use indirect if size of the illegal vector is bigger than 16 bytes.
  5952. bool IsIndirect = false;
  5953. const Type *Base = nullptr;
  5954. uint64_t Members = 0;
  5955. if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
  5956. IsIndirect = true;
  5957. // ARMv7k passes structs bigger than 16 bytes indirectly, in space
  5958. // allocated by the caller.
  5959. } else if (TySize > CharUnits::fromQuantity(16) &&
  5960. getABIKind() == ARMABIInfo::AAPCS16_VFP &&
  5961. !isHomogeneousAggregate(Ty, Base, Members)) {
  5962. IsIndirect = true;
  5963. // Otherwise, bound the type's ABI alignment.
  5964. // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
  5965. // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
  5966. // Our callers should be prepared to handle an under-aligned address.
  5967. } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
  5968. getABIKind() == ARMABIInfo::AAPCS) {
  5969. TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
  5970. TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
  5971. } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
  5972. // ARMv7k allows type alignment up to 16 bytes.
  5973. TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
  5974. TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
  5975. } else {
  5976. TyAlignForABI = CharUnits::fromQuantity(4);
  5977. }
  5978. TypeInfoChars TyInfo(TySize, TyAlignForABI, AlignRequirementKind::None);
  5979. return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
  5980. SlotSize, /*AllowHigherAlign*/ true);
  5981. }
  5982. //===----------------------------------------------------------------------===//
  5983. // NVPTX ABI Implementation
  5984. //===----------------------------------------------------------------------===//
  5985. namespace {
  5986. class NVPTXTargetCodeGenInfo;
  5987. class NVPTXABIInfo : public ABIInfo {
  5988. NVPTXTargetCodeGenInfo &CGInfo;
  5989. public:
  5990. NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info)
  5991. : ABIInfo(CGT), CGInfo(Info) {}
  5992. ABIArgInfo classifyReturnType(QualType RetTy) const;
  5993. ABIArgInfo classifyArgumentType(QualType Ty) const;
  5994. void computeInfo(CGFunctionInfo &FI) const override;
  5995. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  5996. QualType Ty) const override;
  5997. bool isUnsupportedType(QualType T) const;
  5998. ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const;
  5999. };
  6000. class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
  6001. public:
  6002. NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
  6003. : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {}
  6004. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  6005. CodeGen::CodeGenModule &M) const override;
  6006. bool shouldEmitStaticExternCAliases() const override;
  6007. llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override {
  6008. // On the device side, surface reference is represented as an object handle
  6009. // in 64-bit integer.
  6010. return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
  6011. }
  6012. llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override {
  6013. // On the device side, texture reference is represented as an object handle
  6014. // in 64-bit integer.
  6015. return llvm::Type::getInt64Ty(getABIInfo().getVMContext());
  6016. }
  6017. bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst,
  6018. LValue Src) const override {
  6019. emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
  6020. return true;
  6021. }
  6022. bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst,
  6023. LValue Src) const override {
  6024. emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src);
  6025. return true;
  6026. }
  6027. private:
  6028. // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the
  6029. // resulting MDNode to the nvvm.annotations MDNode.
  6030. static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name,
  6031. int Operand);
  6032. static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst,
  6033. LValue Src) {
  6034. llvm::Value *Handle = nullptr;
  6035. llvm::Constant *C =
  6036. llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer());
  6037. // Lookup `addrspacecast` through the constant pointer if any.
  6038. if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C))
  6039. C = llvm::cast<llvm::Constant>(ASC->getPointerOperand());
  6040. if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) {
  6041. // Load the handle from the specific global variable using
  6042. // `nvvm.texsurf.handle.internal` intrinsic.
  6043. Handle = CGF.EmitRuntimeCall(
  6044. CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal,
  6045. {GV->getType()}),
  6046. {GV}, "texsurf_handle");
  6047. } else
  6048. Handle = CGF.EmitLoadOfScalar(Src, SourceLocation());
  6049. CGF.EmitStoreOfScalar(Handle, Dst);
  6050. }
  6051. };
  6052. /// Checks if the type is unsupported directly by the current target.
  6053. bool NVPTXABIInfo::isUnsupportedType(QualType T) const {
  6054. ASTContext &Context = getContext();
  6055. if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
  6056. return true;
  6057. if (!Context.getTargetInfo().hasFloat128Type() &&
  6058. (T->isFloat128Type() ||
  6059. (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
  6060. return true;
  6061. if (const auto *EIT = T->getAs<BitIntType>())
  6062. return EIT->getNumBits() >
  6063. (Context.getTargetInfo().hasInt128Type() ? 128U : 64U);
  6064. if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
  6065. Context.getTypeSize(T) > 64U)
  6066. return true;
  6067. if (const auto *AT = T->getAsArrayTypeUnsafe())
  6068. return isUnsupportedType(AT->getElementType());
  6069. const auto *RT = T->getAs<RecordType>();
  6070. if (!RT)
  6071. return false;
  6072. const RecordDecl *RD = RT->getDecl();
  6073. // If this is a C++ record, check the bases first.
  6074. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  6075. for (const CXXBaseSpecifier &I : CXXRD->bases())
  6076. if (isUnsupportedType(I.getType()))
  6077. return true;
  6078. for (const FieldDecl *I : RD->fields())
  6079. if (isUnsupportedType(I->getType()))
  6080. return true;
  6081. return false;
  6082. }
  6083. /// Coerce the given type into an array with maximum allowed size of elements.
  6084. ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty,
  6085. unsigned MaxSize) const {
  6086. // Alignment and Size are measured in bits.
  6087. const uint64_t Size = getContext().getTypeSize(Ty);
  6088. const uint64_t Alignment = getContext().getTypeAlign(Ty);
  6089. const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
  6090. llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div);
  6091. const uint64_t NumElements = (Size + Div - 1) / Div;
  6092. return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
  6093. }
  6094. ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
  6095. if (RetTy->isVoidType())
  6096. return ABIArgInfo::getIgnore();
  6097. if (getContext().getLangOpts().OpenMP &&
  6098. getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy))
  6099. return coerceToIntArrayWithLimit(RetTy, 64);
  6100. // note: this is different from default ABI
  6101. if (!RetTy->isScalarType())
  6102. return ABIArgInfo::getDirect();
  6103. // Treat an enum type as its underlying type.
  6104. if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
  6105. RetTy = EnumTy->getDecl()->getIntegerType();
  6106. return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
  6107. : ABIArgInfo::getDirect());
  6108. }
  6109. ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
  6110. // Treat an enum type as its underlying type.
  6111. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  6112. Ty = EnumTy->getDecl()->getIntegerType();
  6113. // Return aggregates type as indirect by value
  6114. if (isAggregateTypeForABI(Ty)) {
  6115. // Under CUDA device compilation, tex/surf builtin types are replaced with
  6116. // object types and passed directly.
  6117. if (getContext().getLangOpts().CUDAIsDevice) {
  6118. if (Ty->isCUDADeviceBuiltinSurfaceType())
  6119. return ABIArgInfo::getDirect(
  6120. CGInfo.getCUDADeviceBuiltinSurfaceDeviceType());
  6121. if (Ty->isCUDADeviceBuiltinTextureType())
  6122. return ABIArgInfo::getDirect(
  6123. CGInfo.getCUDADeviceBuiltinTextureDeviceType());
  6124. }
  6125. return getNaturalAlignIndirect(Ty, /* byval */ true);
  6126. }
  6127. if (const auto *EIT = Ty->getAs<BitIntType>()) {
  6128. if ((EIT->getNumBits() > 128) ||
  6129. (!getContext().getTargetInfo().hasInt128Type() &&
  6130. EIT->getNumBits() > 64))
  6131. return getNaturalAlignIndirect(Ty, /* byval */ true);
  6132. }
  6133. return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
  6134. : ABIArgInfo::getDirect());
  6135. }
  6136. void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
  6137. if (!getCXXABI().classifyReturnType(FI))
  6138. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  6139. for (auto &I : FI.arguments())
  6140. I.info = classifyArgumentType(I.type);
  6141. // Always honor user-specified calling convention.
  6142. if (FI.getCallingConvention() != llvm::CallingConv::C)
  6143. return;
  6144. FI.setEffectiveCallingConvention(getRuntimeCC());
  6145. }
  6146. Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  6147. QualType Ty) const {
  6148. llvm_unreachable("NVPTX does not support varargs");
  6149. }
  6150. void NVPTXTargetCodeGenInfo::setTargetAttributes(
  6151. const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
  6152. if (GV->isDeclaration())
  6153. return;
  6154. const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
  6155. if (VD) {
  6156. if (M.getLangOpts().CUDA) {
  6157. if (VD->getType()->isCUDADeviceBuiltinSurfaceType())
  6158. addNVVMMetadata(GV, "surface", 1);
  6159. else if (VD->getType()->isCUDADeviceBuiltinTextureType())
  6160. addNVVMMetadata(GV, "texture", 1);
  6161. return;
  6162. }
  6163. }
  6164. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
  6165. if (!FD) return;
  6166. llvm::Function *F = cast<llvm::Function>(GV);
  6167. // Perform special handling in OpenCL mode
  6168. if (M.getLangOpts().OpenCL) {
  6169. // Use OpenCL function attributes to check for kernel functions
  6170. // By default, all functions are device functions
  6171. if (FD->hasAttr<OpenCLKernelAttr>()) {
  6172. // OpenCL __kernel functions get kernel metadata
  6173. // Create !{<func-ref>, metadata !"kernel", i32 1} node
  6174. addNVVMMetadata(F, "kernel", 1);
  6175. // And kernel functions are not subject to inlining
  6176. F->addFnAttr(llvm::Attribute::NoInline);
  6177. }
  6178. }
  6179. // Perform special handling in CUDA mode.
  6180. if (M.getLangOpts().CUDA) {
  6181. // CUDA __global__ functions get a kernel metadata entry. Since
  6182. // __global__ functions cannot be called from the device, we do not
  6183. // need to set the noinline attribute.
  6184. if (FD->hasAttr<CUDAGlobalAttr>()) {
  6185. // Create !{<func-ref>, metadata !"kernel", i32 1} node
  6186. addNVVMMetadata(F, "kernel", 1);
  6187. }
  6188. if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
  6189. // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
  6190. llvm::APSInt MaxThreads(32);
  6191. MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
  6192. if (MaxThreads > 0)
  6193. addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
  6194. // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
  6195. // not specified in __launch_bounds__ or if the user specified a 0 value,
  6196. // we don't have to add a PTX directive.
  6197. if (Attr->getMinBlocks()) {
  6198. llvm::APSInt MinBlocks(32);
  6199. MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
  6200. if (MinBlocks > 0)
  6201. // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
  6202. addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
  6203. }
  6204. }
  6205. }
  6206. }
  6207. void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV,
  6208. StringRef Name, int Operand) {
  6209. llvm::Module *M = GV->getParent();
  6210. llvm::LLVMContext &Ctx = M->getContext();
  6211. // Get "nvvm.annotations" metadata node
  6212. llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
  6213. llvm::Metadata *MDVals[] = {
  6214. llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name),
  6215. llvm::ConstantAsMetadata::get(
  6216. llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
  6217. // Append metadata to nvvm.annotations
  6218. MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
  6219. }
  6220. bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
  6221. return false;
  6222. }
  6223. }
  6224. //===----------------------------------------------------------------------===//
  6225. // SystemZ ABI Implementation
  6226. //===----------------------------------------------------------------------===//
  6227. namespace {
  6228. class SystemZABIInfo : public SwiftABIInfo {
  6229. bool HasVector;
  6230. bool IsSoftFloatABI;
  6231. public:
  6232. SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF)
  6233. : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {}
  6234. bool isPromotableIntegerTypeForABI(QualType Ty) const;
  6235. bool isCompoundType(QualType Ty) const;
  6236. bool isVectorArgumentType(QualType Ty) const;
  6237. bool isFPArgumentType(QualType Ty) const;
  6238. QualType GetSingleElementType(QualType Ty) const;
  6239. ABIArgInfo classifyReturnType(QualType RetTy) const;
  6240. ABIArgInfo classifyArgumentType(QualType ArgTy) const;
  6241. void computeInfo(CGFunctionInfo &FI) const override {
  6242. if (!getCXXABI().classifyReturnType(FI))
  6243. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  6244. for (auto &I : FI.arguments())
  6245. I.info = classifyArgumentType(I.type);
  6246. }
  6247. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  6248. QualType Ty) const override;
  6249. bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
  6250. bool asReturnValue) const override {
  6251. return occupiesMoreThan(CGT, scalars, /*total*/ 4);
  6252. }
  6253. bool isSwiftErrorInRegister() const override {
  6254. return false;
  6255. }
  6256. };
  6257. class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
  6258. public:
  6259. SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI)
  6260. : TargetCodeGenInfo(
  6261. std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {}
  6262. llvm::Value *testFPKind(llvm::Value *V, unsigned BuiltinID,
  6263. CGBuilderTy &Builder,
  6264. CodeGenModule &CGM) const override {
  6265. assert(V->getType()->isFloatingPointTy() && "V should have an FP type.");
  6266. // Only use TDC in constrained FP mode.
  6267. if (!Builder.getIsFPConstrained())
  6268. return nullptr;
  6269. llvm::Type *Ty = V->getType();
  6270. if (Ty->isFloatTy() || Ty->isDoubleTy() || Ty->isFP128Ty()) {
  6271. llvm::Module &M = CGM.getModule();
  6272. auto &Ctx = M.getContext();
  6273. llvm::Function *TDCFunc =
  6274. llvm::Intrinsic::getDeclaration(&M, llvm::Intrinsic::s390_tdc, Ty);
  6275. unsigned TDCBits = 0;
  6276. switch (BuiltinID) {
  6277. case Builtin::BI__builtin_isnan:
  6278. TDCBits = 0xf;
  6279. break;
  6280. case Builtin::BIfinite:
  6281. case Builtin::BI__finite:
  6282. case Builtin::BIfinitef:
  6283. case Builtin::BI__finitef:
  6284. case Builtin::BIfinitel:
  6285. case Builtin::BI__finitel:
  6286. case Builtin::BI__builtin_isfinite:
  6287. TDCBits = 0xfc0;
  6288. break;
  6289. case Builtin::BI__builtin_isinf:
  6290. TDCBits = 0x30;
  6291. break;
  6292. default:
  6293. break;
  6294. }
  6295. if (TDCBits)
  6296. return Builder.CreateCall(
  6297. TDCFunc,
  6298. {V, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), TDCBits)});
  6299. }
  6300. return nullptr;
  6301. }
  6302. };
  6303. }
  6304. bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const {
  6305. // Treat an enum type as its underlying type.
  6306. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  6307. Ty = EnumTy->getDecl()->getIntegerType();
  6308. // Promotable integer types are required to be promoted by the ABI.
  6309. if (ABIInfo::isPromotableIntegerTypeForABI(Ty))
  6310. return true;
  6311. if (const auto *EIT = Ty->getAs<BitIntType>())
  6312. if (EIT->getNumBits() < 64)
  6313. return true;
  6314. // 32-bit values must also be promoted.
  6315. if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
  6316. switch (BT->getKind()) {
  6317. case BuiltinType::Int:
  6318. case BuiltinType::UInt:
  6319. return true;
  6320. default:
  6321. return false;
  6322. }
  6323. return false;
  6324. }
  6325. bool SystemZABIInfo::isCompoundType(QualType Ty) const {
  6326. return (Ty->isAnyComplexType() ||
  6327. Ty->isVectorType() ||
  6328. isAggregateTypeForABI(Ty));
  6329. }
  6330. bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
  6331. return (HasVector &&
  6332. Ty->isVectorType() &&
  6333. getContext().getTypeSize(Ty) <= 128);
  6334. }
  6335. bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
  6336. if (IsSoftFloatABI)
  6337. return false;
  6338. if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
  6339. switch (BT->getKind()) {
  6340. case BuiltinType::Float:
  6341. case BuiltinType::Double:
  6342. return true;
  6343. default:
  6344. return false;
  6345. }
  6346. return false;
  6347. }
  6348. QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
  6349. const RecordType *RT = Ty->getAs<RecordType>();
  6350. if (RT && RT->isStructureOrClassType()) {
  6351. const RecordDecl *RD = RT->getDecl();
  6352. QualType Found;
  6353. // If this is a C++ record, check the bases first.
  6354. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  6355. for (const auto &I : CXXRD->bases()) {
  6356. QualType Base = I.getType();
  6357. // Empty bases don't affect things either way.
  6358. if (isEmptyRecord(getContext(), Base, true))
  6359. continue;
  6360. if (!Found.isNull())
  6361. return Ty;
  6362. Found = GetSingleElementType(Base);
  6363. }
  6364. // Check the fields.
  6365. for (const auto *FD : RD->fields()) {
  6366. // For compatibility with GCC, ignore empty bitfields in C++ mode.
  6367. // Unlike isSingleElementStruct(), empty structure and array fields
  6368. // do count. So do anonymous bitfields that aren't zero-sized.
  6369. if (getContext().getLangOpts().CPlusPlus &&
  6370. FD->isZeroLengthBitField(getContext()))
  6371. continue;
  6372. // Like isSingleElementStruct(), ignore C++20 empty data members.
  6373. if (FD->hasAttr<NoUniqueAddressAttr>() &&
  6374. isEmptyRecord(getContext(), FD->getType(), true))
  6375. continue;
  6376. // Unlike isSingleElementStruct(), arrays do not count.
  6377. // Nested structures still do though.
  6378. if (!Found.isNull())
  6379. return Ty;
  6380. Found = GetSingleElementType(FD->getType());
  6381. }
  6382. // Unlike isSingleElementStruct(), trailing padding is allowed.
  6383. // An 8-byte aligned struct s { float f; } is passed as a double.
  6384. if (!Found.isNull())
  6385. return Found;
  6386. }
  6387. return Ty;
  6388. }
  6389. Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  6390. QualType Ty) const {
  6391. // Assume that va_list type is correct; should be pointer to LLVM type:
  6392. // struct {
  6393. // i64 __gpr;
  6394. // i64 __fpr;
  6395. // i8 *__overflow_arg_area;
  6396. // i8 *__reg_save_area;
  6397. // };
  6398. // Every non-vector argument occupies 8 bytes and is passed by preference
  6399. // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
  6400. // always passed on the stack.
  6401. Ty = getContext().getCanonicalType(Ty);
  6402. auto TyInfo = getContext().getTypeInfoInChars(Ty);
  6403. llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
  6404. llvm::Type *DirectTy = ArgTy;
  6405. ABIArgInfo AI = classifyArgumentType(Ty);
  6406. bool IsIndirect = AI.isIndirect();
  6407. bool InFPRs = false;
  6408. bool IsVector = false;
  6409. CharUnits UnpaddedSize;
  6410. CharUnits DirectAlign;
  6411. if (IsIndirect) {
  6412. DirectTy = llvm::PointerType::getUnqual(DirectTy);
  6413. UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
  6414. } else {
  6415. if (AI.getCoerceToType())
  6416. ArgTy = AI.getCoerceToType();
  6417. InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy()));
  6418. IsVector = ArgTy->isVectorTy();
  6419. UnpaddedSize = TyInfo.Width;
  6420. DirectAlign = TyInfo.Align;
  6421. }
  6422. CharUnits PaddedSize = CharUnits::fromQuantity(8);
  6423. if (IsVector && UnpaddedSize > PaddedSize)
  6424. PaddedSize = CharUnits::fromQuantity(16);
  6425. assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
  6426. CharUnits Padding = (PaddedSize - UnpaddedSize);
  6427. llvm::Type *IndexTy = CGF.Int64Ty;
  6428. llvm::Value *PaddedSizeV =
  6429. llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
  6430. if (IsVector) {
  6431. // Work out the address of a vector argument on the stack.
  6432. // Vector arguments are always passed in the high bits of a
  6433. // single (8 byte) or double (16 byte) stack slot.
  6434. Address OverflowArgAreaPtr =
  6435. CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
  6436. Address OverflowArgArea =
  6437. Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
  6438. TyInfo.Align);
  6439. Address MemAddr =
  6440. CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
  6441. // Update overflow_arg_area_ptr pointer
  6442. llvm::Value *NewOverflowArgArea =
  6443. CGF.Builder.CreateGEP(OverflowArgArea.getElementType(),
  6444. OverflowArgArea.getPointer(), PaddedSizeV,
  6445. "overflow_arg_area");
  6446. CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
  6447. return MemAddr;
  6448. }
  6449. assert(PaddedSize.getQuantity() == 8);
  6450. unsigned MaxRegs, RegCountField, RegSaveIndex;
  6451. CharUnits RegPadding;
  6452. if (InFPRs) {
  6453. MaxRegs = 4; // Maximum of 4 FPR arguments
  6454. RegCountField = 1; // __fpr
  6455. RegSaveIndex = 16; // save offset for f0
  6456. RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
  6457. } else {
  6458. MaxRegs = 5; // Maximum of 5 GPR arguments
  6459. RegCountField = 0; // __gpr
  6460. RegSaveIndex = 2; // save offset for r2
  6461. RegPadding = Padding; // values are passed in the low bits of a GPR
  6462. }
  6463. Address RegCountPtr =
  6464. CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
  6465. llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
  6466. llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
  6467. llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
  6468. "fits_in_regs");
  6469. llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
  6470. llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
  6471. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
  6472. CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
  6473. // Emit code to load the value if it was passed in registers.
  6474. CGF.EmitBlock(InRegBlock);
  6475. // Work out the address of an argument register.
  6476. llvm::Value *ScaledRegCount =
  6477. CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
  6478. llvm::Value *RegBase =
  6479. llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
  6480. + RegPadding.getQuantity());
  6481. llvm::Value *RegOffset =
  6482. CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
  6483. Address RegSaveAreaPtr =
  6484. CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
  6485. llvm::Value *RegSaveArea =
  6486. CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
  6487. Address RawRegAddr(CGF.Builder.CreateGEP(CGF.Int8Ty, RegSaveArea, RegOffset,
  6488. "raw_reg_addr"),
  6489. PaddedSize);
  6490. Address RegAddr =
  6491. CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
  6492. // Update the register count
  6493. llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
  6494. llvm::Value *NewRegCount =
  6495. CGF.Builder.CreateAdd(RegCount, One, "reg_count");
  6496. CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
  6497. CGF.EmitBranch(ContBlock);
  6498. // Emit code to load the value if it was passed in memory.
  6499. CGF.EmitBlock(InMemBlock);
  6500. // Work out the address of a stack argument.
  6501. Address OverflowArgAreaPtr =
  6502. CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
  6503. Address OverflowArgArea =
  6504. Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
  6505. PaddedSize);
  6506. Address RawMemAddr =
  6507. CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
  6508. Address MemAddr =
  6509. CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
  6510. // Update overflow_arg_area_ptr pointer
  6511. llvm::Value *NewOverflowArgArea =
  6512. CGF.Builder.CreateGEP(OverflowArgArea.getElementType(),
  6513. OverflowArgArea.getPointer(), PaddedSizeV,
  6514. "overflow_arg_area");
  6515. CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
  6516. CGF.EmitBranch(ContBlock);
  6517. // Return the appropriate result.
  6518. CGF.EmitBlock(ContBlock);
  6519. Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
  6520. MemAddr, InMemBlock, "va_arg.addr");
  6521. if (IsIndirect)
  6522. ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
  6523. TyInfo.Align);
  6524. return ResAddr;
  6525. }
  6526. ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
  6527. if (RetTy->isVoidType())
  6528. return ABIArgInfo::getIgnore();
  6529. if (isVectorArgumentType(RetTy))
  6530. return ABIArgInfo::getDirect();
  6531. if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
  6532. return getNaturalAlignIndirect(RetTy);
  6533. return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
  6534. : ABIArgInfo::getDirect());
  6535. }
  6536. ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
  6537. // Handle the generic C++ ABI.
  6538. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
  6539. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  6540. // Integers and enums are extended to full register width.
  6541. if (isPromotableIntegerTypeForABI(Ty))
  6542. return ABIArgInfo::getExtend(Ty);
  6543. // Handle vector types and vector-like structure types. Note that
  6544. // as opposed to float-like structure types, we do not allow any
  6545. // padding for vector-like structures, so verify the sizes match.
  6546. uint64_t Size = getContext().getTypeSize(Ty);
  6547. QualType SingleElementTy = GetSingleElementType(Ty);
  6548. if (isVectorArgumentType(SingleElementTy) &&
  6549. getContext().getTypeSize(SingleElementTy) == Size)
  6550. return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
  6551. // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
  6552. if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
  6553. return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
  6554. // Handle small structures.
  6555. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  6556. // Structures with flexible arrays have variable length, so really
  6557. // fail the size test above.
  6558. const RecordDecl *RD = RT->getDecl();
  6559. if (RD->hasFlexibleArrayMember())
  6560. return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
  6561. // The structure is passed as an unextended integer, a float, or a double.
  6562. llvm::Type *PassTy;
  6563. if (isFPArgumentType(SingleElementTy)) {
  6564. assert(Size == 32 || Size == 64);
  6565. if (Size == 32)
  6566. PassTy = llvm::Type::getFloatTy(getVMContext());
  6567. else
  6568. PassTy = llvm::Type::getDoubleTy(getVMContext());
  6569. } else
  6570. PassTy = llvm::IntegerType::get(getVMContext(), Size);
  6571. return ABIArgInfo::getDirect(PassTy);
  6572. }
  6573. // Non-structure compounds are passed indirectly.
  6574. if (isCompoundType(Ty))
  6575. return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
  6576. return ABIArgInfo::getDirect(nullptr);
  6577. }
  6578. //===----------------------------------------------------------------------===//
  6579. // MSP430 ABI Implementation
  6580. //===----------------------------------------------------------------------===//
  6581. namespace {
  6582. class MSP430ABIInfo : public DefaultABIInfo {
  6583. static ABIArgInfo complexArgInfo() {
  6584. ABIArgInfo Info = ABIArgInfo::getDirect();
  6585. Info.setCanBeFlattened(false);
  6586. return Info;
  6587. }
  6588. public:
  6589. MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
  6590. ABIArgInfo classifyReturnType(QualType RetTy) const {
  6591. if (RetTy->isAnyComplexType())
  6592. return complexArgInfo();
  6593. return DefaultABIInfo::classifyReturnType(RetTy);
  6594. }
  6595. ABIArgInfo classifyArgumentType(QualType RetTy) const {
  6596. if (RetTy->isAnyComplexType())
  6597. return complexArgInfo();
  6598. return DefaultABIInfo::classifyArgumentType(RetTy);
  6599. }
  6600. // Just copy the original implementations because
  6601. // DefaultABIInfo::classify{Return,Argument}Type() are not virtual
  6602. void computeInfo(CGFunctionInfo &FI) const override {
  6603. if (!getCXXABI().classifyReturnType(FI))
  6604. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  6605. for (auto &I : FI.arguments())
  6606. I.info = classifyArgumentType(I.type);
  6607. }
  6608. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  6609. QualType Ty) const override {
  6610. return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
  6611. }
  6612. };
  6613. class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
  6614. public:
  6615. MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
  6616. : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {}
  6617. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  6618. CodeGen::CodeGenModule &M) const override;
  6619. };
  6620. }
  6621. void MSP430TargetCodeGenInfo::setTargetAttributes(
  6622. const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
  6623. if (GV->isDeclaration())
  6624. return;
  6625. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  6626. const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
  6627. if (!InterruptAttr)
  6628. return;
  6629. // Handle 'interrupt' attribute:
  6630. llvm::Function *F = cast<llvm::Function>(GV);
  6631. // Step 1: Set ISR calling convention.
  6632. F->setCallingConv(llvm::CallingConv::MSP430_INTR);
  6633. // Step 2: Add attributes goodness.
  6634. F->addFnAttr(llvm::Attribute::NoInline);
  6635. F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
  6636. }
  6637. }
  6638. //===----------------------------------------------------------------------===//
  6639. // MIPS ABI Implementation. This works for both little-endian and
  6640. // big-endian variants.
  6641. //===----------------------------------------------------------------------===//
  6642. namespace {
  6643. class MipsABIInfo : public ABIInfo {
  6644. bool IsO32;
  6645. unsigned MinABIStackAlignInBytes, StackAlignInBytes;
  6646. void CoerceToIntArgs(uint64_t TySize,
  6647. SmallVectorImpl<llvm::Type *> &ArgList) const;
  6648. llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
  6649. llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
  6650. llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
  6651. public:
  6652. MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
  6653. ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
  6654. StackAlignInBytes(IsO32 ? 8 : 16) {}
  6655. ABIArgInfo classifyReturnType(QualType RetTy) const;
  6656. ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
  6657. void computeInfo(CGFunctionInfo &FI) const override;
  6658. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  6659. QualType Ty) const override;
  6660. ABIArgInfo extendType(QualType Ty) const;
  6661. };
  6662. class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
  6663. unsigned SizeOfUnwindException;
  6664. public:
  6665. MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
  6666. : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)),
  6667. SizeOfUnwindException(IsO32 ? 24 : 32) {}
  6668. int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
  6669. return 29;
  6670. }
  6671. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  6672. CodeGen::CodeGenModule &CGM) const override {
  6673. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
  6674. if (!FD) return;
  6675. llvm::Function *Fn = cast<llvm::Function>(GV);
  6676. if (FD->hasAttr<MipsLongCallAttr>())
  6677. Fn->addFnAttr("long-call");
  6678. else if (FD->hasAttr<MipsShortCallAttr>())
  6679. Fn->addFnAttr("short-call");
  6680. // Other attributes do not have a meaning for declarations.
  6681. if (GV->isDeclaration())
  6682. return;
  6683. if (FD->hasAttr<Mips16Attr>()) {
  6684. Fn->addFnAttr("mips16");
  6685. }
  6686. else if (FD->hasAttr<NoMips16Attr>()) {
  6687. Fn->addFnAttr("nomips16");
  6688. }
  6689. if (FD->hasAttr<MicroMipsAttr>())
  6690. Fn->addFnAttr("micromips");
  6691. else if (FD->hasAttr<NoMicroMipsAttr>())
  6692. Fn->addFnAttr("nomicromips");
  6693. const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
  6694. if (!Attr)
  6695. return;
  6696. const char *Kind;
  6697. switch (Attr->getInterrupt()) {
  6698. case MipsInterruptAttr::eic: Kind = "eic"; break;
  6699. case MipsInterruptAttr::sw0: Kind = "sw0"; break;
  6700. case MipsInterruptAttr::sw1: Kind = "sw1"; break;
  6701. case MipsInterruptAttr::hw0: Kind = "hw0"; break;
  6702. case MipsInterruptAttr::hw1: Kind = "hw1"; break;
  6703. case MipsInterruptAttr::hw2: Kind = "hw2"; break;
  6704. case MipsInterruptAttr::hw3: Kind = "hw3"; break;
  6705. case MipsInterruptAttr::hw4: Kind = "hw4"; break;
  6706. case MipsInterruptAttr::hw5: Kind = "hw5"; break;
  6707. }
  6708. Fn->addFnAttr("interrupt", Kind);
  6709. }
  6710. bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  6711. llvm::Value *Address) const override;
  6712. unsigned getSizeOfUnwindException() const override {
  6713. return SizeOfUnwindException;
  6714. }
  6715. };
  6716. }
  6717. void MipsABIInfo::CoerceToIntArgs(
  6718. uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
  6719. llvm::IntegerType *IntTy =
  6720. llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
  6721. // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
  6722. for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
  6723. ArgList.push_back(IntTy);
  6724. // If necessary, add one more integer type to ArgList.
  6725. unsigned R = TySize % (MinABIStackAlignInBytes * 8);
  6726. if (R)
  6727. ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
  6728. }
  6729. // In N32/64, an aligned double precision floating point field is passed in
  6730. // a register.
  6731. llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
  6732. SmallVector<llvm::Type*, 8> ArgList, IntArgList;
  6733. if (IsO32) {
  6734. CoerceToIntArgs(TySize, ArgList);
  6735. return llvm::StructType::get(getVMContext(), ArgList);
  6736. }
  6737. if (Ty->isComplexType())
  6738. return CGT.ConvertType(Ty);
  6739. const RecordType *RT = Ty->getAs<RecordType>();
  6740. // Unions/vectors are passed in integer registers.
  6741. if (!RT || !RT->isStructureOrClassType()) {
  6742. CoerceToIntArgs(TySize, ArgList);
  6743. return llvm::StructType::get(getVMContext(), ArgList);
  6744. }
  6745. const RecordDecl *RD = RT->getDecl();
  6746. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  6747. assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
  6748. uint64_t LastOffset = 0;
  6749. unsigned idx = 0;
  6750. llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
  6751. // Iterate over fields in the struct/class and check if there are any aligned
  6752. // double fields.
  6753. for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
  6754. i != e; ++i, ++idx) {
  6755. const QualType Ty = i->getType();
  6756. const BuiltinType *BT = Ty->getAs<BuiltinType>();
  6757. if (!BT || BT->getKind() != BuiltinType::Double)
  6758. continue;
  6759. uint64_t Offset = Layout.getFieldOffset(idx);
  6760. if (Offset % 64) // Ignore doubles that are not aligned.
  6761. continue;
  6762. // Add ((Offset - LastOffset) / 64) args of type i64.
  6763. for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
  6764. ArgList.push_back(I64);
  6765. // Add double type.
  6766. ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
  6767. LastOffset = Offset + 64;
  6768. }
  6769. CoerceToIntArgs(TySize - LastOffset, IntArgList);
  6770. ArgList.append(IntArgList.begin(), IntArgList.end());
  6771. return llvm::StructType::get(getVMContext(), ArgList);
  6772. }
  6773. llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
  6774. uint64_t Offset) const {
  6775. if (OrigOffset + MinABIStackAlignInBytes > Offset)
  6776. return nullptr;
  6777. return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
  6778. }
  6779. ABIArgInfo
  6780. MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
  6781. Ty = useFirstFieldIfTransparentUnion(Ty);
  6782. uint64_t OrigOffset = Offset;
  6783. uint64_t TySize = getContext().getTypeSize(Ty);
  6784. uint64_t Align = getContext().getTypeAlign(Ty) / 8;
  6785. Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
  6786. (uint64_t)StackAlignInBytes);
  6787. unsigned CurrOffset = llvm::alignTo(Offset, Align);
  6788. Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
  6789. if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
  6790. // Ignore empty aggregates.
  6791. if (TySize == 0)
  6792. return ABIArgInfo::getIgnore();
  6793. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
  6794. Offset = OrigOffset + MinABIStackAlignInBytes;
  6795. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  6796. }
  6797. // If we have reached here, aggregates are passed directly by coercing to
  6798. // another structure type. Padding is inserted if the offset of the
  6799. // aggregate is unaligned.
  6800. ABIArgInfo ArgInfo =
  6801. ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
  6802. getPaddingType(OrigOffset, CurrOffset));
  6803. ArgInfo.setInReg(true);
  6804. return ArgInfo;
  6805. }
  6806. // Treat an enum type as its underlying type.
  6807. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  6808. Ty = EnumTy->getDecl()->getIntegerType();
  6809. // Make sure we pass indirectly things that are too large.
  6810. if (const auto *EIT = Ty->getAs<BitIntType>())
  6811. if (EIT->getNumBits() > 128 ||
  6812. (EIT->getNumBits() > 64 &&
  6813. !getContext().getTargetInfo().hasInt128Type()))
  6814. return getNaturalAlignIndirect(Ty);
  6815. // All integral types are promoted to the GPR width.
  6816. if (Ty->isIntegralOrEnumerationType())
  6817. return extendType(Ty);
  6818. return ABIArgInfo::getDirect(
  6819. nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
  6820. }
  6821. llvm::Type*
  6822. MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
  6823. const RecordType *RT = RetTy->getAs<RecordType>();
  6824. SmallVector<llvm::Type*, 8> RTList;
  6825. if (RT && RT->isStructureOrClassType()) {
  6826. const RecordDecl *RD = RT->getDecl();
  6827. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  6828. unsigned FieldCnt = Layout.getFieldCount();
  6829. // N32/64 returns struct/classes in floating point registers if the
  6830. // following conditions are met:
  6831. // 1. The size of the struct/class is no larger than 128-bit.
  6832. // 2. The struct/class has one or two fields all of which are floating
  6833. // point types.
  6834. // 3. The offset of the first field is zero (this follows what gcc does).
  6835. //
  6836. // Any other composite results are returned in integer registers.
  6837. //
  6838. if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
  6839. RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
  6840. for (; b != e; ++b) {
  6841. const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
  6842. if (!BT || !BT->isFloatingPoint())
  6843. break;
  6844. RTList.push_back(CGT.ConvertType(b->getType()));
  6845. }
  6846. if (b == e)
  6847. return llvm::StructType::get(getVMContext(), RTList,
  6848. RD->hasAttr<PackedAttr>());
  6849. RTList.clear();
  6850. }
  6851. }
  6852. CoerceToIntArgs(Size, RTList);
  6853. return llvm::StructType::get(getVMContext(), RTList);
  6854. }
  6855. ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
  6856. uint64_t Size = getContext().getTypeSize(RetTy);
  6857. if (RetTy->isVoidType())
  6858. return ABIArgInfo::getIgnore();
  6859. // O32 doesn't treat zero-sized structs differently from other structs.
  6860. // However, N32/N64 ignores zero sized return values.
  6861. if (!IsO32 && Size == 0)
  6862. return ABIArgInfo::getIgnore();
  6863. if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
  6864. if (Size <= 128) {
  6865. if (RetTy->isAnyComplexType())
  6866. return ABIArgInfo::getDirect();
  6867. // O32 returns integer vectors in registers and N32/N64 returns all small
  6868. // aggregates in registers.
  6869. if (!IsO32 ||
  6870. (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
  6871. ABIArgInfo ArgInfo =
  6872. ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
  6873. ArgInfo.setInReg(true);
  6874. return ArgInfo;
  6875. }
  6876. }
  6877. return getNaturalAlignIndirect(RetTy);
  6878. }
  6879. // Treat an enum type as its underlying type.
  6880. if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
  6881. RetTy = EnumTy->getDecl()->getIntegerType();
  6882. // Make sure we pass indirectly things that are too large.
  6883. if (const auto *EIT = RetTy->getAs<BitIntType>())
  6884. if (EIT->getNumBits() > 128 ||
  6885. (EIT->getNumBits() > 64 &&
  6886. !getContext().getTargetInfo().hasInt128Type()))
  6887. return getNaturalAlignIndirect(RetTy);
  6888. if (isPromotableIntegerTypeForABI(RetTy))
  6889. return ABIArgInfo::getExtend(RetTy);
  6890. if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
  6891. RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
  6892. return ABIArgInfo::getSignExtend(RetTy);
  6893. return ABIArgInfo::getDirect();
  6894. }
  6895. void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
  6896. ABIArgInfo &RetInfo = FI.getReturnInfo();
  6897. if (!getCXXABI().classifyReturnType(FI))
  6898. RetInfo = classifyReturnType(FI.getReturnType());
  6899. // Check if a pointer to an aggregate is passed as a hidden argument.
  6900. uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
  6901. for (auto &I : FI.arguments())
  6902. I.info = classifyArgumentType(I.type, Offset);
  6903. }
  6904. Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  6905. QualType OrigTy) const {
  6906. QualType Ty = OrigTy;
  6907. // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
  6908. // Pointers are also promoted in the same way but this only matters for N32.
  6909. unsigned SlotSizeInBits = IsO32 ? 32 : 64;
  6910. unsigned PtrWidth = getTarget().getPointerWidth(0);
  6911. bool DidPromote = false;
  6912. if ((Ty->isIntegerType() &&
  6913. getContext().getIntWidth(Ty) < SlotSizeInBits) ||
  6914. (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
  6915. DidPromote = true;
  6916. Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
  6917. Ty->isSignedIntegerType());
  6918. }
  6919. auto TyInfo = getContext().getTypeInfoInChars(Ty);
  6920. // The alignment of things in the argument area is never larger than
  6921. // StackAlignInBytes.
  6922. TyInfo.Align =
  6923. std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes));
  6924. // MinABIStackAlignInBytes is the size of argument slots on the stack.
  6925. CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
  6926. Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
  6927. TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
  6928. // If there was a promotion, "unpromote" into a temporary.
  6929. // TODO: can we just use a pointer into a subset of the original slot?
  6930. if (DidPromote) {
  6931. Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
  6932. llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
  6933. // Truncate down to the right width.
  6934. llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
  6935. : CGF.IntPtrTy);
  6936. llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
  6937. if (OrigTy->isPointerType())
  6938. V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
  6939. CGF.Builder.CreateStore(V, Temp);
  6940. Addr = Temp;
  6941. }
  6942. return Addr;
  6943. }
  6944. ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
  6945. int TySize = getContext().getTypeSize(Ty);
  6946. // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
  6947. if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
  6948. return ABIArgInfo::getSignExtend(Ty);
  6949. return ABIArgInfo::getExtend(Ty);
  6950. }
  6951. bool
  6952. MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  6953. llvm::Value *Address) const {
  6954. // This information comes from gcc's implementation, which seems to
  6955. // as canonical as it gets.
  6956. // Everything on MIPS is 4 bytes. Double-precision FP registers
  6957. // are aliased to pairs of single-precision FP registers.
  6958. llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
  6959. // 0-31 are the general purpose registers, $0 - $31.
  6960. // 32-63 are the floating-point registers, $f0 - $f31.
  6961. // 64 and 65 are the multiply/divide registers, $hi and $lo.
  6962. // 66 is the (notional, I think) register for signal-handler return.
  6963. AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
  6964. // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
  6965. // They are one bit wide and ignored here.
  6966. // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
  6967. // (coprocessor 1 is the FP unit)
  6968. // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
  6969. // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
  6970. // 176-181 are the DSP accumulator registers.
  6971. AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
  6972. return false;
  6973. }
  6974. //===----------------------------------------------------------------------===//
  6975. // M68k ABI Implementation
  6976. //===----------------------------------------------------------------------===//
  6977. namespace {
  6978. class M68kTargetCodeGenInfo : public TargetCodeGenInfo {
  6979. public:
  6980. M68kTargetCodeGenInfo(CodeGenTypes &CGT)
  6981. : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {}
  6982. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  6983. CodeGen::CodeGenModule &M) const override;
  6984. };
  6985. } // namespace
  6986. void M68kTargetCodeGenInfo::setTargetAttributes(
  6987. const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
  6988. if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  6989. if (const auto *attr = FD->getAttr<M68kInterruptAttr>()) {
  6990. // Handle 'interrupt' attribute:
  6991. llvm::Function *F = cast<llvm::Function>(GV);
  6992. // Step 1: Set ISR calling convention.
  6993. F->setCallingConv(llvm::CallingConv::M68k_INTR);
  6994. // Step 2: Add attributes goodness.
  6995. F->addFnAttr(llvm::Attribute::NoInline);
  6996. // Step 3: Emit ISR vector alias.
  6997. unsigned Num = attr->getNumber() / 2;
  6998. llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
  6999. "__isr_" + Twine(Num), F);
  7000. }
  7001. }
  7002. }
  7003. //===----------------------------------------------------------------------===//
  7004. // AVR ABI Implementation. Documented at
  7005. // https://gcc.gnu.org/wiki/avr-gcc#Calling_Convention
  7006. // https://gcc.gnu.org/wiki/avr-gcc#Reduced_Tiny
  7007. //===----------------------------------------------------------------------===//
  7008. namespace {
  7009. class AVRABIInfo : public DefaultABIInfo {
  7010. private:
  7011. // The total amount of registers can be used to pass parameters. It is 18 on
  7012. // AVR, or 6 on AVRTiny.
  7013. const unsigned ParamRegs;
  7014. // The total amount of registers can be used to pass return value. It is 8 on
  7015. // AVR, or 4 on AVRTiny.
  7016. const unsigned RetRegs;
  7017. public:
  7018. AVRABIInfo(CodeGenTypes &CGT, unsigned NPR, unsigned NRR)
  7019. : DefaultABIInfo(CGT), ParamRegs(NPR), RetRegs(NRR) {}
  7020. ABIArgInfo classifyReturnType(QualType Ty, bool &LargeRet) const {
  7021. if (isAggregateTypeForABI(Ty)) {
  7022. // On AVR, a return struct with size less than or equals to 8 bytes is
  7023. // returned directly via registers R18-R25. On AVRTiny, a return struct
  7024. // with size less than or equals to 4 bytes is returned directly via
  7025. // registers R22-R25.
  7026. if (getContext().getTypeSize(Ty) <= RetRegs * 8)
  7027. return ABIArgInfo::getDirect();
  7028. // A return struct with larger size is returned via a stack
  7029. // slot, along with a pointer to it as the function's implicit argument.
  7030. LargeRet = true;
  7031. return getNaturalAlignIndirect(Ty);
  7032. }
  7033. // Otherwise we follow the default way which is compatible.
  7034. return DefaultABIInfo::classifyReturnType(Ty);
  7035. }
  7036. ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegs) const {
  7037. unsigned TySize = getContext().getTypeSize(Ty);
  7038. // An int8 type argument always costs two registers like an int16.
  7039. if (TySize == 8 && NumRegs >= 2) {
  7040. NumRegs -= 2;
  7041. return ABIArgInfo::getExtend(Ty);
  7042. }
  7043. // If the argument size is an odd number of bytes, round up the size
  7044. // to the next even number.
  7045. TySize = llvm::alignTo(TySize, 16);
  7046. // Any type including an array/struct type can be passed in rgisters,
  7047. // if there are enough registers left.
  7048. if (TySize <= NumRegs * 8) {
  7049. NumRegs -= TySize / 8;
  7050. return ABIArgInfo::getDirect();
  7051. }
  7052. // An argument is passed either completely in registers or completely in
  7053. // memory. Since there are not enough registers left, current argument
  7054. // and all other unprocessed arguments should be passed in memory.
  7055. // However we still need to return `ABIArgInfo::getDirect()` other than
  7056. // `ABIInfo::getNaturalAlignIndirect(Ty)`, otherwise an extra stack slot
  7057. // will be allocated, so the stack frame layout will be incompatible with
  7058. // avr-gcc.
  7059. NumRegs = 0;
  7060. return ABIArgInfo::getDirect();
  7061. }
  7062. void computeInfo(CGFunctionInfo &FI) const override {
  7063. // Decide the return type.
  7064. bool LargeRet = false;
  7065. if (!getCXXABI().classifyReturnType(FI))
  7066. FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), LargeRet);
  7067. // Decide each argument type. The total number of registers can be used for
  7068. // arguments depends on several factors:
  7069. // 1. Arguments of varargs functions are passed on the stack. This applies
  7070. // even to the named arguments. So no register can be used.
  7071. // 2. Total 18 registers can be used on avr and 6 ones on avrtiny.
  7072. // 3. If the return type is a struct with too large size, two registers
  7073. // (out of 18/6) will be cost as an implicit pointer argument.
  7074. unsigned NumRegs = ParamRegs;
  7075. if (FI.isVariadic())
  7076. NumRegs = 0;
  7077. else if (LargeRet)
  7078. NumRegs -= 2;
  7079. for (auto &I : FI.arguments())
  7080. I.info = classifyArgumentType(I.type, NumRegs);
  7081. }
  7082. };
  7083. class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
  7084. public:
  7085. AVRTargetCodeGenInfo(CodeGenTypes &CGT, unsigned NPR, unsigned NRR)
  7086. : TargetCodeGenInfo(std::make_unique<AVRABIInfo>(CGT, NPR, NRR)) {}
  7087. LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
  7088. const VarDecl *D) const override {
  7089. // Check if global/static variable is defined in address space
  7090. // 1~6 (__flash, __flash1, __flash2, __flash3, __flash4, __flash5)
  7091. // but not constant.
  7092. if (D) {
  7093. LangAS AS = D->getType().getAddressSpace();
  7094. if (isTargetAddressSpace(AS) && 1 <= toTargetAddressSpace(AS) &&
  7095. toTargetAddressSpace(AS) <= 6 && !D->getType().isConstQualified())
  7096. CGM.getDiags().Report(D->getLocation(),
  7097. diag::err_verify_nonconst_addrspace)
  7098. << "__flash*";
  7099. }
  7100. return TargetCodeGenInfo::getGlobalVarAddressSpace(CGM, D);
  7101. }
  7102. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  7103. CodeGen::CodeGenModule &CGM) const override {
  7104. if (GV->isDeclaration())
  7105. return;
  7106. const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
  7107. if (!FD) return;
  7108. auto *Fn = cast<llvm::Function>(GV);
  7109. if (FD->getAttr<AVRInterruptAttr>())
  7110. Fn->addFnAttr("interrupt");
  7111. if (FD->getAttr<AVRSignalAttr>())
  7112. Fn->addFnAttr("signal");
  7113. }
  7114. };
  7115. }
  7116. //===----------------------------------------------------------------------===//
  7117. // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
  7118. // Currently subclassed only to implement custom OpenCL C function attribute
  7119. // handling.
  7120. //===----------------------------------------------------------------------===//
  7121. namespace {
  7122. class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
  7123. public:
  7124. TCETargetCodeGenInfo(CodeGenTypes &CGT)
  7125. : DefaultTargetCodeGenInfo(CGT) {}
  7126. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  7127. CodeGen::CodeGenModule &M) const override;
  7128. };
  7129. void TCETargetCodeGenInfo::setTargetAttributes(
  7130. const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
  7131. if (GV->isDeclaration())
  7132. return;
  7133. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
  7134. if (!FD) return;
  7135. llvm::Function *F = cast<llvm::Function>(GV);
  7136. if (M.getLangOpts().OpenCL) {
  7137. if (FD->hasAttr<OpenCLKernelAttr>()) {
  7138. // OpenCL C Kernel functions are not subject to inlining
  7139. F->addFnAttr(llvm::Attribute::NoInline);
  7140. const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
  7141. if (Attr) {
  7142. // Convert the reqd_work_group_size() attributes to metadata.
  7143. llvm::LLVMContext &Context = F->getContext();
  7144. llvm::NamedMDNode *OpenCLMetadata =
  7145. M.getModule().getOrInsertNamedMetadata(
  7146. "opencl.kernel_wg_size_info");
  7147. SmallVector<llvm::Metadata *, 5> Operands;
  7148. Operands.push_back(llvm::ConstantAsMetadata::get(F));
  7149. Operands.push_back(
  7150. llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
  7151. M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
  7152. Operands.push_back(
  7153. llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
  7154. M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
  7155. Operands.push_back(
  7156. llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
  7157. M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
  7158. // Add a boolean constant operand for "required" (true) or "hint"
  7159. // (false) for implementing the work_group_size_hint attr later.
  7160. // Currently always true as the hint is not yet implemented.
  7161. Operands.push_back(
  7162. llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
  7163. OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
  7164. }
  7165. }
  7166. }
  7167. }
  7168. }
  7169. //===----------------------------------------------------------------------===//
  7170. // Hexagon ABI Implementation
  7171. //===----------------------------------------------------------------------===//
  7172. namespace {
  7173. class HexagonABIInfo : public DefaultABIInfo {
  7174. public:
  7175. HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
  7176. private:
  7177. ABIArgInfo classifyReturnType(QualType RetTy) const;
  7178. ABIArgInfo classifyArgumentType(QualType RetTy) const;
  7179. ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const;
  7180. void computeInfo(CGFunctionInfo &FI) const override;
  7181. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  7182. QualType Ty) const override;
  7183. Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr,
  7184. QualType Ty) const;
  7185. Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr,
  7186. QualType Ty) const;
  7187. Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr,
  7188. QualType Ty) const;
  7189. };
  7190. class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
  7191. public:
  7192. HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
  7193. : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {}
  7194. int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
  7195. return 29;
  7196. }
  7197. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  7198. CodeGen::CodeGenModule &GCM) const override {
  7199. if (GV->isDeclaration())
  7200. return;
  7201. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
  7202. if (!FD)
  7203. return;
  7204. }
  7205. };
  7206. } // namespace
  7207. void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
  7208. unsigned RegsLeft = 6;
  7209. if (!getCXXABI().classifyReturnType(FI))
  7210. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  7211. for (auto &I : FI.arguments())
  7212. I.info = classifyArgumentType(I.type, &RegsLeft);
  7213. }
  7214. static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) {
  7215. assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits"
  7216. " through registers");
  7217. if (*RegsLeft == 0)
  7218. return false;
  7219. if (Size <= 32) {
  7220. (*RegsLeft)--;
  7221. return true;
  7222. }
  7223. if (2 <= (*RegsLeft & (~1U))) {
  7224. *RegsLeft = (*RegsLeft & (~1U)) - 2;
  7225. return true;
  7226. }
  7227. // Next available register was r5 but candidate was greater than 32-bits so it
  7228. // has to go on the stack. However we still consume r5
  7229. if (*RegsLeft == 1)
  7230. *RegsLeft = 0;
  7231. return false;
  7232. }
  7233. ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty,
  7234. unsigned *RegsLeft) const {
  7235. if (!isAggregateTypeForABI(Ty)) {
  7236. // Treat an enum type as its underlying type.
  7237. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  7238. Ty = EnumTy->getDecl()->getIntegerType();
  7239. uint64_t Size = getContext().getTypeSize(Ty);
  7240. if (Size <= 64)
  7241. HexagonAdjustRegsLeft(Size, RegsLeft);
  7242. if (Size > 64 && Ty->isBitIntType())
  7243. return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
  7244. return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
  7245. : ABIArgInfo::getDirect();
  7246. }
  7247. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
  7248. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  7249. // Ignore empty records.
  7250. if (isEmptyRecord(getContext(), Ty, true))
  7251. return ABIArgInfo::getIgnore();
  7252. uint64_t Size = getContext().getTypeSize(Ty);
  7253. unsigned Align = getContext().getTypeAlign(Ty);
  7254. if (Size > 64)
  7255. return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
  7256. if (HexagonAdjustRegsLeft(Size, RegsLeft))
  7257. Align = Size <= 32 ? 32 : 64;
  7258. if (Size <= Align) {
  7259. // Pass in the smallest viable integer type.
  7260. if (!llvm::isPowerOf2_64(Size))
  7261. Size = llvm::NextPowerOf2(Size);
  7262. return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
  7263. }
  7264. return DefaultABIInfo::classifyArgumentType(Ty);
  7265. }
  7266. ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
  7267. if (RetTy->isVoidType())
  7268. return ABIArgInfo::getIgnore();
  7269. const TargetInfo &T = CGT.getTarget();
  7270. uint64_t Size = getContext().getTypeSize(RetTy);
  7271. if (RetTy->getAs<VectorType>()) {
  7272. // HVX vectors are returned in vector registers or register pairs.
  7273. if (T.hasFeature("hvx")) {
  7274. assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b"));
  7275. uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8;
  7276. if (Size == VecSize || Size == 2*VecSize)
  7277. return ABIArgInfo::getDirectInReg();
  7278. }
  7279. // Large vector types should be returned via memory.
  7280. if (Size > 64)
  7281. return getNaturalAlignIndirect(RetTy);
  7282. }
  7283. if (!isAggregateTypeForABI(RetTy)) {
  7284. // Treat an enum type as its underlying type.
  7285. if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
  7286. RetTy = EnumTy->getDecl()->getIntegerType();
  7287. if (Size > 64 && RetTy->isBitIntType())
  7288. return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
  7289. return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
  7290. : ABIArgInfo::getDirect();
  7291. }
  7292. if (isEmptyRecord(getContext(), RetTy, true))
  7293. return ABIArgInfo::getIgnore();
  7294. // Aggregates <= 8 bytes are returned in registers, other aggregates
  7295. // are returned indirectly.
  7296. if (Size <= 64) {
  7297. // Return in the smallest viable integer type.
  7298. if (!llvm::isPowerOf2_64(Size))
  7299. Size = llvm::NextPowerOf2(Size);
  7300. return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size));
  7301. }
  7302. return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
  7303. }
  7304. Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF,
  7305. Address VAListAddr,
  7306. QualType Ty) const {
  7307. // Load the overflow area pointer.
  7308. Address __overflow_area_pointer_p =
  7309. CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
  7310. llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
  7311. __overflow_area_pointer_p, "__overflow_area_pointer");
  7312. uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
  7313. if (Align > 4) {
  7314. // Alignment should be a power of 2.
  7315. assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!");
  7316. // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
  7317. llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
  7318. // Add offset to the current pointer to access the argument.
  7319. __overflow_area_pointer =
  7320. CGF.Builder.CreateGEP(CGF.Int8Ty, __overflow_area_pointer, Offset);
  7321. llvm::Value *AsInt =
  7322. CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
  7323. // Create a mask which should be "AND"ed
  7324. // with (overflow_arg_area + align - 1)
  7325. llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align);
  7326. __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
  7327. CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(),
  7328. "__overflow_area_pointer.align");
  7329. }
  7330. // Get the type of the argument from memory and bitcast
  7331. // overflow area pointer to the argument type.
  7332. llvm::Type *PTy = CGF.ConvertTypeForMem(Ty);
  7333. Address AddrTyped = CGF.Builder.CreateBitCast(
  7334. Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)),
  7335. llvm::PointerType::getUnqual(PTy));
  7336. // Round up to the minimum stack alignment for varargs which is 4 bytes.
  7337. uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
  7338. __overflow_area_pointer = CGF.Builder.CreateGEP(
  7339. CGF.Int8Ty, __overflow_area_pointer,
  7340. llvm::ConstantInt::get(CGF.Int32Ty, Offset),
  7341. "__overflow_area_pointer.next");
  7342. CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p);
  7343. return AddrTyped;
  7344. }
  7345. Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF,
  7346. Address VAListAddr,
  7347. QualType Ty) const {
  7348. // FIXME: Need to handle alignment
  7349. llvm::Type *BP = CGF.Int8PtrTy;
  7350. llvm::Type *BPP = CGF.Int8PtrPtrTy;
  7351. CGBuilderTy &Builder = CGF.Builder;
  7352. Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
  7353. llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
  7354. // Handle address alignment for type alignment > 32 bits
  7355. uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
  7356. if (TyAlign > 4) {
  7357. assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!");
  7358. llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
  7359. AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
  7360. AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
  7361. Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
  7362. }
  7363. llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
  7364. Address AddrTyped = Builder.CreateBitCast(
  7365. Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy);
  7366. uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4);
  7367. llvm::Value *NextAddr = Builder.CreateGEP(
  7368. CGF.Int8Ty, Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
  7369. Builder.CreateStore(NextAddr, VAListAddrAsBPP);
  7370. return AddrTyped;
  7371. }
  7372. Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF,
  7373. Address VAListAddr,
  7374. QualType Ty) const {
  7375. int ArgSize = CGF.getContext().getTypeSize(Ty) / 8;
  7376. if (ArgSize > 8)
  7377. return EmitVAArgFromMemory(CGF, VAListAddr, Ty);
  7378. // Here we have check if the argument is in register area or
  7379. // in overflow area.
  7380. // If the saved register area pointer + argsize rounded up to alignment >
  7381. // saved register area end pointer, argument is in overflow area.
  7382. unsigned RegsLeft = 6;
  7383. Ty = CGF.getContext().getCanonicalType(Ty);
  7384. (void)classifyArgumentType(Ty, &RegsLeft);
  7385. llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
  7386. llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
  7387. llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
  7388. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
  7389. // Get rounded size of the argument.GCC does not allow vararg of
  7390. // size < 4 bytes. We follow the same logic here.
  7391. ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
  7392. int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8;
  7393. // Argument may be in saved register area
  7394. CGF.EmitBlock(MaybeRegBlock);
  7395. // Load the current saved register area pointer.
  7396. Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP(
  7397. VAListAddr, 0, "__current_saved_reg_area_pointer_p");
  7398. llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad(
  7399. __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer");
  7400. // Load the saved register area end pointer.
  7401. Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP(
  7402. VAListAddr, 1, "__saved_reg_area_end_pointer_p");
  7403. llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad(
  7404. __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer");
  7405. // If the size of argument is > 4 bytes, check if the stack
  7406. // location is aligned to 8 bytes
  7407. if (ArgAlign > 4) {
  7408. llvm::Value *__current_saved_reg_area_pointer_int =
  7409. CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer,
  7410. CGF.Int32Ty);
  7411. __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd(
  7412. __current_saved_reg_area_pointer_int,
  7413. llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)),
  7414. "align_current_saved_reg_area_pointer");
  7415. __current_saved_reg_area_pointer_int =
  7416. CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int,
  7417. llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
  7418. "align_current_saved_reg_area_pointer");
  7419. __current_saved_reg_area_pointer =
  7420. CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int,
  7421. __current_saved_reg_area_pointer->getType(),
  7422. "align_current_saved_reg_area_pointer");
  7423. }
  7424. llvm::Value *__new_saved_reg_area_pointer =
  7425. CGF.Builder.CreateGEP(CGF.Int8Ty, __current_saved_reg_area_pointer,
  7426. llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
  7427. "__new_saved_reg_area_pointer");
  7428. llvm::Value *UsingStack = nullptr;
  7429. UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer,
  7430. __saved_reg_area_end_pointer);
  7431. CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock);
  7432. // Argument in saved register area
  7433. // Implement the block where argument is in register saved area
  7434. CGF.EmitBlock(InRegBlock);
  7435. llvm::Type *PTy = CGF.ConvertType(Ty);
  7436. llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast(
  7437. __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy));
  7438. CGF.Builder.CreateStore(__new_saved_reg_area_pointer,
  7439. __current_saved_reg_area_pointer_p);
  7440. CGF.EmitBranch(ContBlock);
  7441. // Argument in overflow area
  7442. // Implement the block where the argument is in overflow area.
  7443. CGF.EmitBlock(OnStackBlock);
  7444. // Load the overflow area pointer
  7445. Address __overflow_area_pointer_p =
  7446. CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p");
  7447. llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad(
  7448. __overflow_area_pointer_p, "__overflow_area_pointer");
  7449. // Align the overflow area pointer according to the alignment of the argument
  7450. if (ArgAlign > 4) {
  7451. llvm::Value *__overflow_area_pointer_int =
  7452. CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty);
  7453. __overflow_area_pointer_int =
  7454. CGF.Builder.CreateAdd(__overflow_area_pointer_int,
  7455. llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1),
  7456. "align_overflow_area_pointer");
  7457. __overflow_area_pointer_int =
  7458. CGF.Builder.CreateAnd(__overflow_area_pointer_int,
  7459. llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign),
  7460. "align_overflow_area_pointer");
  7461. __overflow_area_pointer = CGF.Builder.CreateIntToPtr(
  7462. __overflow_area_pointer_int, __overflow_area_pointer->getType(),
  7463. "align_overflow_area_pointer");
  7464. }
  7465. // Get the pointer for next argument in overflow area and store it
  7466. // to overflow area pointer.
  7467. llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP(
  7468. CGF.Int8Ty, __overflow_area_pointer,
  7469. llvm::ConstantInt::get(CGF.Int32Ty, ArgSize),
  7470. "__overflow_area_pointer.next");
  7471. CGF.Builder.CreateStore(__new_overflow_area_pointer,
  7472. __overflow_area_pointer_p);
  7473. CGF.Builder.CreateStore(__new_overflow_area_pointer,
  7474. __current_saved_reg_area_pointer_p);
  7475. // Bitcast the overflow area pointer to the type of argument.
  7476. llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty);
  7477. llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast(
  7478. __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy));
  7479. CGF.EmitBranch(ContBlock);
  7480. // Get the correct pointer to load the variable argument
  7481. // Implement the ContBlock
  7482. CGF.EmitBlock(ContBlock);
  7483. llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
  7484. llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr");
  7485. ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock);
  7486. ArgAddr->addIncoming(__overflow_area_p, OnStackBlock);
  7487. return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign));
  7488. }
  7489. Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  7490. QualType Ty) const {
  7491. if (getTarget().getTriple().isMusl())
  7492. return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty);
  7493. return EmitVAArgForHexagon(CGF, VAListAddr, Ty);
  7494. }
  7495. //===----------------------------------------------------------------------===//
  7496. // Lanai ABI Implementation
  7497. //===----------------------------------------------------------------------===//
  7498. namespace {
  7499. class LanaiABIInfo : public DefaultABIInfo {
  7500. public:
  7501. LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
  7502. bool shouldUseInReg(QualType Ty, CCState &State) const;
  7503. void computeInfo(CGFunctionInfo &FI) const override {
  7504. CCState State(FI);
  7505. // Lanai uses 4 registers to pass arguments unless the function has the
  7506. // regparm attribute set.
  7507. if (FI.getHasRegParm()) {
  7508. State.FreeRegs = FI.getRegParm();
  7509. } else {
  7510. State.FreeRegs = 4;
  7511. }
  7512. if (!getCXXABI().classifyReturnType(FI))
  7513. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  7514. for (auto &I : FI.arguments())
  7515. I.info = classifyArgumentType(I.type, State);
  7516. }
  7517. ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
  7518. ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
  7519. };
  7520. } // end anonymous namespace
  7521. bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
  7522. unsigned Size = getContext().getTypeSize(Ty);
  7523. unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
  7524. if (SizeInRegs == 0)
  7525. return false;
  7526. if (SizeInRegs > State.FreeRegs) {
  7527. State.FreeRegs = 0;
  7528. return false;
  7529. }
  7530. State.FreeRegs -= SizeInRegs;
  7531. return true;
  7532. }
  7533. ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
  7534. CCState &State) const {
  7535. if (!ByVal) {
  7536. if (State.FreeRegs) {
  7537. --State.FreeRegs; // Non-byval indirects just use one pointer.
  7538. return getNaturalAlignIndirectInReg(Ty);
  7539. }
  7540. return getNaturalAlignIndirect(Ty, false);
  7541. }
  7542. // Compute the byval alignment.
  7543. const unsigned MinABIStackAlignInBytes = 4;
  7544. unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
  7545. return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
  7546. /*Realign=*/TypeAlign >
  7547. MinABIStackAlignInBytes);
  7548. }
  7549. ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
  7550. CCState &State) const {
  7551. // Check with the C++ ABI first.
  7552. const RecordType *RT = Ty->getAs<RecordType>();
  7553. if (RT) {
  7554. CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
  7555. if (RAA == CGCXXABI::RAA_Indirect) {
  7556. return getIndirectResult(Ty, /*ByVal=*/false, State);
  7557. } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
  7558. return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
  7559. }
  7560. }
  7561. if (isAggregateTypeForABI(Ty)) {
  7562. // Structures with flexible arrays are always indirect.
  7563. if (RT && RT->getDecl()->hasFlexibleArrayMember())
  7564. return getIndirectResult(Ty, /*ByVal=*/true, State);
  7565. // Ignore empty structs/unions.
  7566. if (isEmptyRecord(getContext(), Ty, true))
  7567. return ABIArgInfo::getIgnore();
  7568. llvm::LLVMContext &LLVMContext = getVMContext();
  7569. unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
  7570. if (SizeInRegs <= State.FreeRegs) {
  7571. llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
  7572. SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
  7573. llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
  7574. State.FreeRegs -= SizeInRegs;
  7575. return ABIArgInfo::getDirectInReg(Result);
  7576. } else {
  7577. State.FreeRegs = 0;
  7578. }
  7579. return getIndirectResult(Ty, true, State);
  7580. }
  7581. // Treat an enum type as its underlying type.
  7582. if (const auto *EnumTy = Ty->getAs<EnumType>())
  7583. Ty = EnumTy->getDecl()->getIntegerType();
  7584. bool InReg = shouldUseInReg(Ty, State);
  7585. // Don't pass >64 bit integers in registers.
  7586. if (const auto *EIT = Ty->getAs<BitIntType>())
  7587. if (EIT->getNumBits() > 64)
  7588. return getIndirectResult(Ty, /*ByVal=*/true, State);
  7589. if (isPromotableIntegerTypeForABI(Ty)) {
  7590. if (InReg)
  7591. return ABIArgInfo::getDirectInReg();
  7592. return ABIArgInfo::getExtend(Ty);
  7593. }
  7594. if (InReg)
  7595. return ABIArgInfo::getDirectInReg();
  7596. return ABIArgInfo::getDirect();
  7597. }
  7598. namespace {
  7599. class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
  7600. public:
  7601. LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
  7602. : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {}
  7603. };
  7604. }
  7605. //===----------------------------------------------------------------------===//
  7606. // AMDGPU ABI Implementation
  7607. //===----------------------------------------------------------------------===//
  7608. namespace {
  7609. class AMDGPUABIInfo final : public DefaultABIInfo {
  7610. private:
  7611. static const unsigned MaxNumRegsForArgsRet = 16;
  7612. unsigned numRegsForType(QualType Ty) const;
  7613. bool isHomogeneousAggregateBaseType(QualType Ty) const override;
  7614. bool isHomogeneousAggregateSmallEnough(const Type *Base,
  7615. uint64_t Members) const override;
  7616. // Coerce HIP scalar pointer arguments from generic pointers to global ones.
  7617. llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
  7618. unsigned ToAS) const {
  7619. // Single value types.
  7620. auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(Ty);
  7621. if (PtrTy && PtrTy->getAddressSpace() == FromAS)
  7622. return llvm::PointerType::getWithSamePointeeType(PtrTy, ToAS);
  7623. return Ty;
  7624. }
  7625. public:
  7626. explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
  7627. DefaultABIInfo(CGT) {}
  7628. ABIArgInfo classifyReturnType(QualType RetTy) const;
  7629. ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
  7630. ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
  7631. void computeInfo(CGFunctionInfo &FI) const override;
  7632. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  7633. QualType Ty) const override;
  7634. };
  7635. bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
  7636. return true;
  7637. }
  7638. bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
  7639. const Type *Base, uint64_t Members) const {
  7640. uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
  7641. // Homogeneous Aggregates may occupy at most 16 registers.
  7642. return Members * NumRegs <= MaxNumRegsForArgsRet;
  7643. }
  7644. /// Estimate number of registers the type will use when passed in registers.
  7645. unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
  7646. unsigned NumRegs = 0;
  7647. if (const VectorType *VT = Ty->getAs<VectorType>()) {
  7648. // Compute from the number of elements. The reported size is based on the
  7649. // in-memory size, which includes the padding 4th element for 3-vectors.
  7650. QualType EltTy = VT->getElementType();
  7651. unsigned EltSize = getContext().getTypeSize(EltTy);
  7652. // 16-bit element vectors should be passed as packed.
  7653. if (EltSize == 16)
  7654. return (VT->getNumElements() + 1) / 2;
  7655. unsigned EltNumRegs = (EltSize + 31) / 32;
  7656. return EltNumRegs * VT->getNumElements();
  7657. }
  7658. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  7659. const RecordDecl *RD = RT->getDecl();
  7660. assert(!RD->hasFlexibleArrayMember());
  7661. for (const FieldDecl *Field : RD->fields()) {
  7662. QualType FieldTy = Field->getType();
  7663. NumRegs += numRegsForType(FieldTy);
  7664. }
  7665. return NumRegs;
  7666. }
  7667. return (getContext().getTypeSize(Ty) + 31) / 32;
  7668. }
  7669. void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
  7670. llvm::CallingConv::ID CC = FI.getCallingConvention();
  7671. if (!getCXXABI().classifyReturnType(FI))
  7672. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  7673. unsigned NumRegsLeft = MaxNumRegsForArgsRet;
  7674. for (auto &Arg : FI.arguments()) {
  7675. if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
  7676. Arg.info = classifyKernelArgumentType(Arg.type);
  7677. } else {
  7678. Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
  7679. }
  7680. }
  7681. }
  7682. Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  7683. QualType Ty) const {
  7684. llvm_unreachable("AMDGPU does not support varargs");
  7685. }
  7686. ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
  7687. if (isAggregateTypeForABI(RetTy)) {
  7688. // Records with non-trivial destructors/copy-constructors should not be
  7689. // returned by value.
  7690. if (!getRecordArgABI(RetTy, getCXXABI())) {
  7691. // Ignore empty structs/unions.
  7692. if (isEmptyRecord(getContext(), RetTy, true))
  7693. return ABIArgInfo::getIgnore();
  7694. // Lower single-element structs to just return a regular value.
  7695. if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
  7696. return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
  7697. if (const RecordType *RT = RetTy->getAs<RecordType>()) {
  7698. const RecordDecl *RD = RT->getDecl();
  7699. if (RD->hasFlexibleArrayMember())
  7700. return DefaultABIInfo::classifyReturnType(RetTy);
  7701. }
  7702. // Pack aggregates <= 4 bytes into single VGPR or pair.
  7703. uint64_t Size = getContext().getTypeSize(RetTy);
  7704. if (Size <= 16)
  7705. return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
  7706. if (Size <= 32)
  7707. return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
  7708. if (Size <= 64) {
  7709. llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
  7710. return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
  7711. }
  7712. if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
  7713. return ABIArgInfo::getDirect();
  7714. }
  7715. }
  7716. // Otherwise just do the default thing.
  7717. return DefaultABIInfo::classifyReturnType(RetTy);
  7718. }
  7719. /// For kernels all parameters are really passed in a special buffer. It doesn't
  7720. /// make sense to pass anything byval, so everything must be direct.
  7721. ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
  7722. Ty = useFirstFieldIfTransparentUnion(Ty);
  7723. // TODO: Can we omit empty structs?
  7724. if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
  7725. Ty = QualType(SeltTy, 0);
  7726. llvm::Type *OrigLTy = CGT.ConvertType(Ty);
  7727. llvm::Type *LTy = OrigLTy;
  7728. if (getContext().getLangOpts().HIP) {
  7729. LTy = coerceKernelArgumentType(
  7730. OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
  7731. /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
  7732. }
  7733. // FIXME: Should also use this for OpenCL, but it requires addressing the
  7734. // problem of kernels being called.
  7735. //
  7736. // FIXME: This doesn't apply the optimization of coercing pointers in structs
  7737. // to global address space when using byref. This would require implementing a
  7738. // new kind of coercion of the in-memory type when for indirect arguments.
  7739. if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy &&
  7740. isAggregateTypeForABI(Ty)) {
  7741. return ABIArgInfo::getIndirectAliased(
  7742. getContext().getTypeAlignInChars(Ty),
  7743. getContext().getTargetAddressSpace(LangAS::opencl_constant),
  7744. false /*Realign*/, nullptr /*Padding*/);
  7745. }
  7746. // If we set CanBeFlattened to true, CodeGen will expand the struct to its
  7747. // individual elements, which confuses the Clover OpenCL backend; therefore we
  7748. // have to set it to false here. Other args of getDirect() are just defaults.
  7749. return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
  7750. }
  7751. ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
  7752. unsigned &NumRegsLeft) const {
  7753. assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
  7754. Ty = useFirstFieldIfTransparentUnion(Ty);
  7755. if (isAggregateTypeForABI(Ty)) {
  7756. // Records with non-trivial destructors/copy-constructors should not be
  7757. // passed by value.
  7758. if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
  7759. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  7760. // Ignore empty structs/unions.
  7761. if (isEmptyRecord(getContext(), Ty, true))
  7762. return ABIArgInfo::getIgnore();
  7763. // Lower single-element structs to just pass a regular value. TODO: We
  7764. // could do reasonable-size multiple-element structs too, using getExpand(),
  7765. // though watch out for things like bitfields.
  7766. if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
  7767. return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
  7768. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  7769. const RecordDecl *RD = RT->getDecl();
  7770. if (RD->hasFlexibleArrayMember())
  7771. return DefaultABIInfo::classifyArgumentType(Ty);
  7772. }
  7773. // Pack aggregates <= 8 bytes into single VGPR or pair.
  7774. uint64_t Size = getContext().getTypeSize(Ty);
  7775. if (Size <= 64) {
  7776. unsigned NumRegs = (Size + 31) / 32;
  7777. NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
  7778. if (Size <= 16)
  7779. return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
  7780. if (Size <= 32)
  7781. return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
  7782. // XXX: Should this be i64 instead, and should the limit increase?
  7783. llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
  7784. return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
  7785. }
  7786. if (NumRegsLeft > 0) {
  7787. unsigned NumRegs = numRegsForType(Ty);
  7788. if (NumRegsLeft >= NumRegs) {
  7789. NumRegsLeft -= NumRegs;
  7790. return ABIArgInfo::getDirect();
  7791. }
  7792. }
  7793. }
  7794. // Otherwise just do the default thing.
  7795. ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
  7796. if (!ArgInfo.isIndirect()) {
  7797. unsigned NumRegs = numRegsForType(Ty);
  7798. NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
  7799. }
  7800. return ArgInfo;
  7801. }
  7802. class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
  7803. public:
  7804. AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
  7805. : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {}
  7806. void setFunctionDeclAttributes(const FunctionDecl *FD, llvm::Function *F,
  7807. CodeGenModule &CGM) const;
  7808. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  7809. CodeGen::CodeGenModule &M) const override;
  7810. unsigned getOpenCLKernelCallingConv() const override;
  7811. llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
  7812. llvm::PointerType *T, QualType QT) const override;
  7813. LangAS getASTAllocaAddressSpace() const override {
  7814. return getLangASFromTargetAS(
  7815. getABIInfo().getDataLayout().getAllocaAddrSpace());
  7816. }
  7817. LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
  7818. const VarDecl *D) const override;
  7819. llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
  7820. SyncScope Scope,
  7821. llvm::AtomicOrdering Ordering,
  7822. llvm::LLVMContext &Ctx) const override;
  7823. llvm::Function *
  7824. createEnqueuedBlockKernel(CodeGenFunction &CGF,
  7825. llvm::Function *BlockInvokeFunc,
  7826. llvm::Value *BlockLiteral) const override;
  7827. bool shouldEmitStaticExternCAliases() const override;
  7828. void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
  7829. };
  7830. }
  7831. static bool requiresAMDGPUProtectedVisibility(const Decl *D,
  7832. llvm::GlobalValue *GV) {
  7833. if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
  7834. return false;
  7835. return D->hasAttr<OpenCLKernelAttr>() ||
  7836. (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
  7837. (isa<VarDecl>(D) &&
  7838. (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
  7839. cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() ||
  7840. cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType()));
  7841. }
  7842. void AMDGPUTargetCodeGenInfo::setFunctionDeclAttributes(
  7843. const FunctionDecl *FD, llvm::Function *F, CodeGenModule &M) const {
  7844. const auto *ReqdWGS =
  7845. M.getLangOpts().OpenCL ? FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
  7846. const bool IsOpenCLKernel =
  7847. M.getLangOpts().OpenCL && FD->hasAttr<OpenCLKernelAttr>();
  7848. const bool IsHIPKernel = M.getLangOpts().HIP && FD->hasAttr<CUDAGlobalAttr>();
  7849. const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
  7850. if (ReqdWGS || FlatWGS) {
  7851. unsigned Min = 0;
  7852. unsigned Max = 0;
  7853. if (FlatWGS) {
  7854. Min = FlatWGS->getMin()
  7855. ->EvaluateKnownConstInt(M.getContext())
  7856. .getExtValue();
  7857. Max = FlatWGS->getMax()
  7858. ->EvaluateKnownConstInt(M.getContext())
  7859. .getExtValue();
  7860. }
  7861. if (ReqdWGS && Min == 0 && Max == 0)
  7862. Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
  7863. if (Min != 0) {
  7864. assert(Min <= Max && "Min must be less than or equal Max");
  7865. std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
  7866. F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
  7867. } else
  7868. assert(Max == 0 && "Max must be zero");
  7869. } else if (IsOpenCLKernel || IsHIPKernel) {
  7870. // By default, restrict the maximum size to a value specified by
  7871. // --gpu-max-threads-per-block=n or its default value for HIP.
  7872. const unsigned OpenCLDefaultMaxWorkGroupSize = 256;
  7873. const unsigned DefaultMaxWorkGroupSize =
  7874. IsOpenCLKernel ? OpenCLDefaultMaxWorkGroupSize
  7875. : M.getLangOpts().GPUMaxThreadsPerBlock;
  7876. std::string AttrVal =
  7877. std::string("1,") + llvm::utostr(DefaultMaxWorkGroupSize);
  7878. F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
  7879. }
  7880. if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
  7881. unsigned Min =
  7882. Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
  7883. unsigned Max = Attr->getMax() ? Attr->getMax()
  7884. ->EvaluateKnownConstInt(M.getContext())
  7885. .getExtValue()
  7886. : 0;
  7887. if (Min != 0) {
  7888. assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
  7889. std::string AttrVal = llvm::utostr(Min);
  7890. if (Max != 0)
  7891. AttrVal = AttrVal + "," + llvm::utostr(Max);
  7892. F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
  7893. } else
  7894. assert(Max == 0 && "Max must be zero");
  7895. }
  7896. if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
  7897. unsigned NumSGPR = Attr->getNumSGPR();
  7898. if (NumSGPR != 0)
  7899. F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
  7900. }
  7901. if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
  7902. uint32_t NumVGPR = Attr->getNumVGPR();
  7903. if (NumVGPR != 0)
  7904. F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
  7905. }
  7906. }
  7907. void AMDGPUTargetCodeGenInfo::setTargetAttributes(
  7908. const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
  7909. if (requiresAMDGPUProtectedVisibility(D, GV)) {
  7910. GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
  7911. GV->setDSOLocal(true);
  7912. }
  7913. if (GV->isDeclaration())
  7914. return;
  7915. llvm::Function *F = dyn_cast<llvm::Function>(GV);
  7916. if (!F)
  7917. return;
  7918. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
  7919. if (FD)
  7920. setFunctionDeclAttributes(FD, F, M);
  7921. const bool IsHIPKernel =
  7922. M.getLangOpts().HIP && FD && FD->hasAttr<CUDAGlobalAttr>();
  7923. if (IsHIPKernel)
  7924. F->addFnAttr("uniform-work-group-size", "true");
  7925. if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics())
  7926. F->addFnAttr("amdgpu-unsafe-fp-atomics", "true");
  7927. if (!getABIInfo().getCodeGenOpts().EmitIEEENaNCompliantInsts)
  7928. F->addFnAttr("amdgpu-ieee", "false");
  7929. }
  7930. unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
  7931. return llvm::CallingConv::AMDGPU_KERNEL;
  7932. }
  7933. // Currently LLVM assumes null pointers always have value 0,
  7934. // which results in incorrectly transformed IR. Therefore, instead of
  7935. // emitting null pointers in private and local address spaces, a null
  7936. // pointer in generic address space is emitted which is casted to a
  7937. // pointer in local or private address space.
  7938. llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
  7939. const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
  7940. QualType QT) const {
  7941. if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
  7942. return llvm::ConstantPointerNull::get(PT);
  7943. auto &Ctx = CGM.getContext();
  7944. auto NPT = llvm::PointerType::getWithSamePointeeType(
  7945. PT, Ctx.getTargetAddressSpace(LangAS::opencl_generic));
  7946. return llvm::ConstantExpr::getAddrSpaceCast(
  7947. llvm::ConstantPointerNull::get(NPT), PT);
  7948. }
  7949. LangAS
  7950. AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
  7951. const VarDecl *D) const {
  7952. assert(!CGM.getLangOpts().OpenCL &&
  7953. !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
  7954. "Address space agnostic languages only");
  7955. LangAS DefaultGlobalAS = getLangASFromTargetAS(
  7956. CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
  7957. if (!D)
  7958. return DefaultGlobalAS;
  7959. LangAS AddrSpace = D->getType().getAddressSpace();
  7960. assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
  7961. if (AddrSpace != LangAS::Default)
  7962. return AddrSpace;
  7963. // Only promote to address space 4 if VarDecl has constant initialization.
  7964. if (CGM.isTypeConstant(D->getType(), false) &&
  7965. D->hasConstantInitialization()) {
  7966. if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
  7967. return ConstAS.getValue();
  7968. }
  7969. return DefaultGlobalAS;
  7970. }
  7971. llvm::SyncScope::ID
  7972. AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
  7973. SyncScope Scope,
  7974. llvm::AtomicOrdering Ordering,
  7975. llvm::LLVMContext &Ctx) const {
  7976. std::string Name;
  7977. switch (Scope) {
  7978. case SyncScope::HIPSingleThread:
  7979. Name = "singlethread";
  7980. break;
  7981. case SyncScope::HIPWavefront:
  7982. case SyncScope::OpenCLSubGroup:
  7983. Name = "wavefront";
  7984. break;
  7985. case SyncScope::HIPWorkgroup:
  7986. case SyncScope::OpenCLWorkGroup:
  7987. Name = "workgroup";
  7988. break;
  7989. case SyncScope::HIPAgent:
  7990. case SyncScope::OpenCLDevice:
  7991. Name = "agent";
  7992. break;
  7993. case SyncScope::HIPSystem:
  7994. case SyncScope::OpenCLAllSVMDevices:
  7995. Name = "";
  7996. break;
  7997. }
  7998. if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
  7999. if (!Name.empty())
  8000. Name = Twine(Twine(Name) + Twine("-")).str();
  8001. Name = Twine(Twine(Name) + Twine("one-as")).str();
  8002. }
  8003. return Ctx.getOrInsertSyncScopeID(Name);
  8004. }
  8005. bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
  8006. return false;
  8007. }
  8008. void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
  8009. const FunctionType *&FT) const {
  8010. FT = getABIInfo().getContext().adjustFunctionType(
  8011. FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
  8012. }
  8013. //===----------------------------------------------------------------------===//
  8014. // SPARC v8 ABI Implementation.
  8015. // Based on the SPARC Compliance Definition version 2.4.1.
  8016. //
  8017. // Ensures that complex values are passed in registers.
  8018. //
  8019. namespace {
  8020. class SparcV8ABIInfo : public DefaultABIInfo {
  8021. public:
  8022. SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
  8023. private:
  8024. ABIArgInfo classifyReturnType(QualType RetTy) const;
  8025. void computeInfo(CGFunctionInfo &FI) const override;
  8026. };
  8027. } // end anonymous namespace
  8028. ABIArgInfo
  8029. SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
  8030. if (Ty->isAnyComplexType()) {
  8031. return ABIArgInfo::getDirect();
  8032. }
  8033. else {
  8034. return DefaultABIInfo::classifyReturnType(Ty);
  8035. }
  8036. }
  8037. void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
  8038. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  8039. for (auto &Arg : FI.arguments())
  8040. Arg.info = classifyArgumentType(Arg.type);
  8041. }
  8042. namespace {
  8043. class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
  8044. public:
  8045. SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
  8046. : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {}
  8047. llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF,
  8048. llvm::Value *Address) const override {
  8049. int Offset;
  8050. if (isAggregateTypeForABI(CGF.CurFnInfo->getReturnType()))
  8051. Offset = 12;
  8052. else
  8053. Offset = 8;
  8054. return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
  8055. llvm::ConstantInt::get(CGF.Int32Ty, Offset));
  8056. }
  8057. llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF,
  8058. llvm::Value *Address) const override {
  8059. int Offset;
  8060. if (isAggregateTypeForABI(CGF.CurFnInfo->getReturnType()))
  8061. Offset = -12;
  8062. else
  8063. Offset = -8;
  8064. return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
  8065. llvm::ConstantInt::get(CGF.Int32Ty, Offset));
  8066. }
  8067. };
  8068. } // end anonymous namespace
  8069. //===----------------------------------------------------------------------===//
  8070. // SPARC v9 ABI Implementation.
  8071. // Based on the SPARC Compliance Definition version 2.4.1.
  8072. //
  8073. // Function arguments a mapped to a nominal "parameter array" and promoted to
  8074. // registers depending on their type. Each argument occupies 8 or 16 bytes in
  8075. // the array, structs larger than 16 bytes are passed indirectly.
  8076. //
  8077. // One case requires special care:
  8078. //
  8079. // struct mixed {
  8080. // int i;
  8081. // float f;
  8082. // };
  8083. //
  8084. // When a struct mixed is passed by value, it only occupies 8 bytes in the
  8085. // parameter array, but the int is passed in an integer register, and the float
  8086. // is passed in a floating point register. This is represented as two arguments
  8087. // with the LLVM IR inreg attribute:
  8088. //
  8089. // declare void f(i32 inreg %i, float inreg %f)
  8090. //
  8091. // The code generator will only allocate 4 bytes from the parameter array for
  8092. // the inreg arguments. All other arguments are allocated a multiple of 8
  8093. // bytes.
  8094. //
  8095. namespace {
  8096. class SparcV9ABIInfo : public ABIInfo {
  8097. public:
  8098. SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
  8099. private:
  8100. ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
  8101. void computeInfo(CGFunctionInfo &FI) const override;
  8102. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  8103. QualType Ty) const override;
  8104. // Coercion type builder for structs passed in registers. The coercion type
  8105. // serves two purposes:
  8106. //
  8107. // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
  8108. // in registers.
  8109. // 2. Expose aligned floating point elements as first-level elements, so the
  8110. // code generator knows to pass them in floating point registers.
  8111. //
  8112. // We also compute the InReg flag which indicates that the struct contains
  8113. // aligned 32-bit floats.
  8114. //
  8115. struct CoerceBuilder {
  8116. llvm::LLVMContext &Context;
  8117. const llvm::DataLayout &DL;
  8118. SmallVector<llvm::Type*, 8> Elems;
  8119. uint64_t Size;
  8120. bool InReg;
  8121. CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
  8122. : Context(c), DL(dl), Size(0), InReg(false) {}
  8123. // Pad Elems with integers until Size is ToSize.
  8124. void pad(uint64_t ToSize) {
  8125. assert(ToSize >= Size && "Cannot remove elements");
  8126. if (ToSize == Size)
  8127. return;
  8128. // Finish the current 64-bit word.
  8129. uint64_t Aligned = llvm::alignTo(Size, 64);
  8130. if (Aligned > Size && Aligned <= ToSize) {
  8131. Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
  8132. Size = Aligned;
  8133. }
  8134. // Add whole 64-bit words.
  8135. while (Size + 64 <= ToSize) {
  8136. Elems.push_back(llvm::Type::getInt64Ty(Context));
  8137. Size += 64;
  8138. }
  8139. // Final in-word padding.
  8140. if (Size < ToSize) {
  8141. Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
  8142. Size = ToSize;
  8143. }
  8144. }
  8145. // Add a floating point element at Offset.
  8146. void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
  8147. // Unaligned floats are treated as integers.
  8148. if (Offset % Bits)
  8149. return;
  8150. // The InReg flag is only required if there are any floats < 64 bits.
  8151. if (Bits < 64)
  8152. InReg = true;
  8153. pad(Offset);
  8154. Elems.push_back(Ty);
  8155. Size = Offset + Bits;
  8156. }
  8157. // Add a struct type to the coercion type, starting at Offset (in bits).
  8158. void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
  8159. const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
  8160. for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
  8161. llvm::Type *ElemTy = StrTy->getElementType(i);
  8162. uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
  8163. switch (ElemTy->getTypeID()) {
  8164. case llvm::Type::StructTyID:
  8165. addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
  8166. break;
  8167. case llvm::Type::FloatTyID:
  8168. addFloat(ElemOffset, ElemTy, 32);
  8169. break;
  8170. case llvm::Type::DoubleTyID:
  8171. addFloat(ElemOffset, ElemTy, 64);
  8172. break;
  8173. case llvm::Type::FP128TyID:
  8174. addFloat(ElemOffset, ElemTy, 128);
  8175. break;
  8176. case llvm::Type::PointerTyID:
  8177. if (ElemOffset % 64 == 0) {
  8178. pad(ElemOffset);
  8179. Elems.push_back(ElemTy);
  8180. Size += 64;
  8181. }
  8182. break;
  8183. default:
  8184. break;
  8185. }
  8186. }
  8187. }
  8188. // Check if Ty is a usable substitute for the coercion type.
  8189. bool isUsableType(llvm::StructType *Ty) const {
  8190. return llvm::makeArrayRef(Elems) == Ty->elements();
  8191. }
  8192. // Get the coercion type as a literal struct type.
  8193. llvm::Type *getType() const {
  8194. if (Elems.size() == 1)
  8195. return Elems.front();
  8196. else
  8197. return llvm::StructType::get(Context, Elems);
  8198. }
  8199. };
  8200. };
  8201. } // end anonymous namespace
  8202. ABIArgInfo
  8203. SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
  8204. if (Ty->isVoidType())
  8205. return ABIArgInfo::getIgnore();
  8206. uint64_t Size = getContext().getTypeSize(Ty);
  8207. // Anything too big to fit in registers is passed with an explicit indirect
  8208. // pointer / sret pointer.
  8209. if (Size > SizeLimit)
  8210. return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
  8211. // Treat an enum type as its underlying type.
  8212. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  8213. Ty = EnumTy->getDecl()->getIntegerType();
  8214. // Integer types smaller than a register are extended.
  8215. if (Size < 64 && Ty->isIntegerType())
  8216. return ABIArgInfo::getExtend(Ty);
  8217. if (const auto *EIT = Ty->getAs<BitIntType>())
  8218. if (EIT->getNumBits() < 64)
  8219. return ABIArgInfo::getExtend(Ty);
  8220. // Other non-aggregates go in registers.
  8221. if (!isAggregateTypeForABI(Ty))
  8222. return ABIArgInfo::getDirect();
  8223. // If a C++ object has either a non-trivial copy constructor or a non-trivial
  8224. // destructor, it is passed with an explicit indirect pointer / sret pointer.
  8225. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
  8226. return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
  8227. // This is a small aggregate type that should be passed in registers.
  8228. // Build a coercion type from the LLVM struct type.
  8229. llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
  8230. if (!StrTy)
  8231. return ABIArgInfo::getDirect();
  8232. CoerceBuilder CB(getVMContext(), getDataLayout());
  8233. CB.addStruct(0, StrTy);
  8234. CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
  8235. // Try to use the original type for coercion.
  8236. llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
  8237. if (CB.InReg)
  8238. return ABIArgInfo::getDirectInReg(CoerceTy);
  8239. else
  8240. return ABIArgInfo::getDirect(CoerceTy);
  8241. }
  8242. Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  8243. QualType Ty) const {
  8244. ABIArgInfo AI = classifyType(Ty, 16 * 8);
  8245. llvm::Type *ArgTy = CGT.ConvertType(Ty);
  8246. if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
  8247. AI.setCoerceToType(ArgTy);
  8248. CharUnits SlotSize = CharUnits::fromQuantity(8);
  8249. CGBuilderTy &Builder = CGF.Builder;
  8250. Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
  8251. llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
  8252. auto TypeInfo = getContext().getTypeInfoInChars(Ty);
  8253. Address ArgAddr = Address::invalid();
  8254. CharUnits Stride;
  8255. switch (AI.getKind()) {
  8256. case ABIArgInfo::Expand:
  8257. case ABIArgInfo::CoerceAndExpand:
  8258. case ABIArgInfo::InAlloca:
  8259. llvm_unreachable("Unsupported ABI kind for va_arg");
  8260. case ABIArgInfo::Extend: {
  8261. Stride = SlotSize;
  8262. CharUnits Offset = SlotSize - TypeInfo.Width;
  8263. ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
  8264. break;
  8265. }
  8266. case ABIArgInfo::Direct: {
  8267. auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
  8268. Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
  8269. ArgAddr = Addr;
  8270. break;
  8271. }
  8272. case ABIArgInfo::Indirect:
  8273. case ABIArgInfo::IndirectAliased:
  8274. Stride = SlotSize;
  8275. ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
  8276. ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
  8277. TypeInfo.Align);
  8278. break;
  8279. case ABIArgInfo::Ignore:
  8280. return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.Align);
  8281. }
  8282. // Update VAList.
  8283. Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
  8284. Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
  8285. return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
  8286. }
  8287. void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
  8288. FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
  8289. for (auto &I : FI.arguments())
  8290. I.info = classifyType(I.type, 16 * 8);
  8291. }
  8292. namespace {
  8293. class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
  8294. public:
  8295. SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
  8296. : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {}
  8297. int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
  8298. return 14;
  8299. }
  8300. bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  8301. llvm::Value *Address) const override;
  8302. llvm::Value *decodeReturnAddress(CodeGen::CodeGenFunction &CGF,
  8303. llvm::Value *Address) const override {
  8304. return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
  8305. llvm::ConstantInt::get(CGF.Int32Ty, 8));
  8306. }
  8307. llvm::Value *encodeReturnAddress(CodeGen::CodeGenFunction &CGF,
  8308. llvm::Value *Address) const override {
  8309. return CGF.Builder.CreateGEP(CGF.Int8Ty, Address,
  8310. llvm::ConstantInt::get(CGF.Int32Ty, -8));
  8311. }
  8312. };
  8313. } // end anonymous namespace
  8314. bool
  8315. SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
  8316. llvm::Value *Address) const {
  8317. // This is calculated from the LLVM and GCC tables and verified
  8318. // against gcc output. AFAIK all ABIs use the same encoding.
  8319. CodeGen::CGBuilderTy &Builder = CGF.Builder;
  8320. llvm::IntegerType *i8 = CGF.Int8Ty;
  8321. llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
  8322. llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
  8323. // 0-31: the 8-byte general-purpose registers
  8324. AssignToArrayRange(Builder, Address, Eight8, 0, 31);
  8325. // 32-63: f0-31, the 4-byte floating-point registers
  8326. AssignToArrayRange(Builder, Address, Four8, 32, 63);
  8327. // Y = 64
  8328. // PSR = 65
  8329. // WIM = 66
  8330. // TBR = 67
  8331. // PC = 68
  8332. // NPC = 69
  8333. // FSR = 70
  8334. // CSR = 71
  8335. AssignToArrayRange(Builder, Address, Eight8, 64, 71);
  8336. // 72-87: d0-15, the 8-byte floating-point registers
  8337. AssignToArrayRange(Builder, Address, Eight8, 72, 87);
  8338. return false;
  8339. }
  8340. // ARC ABI implementation.
  8341. namespace {
  8342. class ARCABIInfo : public DefaultABIInfo {
  8343. public:
  8344. using DefaultABIInfo::DefaultABIInfo;
  8345. private:
  8346. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  8347. QualType Ty) const override;
  8348. void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
  8349. if (!State.FreeRegs)
  8350. return;
  8351. if (Info.isIndirect() && Info.getInReg())
  8352. State.FreeRegs--;
  8353. else if (Info.isDirect() && Info.getInReg()) {
  8354. unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
  8355. if (sz < State.FreeRegs)
  8356. State.FreeRegs -= sz;
  8357. else
  8358. State.FreeRegs = 0;
  8359. }
  8360. }
  8361. void computeInfo(CGFunctionInfo &FI) const override {
  8362. CCState State(FI);
  8363. // ARC uses 8 registers to pass arguments.
  8364. State.FreeRegs = 8;
  8365. if (!getCXXABI().classifyReturnType(FI))
  8366. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  8367. updateState(FI.getReturnInfo(), FI.getReturnType(), State);
  8368. for (auto &I : FI.arguments()) {
  8369. I.info = classifyArgumentType(I.type, State.FreeRegs);
  8370. updateState(I.info, I.type, State);
  8371. }
  8372. }
  8373. ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
  8374. ABIArgInfo getIndirectByValue(QualType Ty) const;
  8375. ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
  8376. ABIArgInfo classifyReturnType(QualType RetTy) const;
  8377. };
  8378. class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
  8379. public:
  8380. ARCTargetCodeGenInfo(CodeGenTypes &CGT)
  8381. : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {}
  8382. };
  8383. ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
  8384. return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
  8385. getNaturalAlignIndirect(Ty, false);
  8386. }
  8387. ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
  8388. // Compute the byval alignment.
  8389. const unsigned MinABIStackAlignInBytes = 4;
  8390. unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
  8391. return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
  8392. TypeAlign > MinABIStackAlignInBytes);
  8393. }
  8394. Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  8395. QualType Ty) const {
  8396. return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
  8397. getContext().getTypeInfoInChars(Ty),
  8398. CharUnits::fromQuantity(4), true);
  8399. }
  8400. ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
  8401. uint8_t FreeRegs) const {
  8402. // Handle the generic C++ ABI.
  8403. const RecordType *RT = Ty->getAs<RecordType>();
  8404. if (RT) {
  8405. CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
  8406. if (RAA == CGCXXABI::RAA_Indirect)
  8407. return getIndirectByRef(Ty, FreeRegs > 0);
  8408. if (RAA == CGCXXABI::RAA_DirectInMemory)
  8409. return getIndirectByValue(Ty);
  8410. }
  8411. // Treat an enum type as its underlying type.
  8412. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  8413. Ty = EnumTy->getDecl()->getIntegerType();
  8414. auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
  8415. if (isAggregateTypeForABI(Ty)) {
  8416. // Structures with flexible arrays are always indirect.
  8417. if (RT && RT->getDecl()->hasFlexibleArrayMember())
  8418. return getIndirectByValue(Ty);
  8419. // Ignore empty structs/unions.
  8420. if (isEmptyRecord(getContext(), Ty, true))
  8421. return ABIArgInfo::getIgnore();
  8422. llvm::LLVMContext &LLVMContext = getVMContext();
  8423. llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
  8424. SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
  8425. llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
  8426. return FreeRegs >= SizeInRegs ?
  8427. ABIArgInfo::getDirectInReg(Result) :
  8428. ABIArgInfo::getDirect(Result, 0, nullptr, false);
  8429. }
  8430. if (const auto *EIT = Ty->getAs<BitIntType>())
  8431. if (EIT->getNumBits() > 64)
  8432. return getIndirectByValue(Ty);
  8433. return isPromotableIntegerTypeForABI(Ty)
  8434. ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty)
  8435. : ABIArgInfo::getExtend(Ty))
  8436. : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg()
  8437. : ABIArgInfo::getDirect());
  8438. }
  8439. ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
  8440. if (RetTy->isAnyComplexType())
  8441. return ABIArgInfo::getDirectInReg();
  8442. // Arguments of size > 4 registers are indirect.
  8443. auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
  8444. if (RetSize > 4)
  8445. return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
  8446. return DefaultABIInfo::classifyReturnType(RetTy);
  8447. }
  8448. } // End anonymous namespace.
  8449. //===----------------------------------------------------------------------===//
  8450. // XCore ABI Implementation
  8451. //===----------------------------------------------------------------------===//
  8452. namespace {
  8453. /// A SmallStringEnc instance is used to build up the TypeString by passing
  8454. /// it by reference between functions that append to it.
  8455. typedef llvm::SmallString<128> SmallStringEnc;
  8456. /// TypeStringCache caches the meta encodings of Types.
  8457. ///
  8458. /// The reason for caching TypeStrings is two fold:
  8459. /// 1. To cache a type's encoding for later uses;
  8460. /// 2. As a means to break recursive member type inclusion.
  8461. ///
  8462. /// A cache Entry can have a Status of:
  8463. /// NonRecursive: The type encoding is not recursive;
  8464. /// Recursive: The type encoding is recursive;
  8465. /// Incomplete: An incomplete TypeString;
  8466. /// IncompleteUsed: An incomplete TypeString that has been used in a
  8467. /// Recursive type encoding.
  8468. ///
  8469. /// A NonRecursive entry will have all of its sub-members expanded as fully
  8470. /// as possible. Whilst it may contain types which are recursive, the type
  8471. /// itself is not recursive and thus its encoding may be safely used whenever
  8472. /// the type is encountered.
  8473. ///
  8474. /// A Recursive entry will have all of its sub-members expanded as fully as
  8475. /// possible. The type itself is recursive and it may contain other types which
  8476. /// are recursive. The Recursive encoding must not be used during the expansion
  8477. /// of a recursive type's recursive branch. For simplicity the code uses
  8478. /// IncompleteCount to reject all usage of Recursive encodings for member types.
  8479. ///
  8480. /// An Incomplete entry is always a RecordType and only encodes its
  8481. /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
  8482. /// are placed into the cache during type expansion as a means to identify and
  8483. /// handle recursive inclusion of types as sub-members. If there is recursion
  8484. /// the entry becomes IncompleteUsed.
  8485. ///
  8486. /// During the expansion of a RecordType's members:
  8487. ///
  8488. /// If the cache contains a NonRecursive encoding for the member type, the
  8489. /// cached encoding is used;
  8490. ///
  8491. /// If the cache contains a Recursive encoding for the member type, the
  8492. /// cached encoding is 'Swapped' out, as it may be incorrect, and...
  8493. ///
  8494. /// If the member is a RecordType, an Incomplete encoding is placed into the
  8495. /// cache to break potential recursive inclusion of itself as a sub-member;
  8496. ///
  8497. /// Once a member RecordType has been expanded, its temporary incomplete
  8498. /// entry is removed from the cache. If a Recursive encoding was swapped out
  8499. /// it is swapped back in;
  8500. ///
  8501. /// If an incomplete entry is used to expand a sub-member, the incomplete
  8502. /// entry is marked as IncompleteUsed. The cache keeps count of how many
  8503. /// IncompleteUsed entries it currently contains in IncompleteUsedCount;
  8504. ///
  8505. /// If a member's encoding is found to be a NonRecursive or Recursive viz:
  8506. /// IncompleteUsedCount==0, the member's encoding is added to the cache.
  8507. /// Else the member is part of a recursive type and thus the recursion has
  8508. /// been exited too soon for the encoding to be correct for the member.
  8509. ///
  8510. class TypeStringCache {
  8511. enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
  8512. struct Entry {
  8513. std::string Str; // The encoded TypeString for the type.
  8514. enum Status State; // Information about the encoding in 'Str'.
  8515. std::string Swapped; // A temporary place holder for a Recursive encoding
  8516. // during the expansion of RecordType's members.
  8517. };
  8518. std::map<const IdentifierInfo *, struct Entry> Map;
  8519. unsigned IncompleteCount; // Number of Incomplete entries in the Map.
  8520. unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
  8521. public:
  8522. TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
  8523. void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
  8524. bool removeIncomplete(const IdentifierInfo *ID);
  8525. void addIfComplete(const IdentifierInfo *ID, StringRef Str,
  8526. bool IsRecursive);
  8527. StringRef lookupStr(const IdentifierInfo *ID);
  8528. };
  8529. /// TypeString encodings for enum & union fields must be order.
  8530. /// FieldEncoding is a helper for this ordering process.
  8531. class FieldEncoding {
  8532. bool HasName;
  8533. std::string Enc;
  8534. public:
  8535. FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
  8536. StringRef str() { return Enc; }
  8537. bool operator<(const FieldEncoding &rhs) const {
  8538. if (HasName != rhs.HasName) return HasName;
  8539. return Enc < rhs.Enc;
  8540. }
  8541. };
  8542. class XCoreABIInfo : public DefaultABIInfo {
  8543. public:
  8544. XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
  8545. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  8546. QualType Ty) const override;
  8547. };
  8548. class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
  8549. mutable TypeStringCache TSC;
  8550. void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
  8551. const CodeGen::CodeGenModule &M) const;
  8552. public:
  8553. XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
  8554. : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {}
  8555. void emitTargetMetadata(CodeGen::CodeGenModule &CGM,
  8556. const llvm::MapVector<GlobalDecl, StringRef>
  8557. &MangledDeclNames) const override;
  8558. };
  8559. } // End anonymous namespace.
  8560. // TODO: this implementation is likely now redundant with the default
  8561. // EmitVAArg.
  8562. Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  8563. QualType Ty) const {
  8564. CGBuilderTy &Builder = CGF.Builder;
  8565. // Get the VAList.
  8566. CharUnits SlotSize = CharUnits::fromQuantity(4);
  8567. Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
  8568. // Handle the argument.
  8569. ABIArgInfo AI = classifyArgumentType(Ty);
  8570. CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
  8571. llvm::Type *ArgTy = CGT.ConvertType(Ty);
  8572. if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
  8573. AI.setCoerceToType(ArgTy);
  8574. llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
  8575. Address Val = Address::invalid();
  8576. CharUnits ArgSize = CharUnits::Zero();
  8577. switch (AI.getKind()) {
  8578. case ABIArgInfo::Expand:
  8579. case ABIArgInfo::CoerceAndExpand:
  8580. case ABIArgInfo::InAlloca:
  8581. llvm_unreachable("Unsupported ABI kind for va_arg");
  8582. case ABIArgInfo::Ignore:
  8583. Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
  8584. ArgSize = CharUnits::Zero();
  8585. break;
  8586. case ABIArgInfo::Extend:
  8587. case ABIArgInfo::Direct:
  8588. Val = Builder.CreateBitCast(AP, ArgPtrTy);
  8589. ArgSize = CharUnits::fromQuantity(
  8590. getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
  8591. ArgSize = ArgSize.alignTo(SlotSize);
  8592. break;
  8593. case ABIArgInfo::Indirect:
  8594. case ABIArgInfo::IndirectAliased:
  8595. Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
  8596. Val = Address(Builder.CreateLoad(Val), TypeAlign);
  8597. ArgSize = SlotSize;
  8598. break;
  8599. }
  8600. // Increment the VAList.
  8601. if (!ArgSize.isZero()) {
  8602. Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
  8603. Builder.CreateStore(APN.getPointer(), VAListAddr);
  8604. }
  8605. return Val;
  8606. }
  8607. /// During the expansion of a RecordType, an incomplete TypeString is placed
  8608. /// into the cache as a means to identify and break recursion.
  8609. /// If there is a Recursive encoding in the cache, it is swapped out and will
  8610. /// be reinserted by removeIncomplete().
  8611. /// All other types of encoding should have been used rather than arriving here.
  8612. void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
  8613. std::string StubEnc) {
  8614. if (!ID)
  8615. return;
  8616. Entry &E = Map[ID];
  8617. assert( (E.Str.empty() || E.State == Recursive) &&
  8618. "Incorrectly use of addIncomplete");
  8619. assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
  8620. E.Swapped.swap(E.Str); // swap out the Recursive
  8621. E.Str.swap(StubEnc);
  8622. E.State = Incomplete;
  8623. ++IncompleteCount;
  8624. }
  8625. /// Once the RecordType has been expanded, the temporary incomplete TypeString
  8626. /// must be removed from the cache.
  8627. /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
  8628. /// Returns true if the RecordType was defined recursively.
  8629. bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
  8630. if (!ID)
  8631. return false;
  8632. auto I = Map.find(ID);
  8633. assert(I != Map.end() && "Entry not present");
  8634. Entry &E = I->second;
  8635. assert( (E.State == Incomplete ||
  8636. E.State == IncompleteUsed) &&
  8637. "Entry must be an incomplete type");
  8638. bool IsRecursive = false;
  8639. if (E.State == IncompleteUsed) {
  8640. // We made use of our Incomplete encoding, thus we are recursive.
  8641. IsRecursive = true;
  8642. --IncompleteUsedCount;
  8643. }
  8644. if (E.Swapped.empty())
  8645. Map.erase(I);
  8646. else {
  8647. // Swap the Recursive back.
  8648. E.Swapped.swap(E.Str);
  8649. E.Swapped.clear();
  8650. E.State = Recursive;
  8651. }
  8652. --IncompleteCount;
  8653. return IsRecursive;
  8654. }
  8655. /// Add the encoded TypeString to the cache only if it is NonRecursive or
  8656. /// Recursive (viz: all sub-members were expanded as fully as possible).
  8657. void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
  8658. bool IsRecursive) {
  8659. if (!ID || IncompleteUsedCount)
  8660. return; // No key or it is is an incomplete sub-type so don't add.
  8661. Entry &E = Map[ID];
  8662. if (IsRecursive && !E.Str.empty()) {
  8663. assert(E.State==Recursive && E.Str.size() == Str.size() &&
  8664. "This is not the same Recursive entry");
  8665. // The parent container was not recursive after all, so we could have used
  8666. // this Recursive sub-member entry after all, but we assumed the worse when
  8667. // we started viz: IncompleteCount!=0.
  8668. return;
  8669. }
  8670. assert(E.Str.empty() && "Entry already present");
  8671. E.Str = Str.str();
  8672. E.State = IsRecursive? Recursive : NonRecursive;
  8673. }
  8674. /// Return a cached TypeString encoding for the ID. If there isn't one, or we
  8675. /// are recursively expanding a type (IncompleteCount != 0) and the cached
  8676. /// encoding is Recursive, return an empty StringRef.
  8677. StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
  8678. if (!ID)
  8679. return StringRef(); // We have no key.
  8680. auto I = Map.find(ID);
  8681. if (I == Map.end())
  8682. return StringRef(); // We have no encoding.
  8683. Entry &E = I->second;
  8684. if (E.State == Recursive && IncompleteCount)
  8685. return StringRef(); // We don't use Recursive encodings for member types.
  8686. if (E.State == Incomplete) {
  8687. // The incomplete type is being used to break out of recursion.
  8688. E.State = IncompleteUsed;
  8689. ++IncompleteUsedCount;
  8690. }
  8691. return E.Str;
  8692. }
  8693. /// The XCore ABI includes a type information section that communicates symbol
  8694. /// type information to the linker. The linker uses this information to verify
  8695. /// safety/correctness of things such as array bound and pointers et al.
  8696. /// The ABI only requires C (and XC) language modules to emit TypeStrings.
  8697. /// This type information (TypeString) is emitted into meta data for all global
  8698. /// symbols: definitions, declarations, functions & variables.
  8699. ///
  8700. /// The TypeString carries type, qualifier, name, size & value details.
  8701. /// Please see 'Tools Development Guide' section 2.16.2 for format details:
  8702. /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
  8703. /// The output is tested by test/CodeGen/xcore-stringtype.c.
  8704. ///
  8705. static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
  8706. const CodeGen::CodeGenModule &CGM,
  8707. TypeStringCache &TSC);
  8708. /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
  8709. void XCoreTargetCodeGenInfo::emitTargetMD(
  8710. const Decl *D, llvm::GlobalValue *GV,
  8711. const CodeGen::CodeGenModule &CGM) const {
  8712. SmallStringEnc Enc;
  8713. if (getTypeString(Enc, D, CGM, TSC)) {
  8714. llvm::LLVMContext &Ctx = CGM.getModule().getContext();
  8715. llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
  8716. llvm::MDString::get(Ctx, Enc.str())};
  8717. llvm::NamedMDNode *MD =
  8718. CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
  8719. MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
  8720. }
  8721. }
  8722. void XCoreTargetCodeGenInfo::emitTargetMetadata(
  8723. CodeGen::CodeGenModule &CGM,
  8724. const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const {
  8725. // Warning, new MangledDeclNames may be appended within this loop.
  8726. // We rely on MapVector insertions adding new elements to the end
  8727. // of the container.
  8728. for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
  8729. auto Val = *(MangledDeclNames.begin() + I);
  8730. llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second);
  8731. if (GV) {
  8732. const Decl *D = Val.first.getDecl()->getMostRecentDecl();
  8733. emitTargetMD(D, GV, CGM);
  8734. }
  8735. }
  8736. }
  8737. //===----------------------------------------------------------------------===//
  8738. // Base ABI and target codegen info implementation common between SPIR and
  8739. // SPIR-V.
  8740. //===----------------------------------------------------------------------===//
  8741. namespace {
  8742. class CommonSPIRABIInfo : public DefaultABIInfo {
  8743. public:
  8744. CommonSPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); }
  8745. private:
  8746. void setCCs();
  8747. };
  8748. class SPIRVABIInfo : public CommonSPIRABIInfo {
  8749. public:
  8750. SPIRVABIInfo(CodeGenTypes &CGT) : CommonSPIRABIInfo(CGT) {}
  8751. void computeInfo(CGFunctionInfo &FI) const override;
  8752. private:
  8753. ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
  8754. };
  8755. } // end anonymous namespace
  8756. namespace {
  8757. class CommonSPIRTargetCodeGenInfo : public TargetCodeGenInfo {
  8758. public:
  8759. CommonSPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
  8760. : TargetCodeGenInfo(std::make_unique<CommonSPIRABIInfo>(CGT)) {}
  8761. CommonSPIRTargetCodeGenInfo(std::unique_ptr<ABIInfo> ABIInfo)
  8762. : TargetCodeGenInfo(std::move(ABIInfo)) {}
  8763. LangAS getASTAllocaAddressSpace() const override {
  8764. return getLangASFromTargetAS(
  8765. getABIInfo().getDataLayout().getAllocaAddrSpace());
  8766. }
  8767. unsigned getOpenCLKernelCallingConv() const override;
  8768. };
  8769. class SPIRVTargetCodeGenInfo : public CommonSPIRTargetCodeGenInfo {
  8770. public:
  8771. SPIRVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
  8772. : CommonSPIRTargetCodeGenInfo(std::make_unique<SPIRVABIInfo>(CGT)) {}
  8773. void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
  8774. };
  8775. } // End anonymous namespace.
  8776. void CommonSPIRABIInfo::setCCs() {
  8777. assert(getRuntimeCC() == llvm::CallingConv::C);
  8778. RuntimeCC = llvm::CallingConv::SPIR_FUNC;
  8779. }
  8780. ABIArgInfo SPIRVABIInfo::classifyKernelArgumentType(QualType Ty) const {
  8781. if (getContext().getLangOpts().HIP) {
  8782. // Coerce pointer arguments with default address space to CrossWorkGroup
  8783. // pointers for HIPSPV. When the language mode is HIP, the SPIRTargetInfo
  8784. // maps cuda_device to SPIR-V's CrossWorkGroup address space.
  8785. llvm::Type *LTy = CGT.ConvertType(Ty);
  8786. auto DefaultAS = getContext().getTargetAddressSpace(LangAS::Default);
  8787. auto GlobalAS = getContext().getTargetAddressSpace(LangAS::cuda_device);
  8788. auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(LTy);
  8789. if (PtrTy && PtrTy->getAddressSpace() == DefaultAS) {
  8790. LTy = llvm::PointerType::getWithSamePointeeType(PtrTy, GlobalAS);
  8791. return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
  8792. }
  8793. }
  8794. return classifyArgumentType(Ty);
  8795. }
  8796. void SPIRVABIInfo::computeInfo(CGFunctionInfo &FI) const {
  8797. // The logic is same as in DefaultABIInfo with an exception on the kernel
  8798. // arguments handling.
  8799. llvm::CallingConv::ID CC = FI.getCallingConvention();
  8800. if (!getCXXABI().classifyReturnType(FI))
  8801. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  8802. for (auto &I : FI.arguments()) {
  8803. if (CC == llvm::CallingConv::SPIR_KERNEL) {
  8804. I.info = classifyKernelArgumentType(I.type);
  8805. } else {
  8806. I.info = classifyArgumentType(I.type);
  8807. }
  8808. }
  8809. }
  8810. namespace clang {
  8811. namespace CodeGen {
  8812. void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
  8813. if (CGM.getTarget().getTriple().isSPIRV())
  8814. SPIRVABIInfo(CGM.getTypes()).computeInfo(FI);
  8815. else
  8816. CommonSPIRABIInfo(CGM.getTypes()).computeInfo(FI);
  8817. }
  8818. }
  8819. }
  8820. unsigned CommonSPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
  8821. return llvm::CallingConv::SPIR_KERNEL;
  8822. }
  8823. void SPIRVTargetCodeGenInfo::setCUDAKernelCallingConvention(
  8824. const FunctionType *&FT) const {
  8825. // Convert HIP kernels to SPIR-V kernels.
  8826. if (getABIInfo().getContext().getLangOpts().HIP) {
  8827. FT = getABIInfo().getContext().adjustFunctionType(
  8828. FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
  8829. return;
  8830. }
  8831. }
  8832. static bool appendType(SmallStringEnc &Enc, QualType QType,
  8833. const CodeGen::CodeGenModule &CGM,
  8834. TypeStringCache &TSC);
  8835. /// Helper function for appendRecordType().
  8836. /// Builds a SmallVector containing the encoded field types in declaration
  8837. /// order.
  8838. static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
  8839. const RecordDecl *RD,
  8840. const CodeGen::CodeGenModule &CGM,
  8841. TypeStringCache &TSC) {
  8842. for (const auto *Field : RD->fields()) {
  8843. SmallStringEnc Enc;
  8844. Enc += "m(";
  8845. Enc += Field->getName();
  8846. Enc += "){";
  8847. if (Field->isBitField()) {
  8848. Enc += "b(";
  8849. llvm::raw_svector_ostream OS(Enc);
  8850. OS << Field->getBitWidthValue(CGM.getContext());
  8851. Enc += ':';
  8852. }
  8853. if (!appendType(Enc, Field->getType(), CGM, TSC))
  8854. return false;
  8855. if (Field->isBitField())
  8856. Enc += ')';
  8857. Enc += '}';
  8858. FE.emplace_back(!Field->getName().empty(), Enc);
  8859. }
  8860. return true;
  8861. }
  8862. /// Appends structure and union types to Enc and adds encoding to cache.
  8863. /// Recursively calls appendType (via extractFieldType) for each field.
  8864. /// Union types have their fields ordered according to the ABI.
  8865. static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
  8866. const CodeGen::CodeGenModule &CGM,
  8867. TypeStringCache &TSC, const IdentifierInfo *ID) {
  8868. // Append the cached TypeString if we have one.
  8869. StringRef TypeString = TSC.lookupStr(ID);
  8870. if (!TypeString.empty()) {
  8871. Enc += TypeString;
  8872. return true;
  8873. }
  8874. // Start to emit an incomplete TypeString.
  8875. size_t Start = Enc.size();
  8876. Enc += (RT->isUnionType()? 'u' : 's');
  8877. Enc += '(';
  8878. if (ID)
  8879. Enc += ID->getName();
  8880. Enc += "){";
  8881. // We collect all encoded fields and order as necessary.
  8882. bool IsRecursive = false;
  8883. const RecordDecl *RD = RT->getDecl()->getDefinition();
  8884. if (RD && !RD->field_empty()) {
  8885. // An incomplete TypeString stub is placed in the cache for this RecordType
  8886. // so that recursive calls to this RecordType will use it whilst building a
  8887. // complete TypeString for this RecordType.
  8888. SmallVector<FieldEncoding, 16> FE;
  8889. std::string StubEnc(Enc.substr(Start).str());
  8890. StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
  8891. TSC.addIncomplete(ID, std::move(StubEnc));
  8892. if (!extractFieldType(FE, RD, CGM, TSC)) {
  8893. (void) TSC.removeIncomplete(ID);
  8894. return false;
  8895. }
  8896. IsRecursive = TSC.removeIncomplete(ID);
  8897. // The ABI requires unions to be sorted but not structures.
  8898. // See FieldEncoding::operator< for sort algorithm.
  8899. if (RT->isUnionType())
  8900. llvm::sort(FE);
  8901. // We can now complete the TypeString.
  8902. unsigned E = FE.size();
  8903. for (unsigned I = 0; I != E; ++I) {
  8904. if (I)
  8905. Enc += ',';
  8906. Enc += FE[I].str();
  8907. }
  8908. }
  8909. Enc += '}';
  8910. TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
  8911. return true;
  8912. }
  8913. /// Appends enum types to Enc and adds the encoding to the cache.
  8914. static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
  8915. TypeStringCache &TSC,
  8916. const IdentifierInfo *ID) {
  8917. // Append the cached TypeString if we have one.
  8918. StringRef TypeString = TSC.lookupStr(ID);
  8919. if (!TypeString.empty()) {
  8920. Enc += TypeString;
  8921. return true;
  8922. }
  8923. size_t Start = Enc.size();
  8924. Enc += "e(";
  8925. if (ID)
  8926. Enc += ID->getName();
  8927. Enc += "){";
  8928. // We collect all encoded enumerations and order them alphanumerically.
  8929. if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
  8930. SmallVector<FieldEncoding, 16> FE;
  8931. for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
  8932. ++I) {
  8933. SmallStringEnc EnumEnc;
  8934. EnumEnc += "m(";
  8935. EnumEnc += I->getName();
  8936. EnumEnc += "){";
  8937. I->getInitVal().toString(EnumEnc);
  8938. EnumEnc += '}';
  8939. FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
  8940. }
  8941. llvm::sort(FE);
  8942. unsigned E = FE.size();
  8943. for (unsigned I = 0; I != E; ++I) {
  8944. if (I)
  8945. Enc += ',';
  8946. Enc += FE[I].str();
  8947. }
  8948. }
  8949. Enc += '}';
  8950. TSC.addIfComplete(ID, Enc.substr(Start), false);
  8951. return true;
  8952. }
  8953. /// Appends type's qualifier to Enc.
  8954. /// This is done prior to appending the type's encoding.
  8955. static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
  8956. // Qualifiers are emitted in alphabetical order.
  8957. static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
  8958. int Lookup = 0;
  8959. if (QT.isConstQualified())
  8960. Lookup += 1<<0;
  8961. if (QT.isRestrictQualified())
  8962. Lookup += 1<<1;
  8963. if (QT.isVolatileQualified())
  8964. Lookup += 1<<2;
  8965. Enc += Table[Lookup];
  8966. }
  8967. /// Appends built-in types to Enc.
  8968. static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
  8969. const char *EncType;
  8970. switch (BT->getKind()) {
  8971. case BuiltinType::Void:
  8972. EncType = "0";
  8973. break;
  8974. case BuiltinType::Bool:
  8975. EncType = "b";
  8976. break;
  8977. case BuiltinType::Char_U:
  8978. EncType = "uc";
  8979. break;
  8980. case BuiltinType::UChar:
  8981. EncType = "uc";
  8982. break;
  8983. case BuiltinType::SChar:
  8984. EncType = "sc";
  8985. break;
  8986. case BuiltinType::UShort:
  8987. EncType = "us";
  8988. break;
  8989. case BuiltinType::Short:
  8990. EncType = "ss";
  8991. break;
  8992. case BuiltinType::UInt:
  8993. EncType = "ui";
  8994. break;
  8995. case BuiltinType::Int:
  8996. EncType = "si";
  8997. break;
  8998. case BuiltinType::ULong:
  8999. EncType = "ul";
  9000. break;
  9001. case BuiltinType::Long:
  9002. EncType = "sl";
  9003. break;
  9004. case BuiltinType::ULongLong:
  9005. EncType = "ull";
  9006. break;
  9007. case BuiltinType::LongLong:
  9008. EncType = "sll";
  9009. break;
  9010. case BuiltinType::Float:
  9011. EncType = "ft";
  9012. break;
  9013. case BuiltinType::Double:
  9014. EncType = "d";
  9015. break;
  9016. case BuiltinType::LongDouble:
  9017. EncType = "ld";
  9018. break;
  9019. default:
  9020. return false;
  9021. }
  9022. Enc += EncType;
  9023. return true;
  9024. }
  9025. /// Appends a pointer encoding to Enc before calling appendType for the pointee.
  9026. static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
  9027. const CodeGen::CodeGenModule &CGM,
  9028. TypeStringCache &TSC) {
  9029. Enc += "p(";
  9030. if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
  9031. return false;
  9032. Enc += ')';
  9033. return true;
  9034. }
  9035. /// Appends array encoding to Enc before calling appendType for the element.
  9036. static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
  9037. const ArrayType *AT,
  9038. const CodeGen::CodeGenModule &CGM,
  9039. TypeStringCache &TSC, StringRef NoSizeEnc) {
  9040. if (AT->getSizeModifier() != ArrayType::Normal)
  9041. return false;
  9042. Enc += "a(";
  9043. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
  9044. CAT->getSize().toStringUnsigned(Enc);
  9045. else
  9046. Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
  9047. Enc += ':';
  9048. // The Qualifiers should be attached to the type rather than the array.
  9049. appendQualifier(Enc, QT);
  9050. if (!appendType(Enc, AT->getElementType(), CGM, TSC))
  9051. return false;
  9052. Enc += ')';
  9053. return true;
  9054. }
  9055. /// Appends a function encoding to Enc, calling appendType for the return type
  9056. /// and the arguments.
  9057. static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
  9058. const CodeGen::CodeGenModule &CGM,
  9059. TypeStringCache &TSC) {
  9060. Enc += "f{";
  9061. if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
  9062. return false;
  9063. Enc += "}(";
  9064. if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
  9065. // N.B. we are only interested in the adjusted param types.
  9066. auto I = FPT->param_type_begin();
  9067. auto E = FPT->param_type_end();
  9068. if (I != E) {
  9069. do {
  9070. if (!appendType(Enc, *I, CGM, TSC))
  9071. return false;
  9072. ++I;
  9073. if (I != E)
  9074. Enc += ',';
  9075. } while (I != E);
  9076. if (FPT->isVariadic())
  9077. Enc += ",va";
  9078. } else {
  9079. if (FPT->isVariadic())
  9080. Enc += "va";
  9081. else
  9082. Enc += '0';
  9083. }
  9084. }
  9085. Enc += ')';
  9086. return true;
  9087. }
  9088. /// Handles the type's qualifier before dispatching a call to handle specific
  9089. /// type encodings.
  9090. static bool appendType(SmallStringEnc &Enc, QualType QType,
  9091. const CodeGen::CodeGenModule &CGM,
  9092. TypeStringCache &TSC) {
  9093. QualType QT = QType.getCanonicalType();
  9094. if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
  9095. // The Qualifiers should be attached to the type rather than the array.
  9096. // Thus we don't call appendQualifier() here.
  9097. return appendArrayType(Enc, QT, AT, CGM, TSC, "");
  9098. appendQualifier(Enc, QT);
  9099. if (const BuiltinType *BT = QT->getAs<BuiltinType>())
  9100. return appendBuiltinType(Enc, BT);
  9101. if (const PointerType *PT = QT->getAs<PointerType>())
  9102. return appendPointerType(Enc, PT, CGM, TSC);
  9103. if (const EnumType *ET = QT->getAs<EnumType>())
  9104. return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
  9105. if (const RecordType *RT = QT->getAsStructureType())
  9106. return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
  9107. if (const RecordType *RT = QT->getAsUnionType())
  9108. return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
  9109. if (const FunctionType *FT = QT->getAs<FunctionType>())
  9110. return appendFunctionType(Enc, FT, CGM, TSC);
  9111. return false;
  9112. }
  9113. static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
  9114. const CodeGen::CodeGenModule &CGM,
  9115. TypeStringCache &TSC) {
  9116. if (!D)
  9117. return false;
  9118. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  9119. if (FD->getLanguageLinkage() != CLanguageLinkage)
  9120. return false;
  9121. return appendType(Enc, FD->getType(), CGM, TSC);
  9122. }
  9123. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  9124. if (VD->getLanguageLinkage() != CLanguageLinkage)
  9125. return false;
  9126. QualType QT = VD->getType().getCanonicalType();
  9127. if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
  9128. // Global ArrayTypes are given a size of '*' if the size is unknown.
  9129. // The Qualifiers should be attached to the type rather than the array.
  9130. // Thus we don't call appendQualifier() here.
  9131. return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
  9132. }
  9133. return appendType(Enc, QT, CGM, TSC);
  9134. }
  9135. return false;
  9136. }
  9137. //===----------------------------------------------------------------------===//
  9138. // RISCV ABI Implementation
  9139. //===----------------------------------------------------------------------===//
  9140. namespace {
  9141. class RISCVABIInfo : public DefaultABIInfo {
  9142. private:
  9143. // Size of the integer ('x') registers in bits.
  9144. unsigned XLen;
  9145. // Size of the floating point ('f') registers in bits. Note that the target
  9146. // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
  9147. // with soft float ABI has FLen==0).
  9148. unsigned FLen;
  9149. static const int NumArgGPRs = 8;
  9150. static const int NumArgFPRs = 8;
  9151. bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
  9152. llvm::Type *&Field1Ty,
  9153. CharUnits &Field1Off,
  9154. llvm::Type *&Field2Ty,
  9155. CharUnits &Field2Off) const;
  9156. public:
  9157. RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
  9158. : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
  9159. // DefaultABIInfo's classifyReturnType and classifyArgumentType are
  9160. // non-virtual, but computeInfo is virtual, so we overload it.
  9161. void computeInfo(CGFunctionInfo &FI) const override;
  9162. ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
  9163. int &ArgFPRsLeft) const;
  9164. ABIArgInfo classifyReturnType(QualType RetTy) const;
  9165. Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  9166. QualType Ty) const override;
  9167. ABIArgInfo extendType(QualType Ty) const;
  9168. bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
  9169. CharUnits &Field1Off, llvm::Type *&Field2Ty,
  9170. CharUnits &Field2Off, int &NeededArgGPRs,
  9171. int &NeededArgFPRs) const;
  9172. ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
  9173. CharUnits Field1Off,
  9174. llvm::Type *Field2Ty,
  9175. CharUnits Field2Off) const;
  9176. };
  9177. } // end anonymous namespace
  9178. void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
  9179. QualType RetTy = FI.getReturnType();
  9180. if (!getCXXABI().classifyReturnType(FI))
  9181. FI.getReturnInfo() = classifyReturnType(RetTy);
  9182. // IsRetIndirect is true if classifyArgumentType indicated the value should
  9183. // be passed indirect, or if the type size is a scalar greater than 2*XLen
  9184. // and not a complex type with elements <= FLen. e.g. fp128 is passed direct
  9185. // in LLVM IR, relying on the backend lowering code to rewrite the argument
  9186. // list and pass indirectly on RV32.
  9187. bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
  9188. if (!IsRetIndirect && RetTy->isScalarType() &&
  9189. getContext().getTypeSize(RetTy) > (2 * XLen)) {
  9190. if (RetTy->isComplexType() && FLen) {
  9191. QualType EltTy = RetTy->castAs<ComplexType>()->getElementType();
  9192. IsRetIndirect = getContext().getTypeSize(EltTy) > FLen;
  9193. } else {
  9194. // This is a normal scalar > 2*XLen, such as fp128 on RV32.
  9195. IsRetIndirect = true;
  9196. }
  9197. }
  9198. // We must track the number of GPRs used in order to conform to the RISC-V
  9199. // ABI, as integer scalars passed in registers should have signext/zeroext
  9200. // when promoted, but are anyext if passed on the stack. As GPR usage is
  9201. // different for variadic arguments, we must also track whether we are
  9202. // examining a vararg or not.
  9203. int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
  9204. int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
  9205. int NumFixedArgs = FI.getNumRequiredArgs();
  9206. int ArgNum = 0;
  9207. for (auto &ArgInfo : FI.arguments()) {
  9208. bool IsFixed = ArgNum < NumFixedArgs;
  9209. ArgInfo.info =
  9210. classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
  9211. ArgNum++;
  9212. }
  9213. }
  9214. // Returns true if the struct is a potential candidate for the floating point
  9215. // calling convention. If this function returns true, the caller is
  9216. // responsible for checking that if there is only a single field then that
  9217. // field is a float.
  9218. bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
  9219. llvm::Type *&Field1Ty,
  9220. CharUnits &Field1Off,
  9221. llvm::Type *&Field2Ty,
  9222. CharUnits &Field2Off) const {
  9223. bool IsInt = Ty->isIntegralOrEnumerationType();
  9224. bool IsFloat = Ty->isRealFloatingType();
  9225. if (IsInt || IsFloat) {
  9226. uint64_t Size = getContext().getTypeSize(Ty);
  9227. if (IsInt && Size > XLen)
  9228. return false;
  9229. // Can't be eligible if larger than the FP registers. Half precision isn't
  9230. // currently supported on RISC-V and the ABI hasn't been confirmed, so
  9231. // default to the integer ABI in that case.
  9232. if (IsFloat && (Size > FLen || Size < 32))
  9233. return false;
  9234. // Can't be eligible if an integer type was already found (int+int pairs
  9235. // are not eligible).
  9236. if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
  9237. return false;
  9238. if (!Field1Ty) {
  9239. Field1Ty = CGT.ConvertType(Ty);
  9240. Field1Off = CurOff;
  9241. return true;
  9242. }
  9243. if (!Field2Ty) {
  9244. Field2Ty = CGT.ConvertType(Ty);
  9245. Field2Off = CurOff;
  9246. return true;
  9247. }
  9248. return false;
  9249. }
  9250. if (auto CTy = Ty->getAs<ComplexType>()) {
  9251. if (Field1Ty)
  9252. return false;
  9253. QualType EltTy = CTy->getElementType();
  9254. if (getContext().getTypeSize(EltTy) > FLen)
  9255. return false;
  9256. Field1Ty = CGT.ConvertType(EltTy);
  9257. Field1Off = CurOff;
  9258. Field2Ty = Field1Ty;
  9259. Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
  9260. return true;
  9261. }
  9262. if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
  9263. uint64_t ArraySize = ATy->getSize().getZExtValue();
  9264. QualType EltTy = ATy->getElementType();
  9265. CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
  9266. for (uint64_t i = 0; i < ArraySize; ++i) {
  9267. bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
  9268. Field1Off, Field2Ty, Field2Off);
  9269. if (!Ret)
  9270. return false;
  9271. CurOff += EltSize;
  9272. }
  9273. return true;
  9274. }
  9275. if (const auto *RTy = Ty->getAs<RecordType>()) {
  9276. // Structures with either a non-trivial destructor or a non-trivial
  9277. // copy constructor are not eligible for the FP calling convention.
  9278. if (getRecordArgABI(Ty, CGT.getCXXABI()))
  9279. return false;
  9280. if (isEmptyRecord(getContext(), Ty, true))
  9281. return true;
  9282. const RecordDecl *RD = RTy->getDecl();
  9283. // Unions aren't eligible unless they're empty (which is caught above).
  9284. if (RD->isUnion())
  9285. return false;
  9286. int ZeroWidthBitFieldCount = 0;
  9287. for (const FieldDecl *FD : RD->fields()) {
  9288. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  9289. uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
  9290. QualType QTy = FD->getType();
  9291. if (FD->isBitField()) {
  9292. unsigned BitWidth = FD->getBitWidthValue(getContext());
  9293. // Allow a bitfield with a type greater than XLen as long as the
  9294. // bitwidth is XLen or less.
  9295. if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
  9296. QTy = getContext().getIntTypeForBitwidth(XLen, false);
  9297. if (BitWidth == 0) {
  9298. ZeroWidthBitFieldCount++;
  9299. continue;
  9300. }
  9301. }
  9302. bool Ret = detectFPCCEligibleStructHelper(
  9303. QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
  9304. Field1Ty, Field1Off, Field2Ty, Field2Off);
  9305. if (!Ret)
  9306. return false;
  9307. // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
  9308. // or int+fp structs, but are ignored for a struct with an fp field and
  9309. // any number of zero-width bitfields.
  9310. if (Field2Ty && ZeroWidthBitFieldCount > 0)
  9311. return false;
  9312. }
  9313. return Field1Ty != nullptr;
  9314. }
  9315. return false;
  9316. }
  9317. // Determine if a struct is eligible for passing according to the floating
  9318. // point calling convention (i.e., when flattened it contains a single fp
  9319. // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
  9320. // NeededArgGPRs are incremented appropriately.
  9321. bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
  9322. CharUnits &Field1Off,
  9323. llvm::Type *&Field2Ty,
  9324. CharUnits &Field2Off,
  9325. int &NeededArgGPRs,
  9326. int &NeededArgFPRs) const {
  9327. Field1Ty = nullptr;
  9328. Field2Ty = nullptr;
  9329. NeededArgGPRs = 0;
  9330. NeededArgFPRs = 0;
  9331. bool IsCandidate = detectFPCCEligibleStructHelper(
  9332. Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
  9333. // Not really a candidate if we have a single int but no float.
  9334. if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
  9335. return false;
  9336. if (!IsCandidate)
  9337. return false;
  9338. if (Field1Ty && Field1Ty->isFloatingPointTy())
  9339. NeededArgFPRs++;
  9340. else if (Field1Ty)
  9341. NeededArgGPRs++;
  9342. if (Field2Ty && Field2Ty->isFloatingPointTy())
  9343. NeededArgFPRs++;
  9344. else if (Field2Ty)
  9345. NeededArgGPRs++;
  9346. return true;
  9347. }
  9348. // Call getCoerceAndExpand for the two-element flattened struct described by
  9349. // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
  9350. // appropriate coerceToType and unpaddedCoerceToType.
  9351. ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
  9352. llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
  9353. CharUnits Field2Off) const {
  9354. SmallVector<llvm::Type *, 3> CoerceElts;
  9355. SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
  9356. if (!Field1Off.isZero())
  9357. CoerceElts.push_back(llvm::ArrayType::get(
  9358. llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
  9359. CoerceElts.push_back(Field1Ty);
  9360. UnpaddedCoerceElts.push_back(Field1Ty);
  9361. if (!Field2Ty) {
  9362. return ABIArgInfo::getCoerceAndExpand(
  9363. llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
  9364. UnpaddedCoerceElts[0]);
  9365. }
  9366. CharUnits Field2Align =
  9367. CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
  9368. CharUnits Field1End = Field1Off +
  9369. CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
  9370. CharUnits Field2OffNoPadNoPack = Field1End.alignTo(Field2Align);
  9371. CharUnits Padding = CharUnits::Zero();
  9372. if (Field2Off > Field2OffNoPadNoPack)
  9373. Padding = Field2Off - Field2OffNoPadNoPack;
  9374. else if (Field2Off != Field2Align && Field2Off > Field1End)
  9375. Padding = Field2Off - Field1End;
  9376. bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
  9377. if (!Padding.isZero())
  9378. CoerceElts.push_back(llvm::ArrayType::get(
  9379. llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
  9380. CoerceElts.push_back(Field2Ty);
  9381. UnpaddedCoerceElts.push_back(Field2Ty);
  9382. auto CoerceToType =
  9383. llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
  9384. auto UnpaddedCoerceToType =
  9385. llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
  9386. return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
  9387. }
  9388. ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
  9389. int &ArgGPRsLeft,
  9390. int &ArgFPRsLeft) const {
  9391. assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
  9392. Ty = useFirstFieldIfTransparentUnion(Ty);
  9393. // Structures with either a non-trivial destructor or a non-trivial
  9394. // copy constructor are always passed indirectly.
  9395. if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
  9396. if (ArgGPRsLeft)
  9397. ArgGPRsLeft -= 1;
  9398. return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
  9399. CGCXXABI::RAA_DirectInMemory);
  9400. }
  9401. // Ignore empty structs/unions.
  9402. if (isEmptyRecord(getContext(), Ty, true))
  9403. return ABIArgInfo::getIgnore();
  9404. uint64_t Size = getContext().getTypeSize(Ty);
  9405. // Pass floating point values via FPRs if possible.
  9406. if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() &&
  9407. FLen >= Size && ArgFPRsLeft) {
  9408. ArgFPRsLeft--;
  9409. return ABIArgInfo::getDirect();
  9410. }
  9411. // Complex types for the hard float ABI must be passed direct rather than
  9412. // using CoerceAndExpand.
  9413. if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
  9414. QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
  9415. if (getContext().getTypeSize(EltTy) <= FLen) {
  9416. ArgFPRsLeft -= 2;
  9417. return ABIArgInfo::getDirect();
  9418. }
  9419. }
  9420. if (IsFixed && FLen && Ty->isStructureOrClassType()) {
  9421. llvm::Type *Field1Ty = nullptr;
  9422. llvm::Type *Field2Ty = nullptr;
  9423. CharUnits Field1Off = CharUnits::Zero();
  9424. CharUnits Field2Off = CharUnits::Zero();
  9425. int NeededArgGPRs = 0;
  9426. int NeededArgFPRs = 0;
  9427. bool IsCandidate =
  9428. detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
  9429. NeededArgGPRs, NeededArgFPRs);
  9430. if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
  9431. NeededArgFPRs <= ArgFPRsLeft) {
  9432. ArgGPRsLeft -= NeededArgGPRs;
  9433. ArgFPRsLeft -= NeededArgFPRs;
  9434. return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
  9435. Field2Off);
  9436. }
  9437. }
  9438. uint64_t NeededAlign = getContext().getTypeAlign(Ty);
  9439. bool MustUseStack = false;
  9440. // Determine the number of GPRs needed to pass the current argument
  9441. // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
  9442. // register pairs, so may consume 3 registers.
  9443. int NeededArgGPRs = 1;
  9444. if (!IsFixed && NeededAlign == 2 * XLen)
  9445. NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
  9446. else if (Size > XLen && Size <= 2 * XLen)
  9447. NeededArgGPRs = 2;
  9448. if (NeededArgGPRs > ArgGPRsLeft) {
  9449. MustUseStack = true;
  9450. NeededArgGPRs = ArgGPRsLeft;
  9451. }
  9452. ArgGPRsLeft -= NeededArgGPRs;
  9453. if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
  9454. // Treat an enum type as its underlying type.
  9455. if (const EnumType *EnumTy = Ty->getAs<EnumType>())
  9456. Ty = EnumTy->getDecl()->getIntegerType();
  9457. // All integral types are promoted to XLen width, unless passed on the
  9458. // stack.
  9459. if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
  9460. return extendType(Ty);
  9461. }
  9462. if (const auto *EIT = Ty->getAs<BitIntType>()) {
  9463. if (EIT->getNumBits() < XLen && !MustUseStack)
  9464. return extendType(Ty);
  9465. if (EIT->getNumBits() > 128 ||
  9466. (!getContext().getTargetInfo().hasInt128Type() &&
  9467. EIT->getNumBits() > 64))
  9468. return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
  9469. }
  9470. return ABIArgInfo::getDirect();
  9471. }
  9472. // Aggregates which are <= 2*XLen will be passed in registers if possible,
  9473. // so coerce to integers.
  9474. if (Size <= 2 * XLen) {
  9475. unsigned Alignment = getContext().getTypeAlign(Ty);
  9476. // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
  9477. // required, and a 2-element XLen array if only XLen alignment is required.
  9478. if (Size <= XLen) {
  9479. return ABIArgInfo::getDirect(
  9480. llvm::IntegerType::get(getVMContext(), XLen));
  9481. } else if (Alignment == 2 * XLen) {
  9482. return ABIArgInfo::getDirect(
  9483. llvm::IntegerType::get(getVMContext(), 2 * XLen));
  9484. } else {
  9485. return ABIArgInfo::getDirect(llvm::ArrayType::get(
  9486. llvm::IntegerType::get(getVMContext(), XLen), 2));
  9487. }
  9488. }
  9489. return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
  9490. }
  9491. ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
  9492. if (RetTy->isVoidType())
  9493. return ABIArgInfo::getIgnore();
  9494. int ArgGPRsLeft = 2;
  9495. int ArgFPRsLeft = FLen ? 2 : 0;
  9496. // The rules for return and argument types are the same, so defer to
  9497. // classifyArgumentType.
  9498. return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
  9499. ArgFPRsLeft);
  9500. }
  9501. Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
  9502. QualType Ty) const {
  9503. CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
  9504. // Empty records are ignored for parameter passing purposes.
  9505. if (isEmptyRecord(getContext(), Ty, true)) {
  9506. Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
  9507. Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
  9508. return Addr;
  9509. }
  9510. auto TInfo = getContext().getTypeInfoInChars(Ty);
  9511. // Arguments bigger than 2*Xlen bytes are passed indirectly.
  9512. bool IsIndirect = TInfo.Width > 2 * SlotSize;
  9513. return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo,
  9514. SlotSize, /*AllowHigherAlign=*/true);
  9515. }
  9516. ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
  9517. int TySize = getContext().getTypeSize(Ty);
  9518. // RV64 ABI requires unsigned 32 bit integers to be sign extended.
  9519. if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
  9520. return ABIArgInfo::getSignExtend(Ty);
  9521. return ABIArgInfo::getExtend(Ty);
  9522. }
  9523. namespace {
  9524. class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
  9525. public:
  9526. RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
  9527. unsigned FLen)
  9528. : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {}
  9529. void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
  9530. CodeGen::CodeGenModule &CGM) const override {
  9531. const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
  9532. if (!FD) return;
  9533. const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
  9534. if (!Attr)
  9535. return;
  9536. const char *Kind;
  9537. switch (Attr->getInterrupt()) {
  9538. case RISCVInterruptAttr::user: Kind = "user"; break;
  9539. case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
  9540. case RISCVInterruptAttr::machine: Kind = "machine"; break;
  9541. }
  9542. auto *Fn = cast<llvm::Function>(GV);
  9543. Fn->addFnAttr("interrupt", Kind);
  9544. }
  9545. };
  9546. } // namespace
  9547. //===----------------------------------------------------------------------===//
  9548. // VE ABI Implementation.
  9549. //
  9550. namespace {
  9551. class VEABIInfo : public DefaultABIInfo {
  9552. public:
  9553. VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
  9554. private:
  9555. ABIArgInfo classifyReturnType(QualType RetTy) const;
  9556. ABIArgInfo classifyArgumentType(QualType RetTy) const;
  9557. void computeInfo(CGFunctionInfo &FI) const override;
  9558. };
  9559. } // end anonymous namespace
  9560. ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const {
  9561. if (Ty->isAnyComplexType())
  9562. return ABIArgInfo::getDirect();
  9563. uint64_t Size = getContext().getTypeSize(Ty);
  9564. if (Size < 64 && Ty->isIntegerType())
  9565. return ABIArgInfo::getExtend(Ty);
  9566. return DefaultABIInfo::classifyReturnType(Ty);
  9567. }
  9568. ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const {
  9569. if (Ty->isAnyComplexType())
  9570. return ABIArgInfo::getDirect();
  9571. uint64_t Size = getContext().getTypeSize(Ty);
  9572. if (Size < 64 && Ty->isIntegerType())
  9573. return ABIArgInfo::getExtend(Ty);
  9574. return DefaultABIInfo::classifyArgumentType(Ty);
  9575. }
  9576. void VEABIInfo::computeInfo(CGFunctionInfo &FI) const {
  9577. FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
  9578. for (auto &Arg : FI.arguments())
  9579. Arg.info = classifyArgumentType(Arg.type);
  9580. }
  9581. namespace {
  9582. class VETargetCodeGenInfo : public TargetCodeGenInfo {
  9583. public:
  9584. VETargetCodeGenInfo(CodeGenTypes &CGT)
  9585. : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {}
  9586. // VE ABI requires the arguments of variadic and prototype-less functions
  9587. // are passed in both registers and memory.
  9588. bool isNoProtoCallVariadic(const CallArgList &args,
  9589. const FunctionNoProtoType *fnType) const override {
  9590. return true;
  9591. }
  9592. };
  9593. } // end anonymous namespace
  9594. //===----------------------------------------------------------------------===//
  9595. // Driver code
  9596. //===----------------------------------------------------------------------===//
  9597. bool CodeGenModule::supportsCOMDAT() const {
  9598. return getTriple().supportsCOMDAT();
  9599. }
  9600. const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
  9601. if (TheTargetCodeGenInfo)
  9602. return *TheTargetCodeGenInfo;
  9603. // Helper to set the unique_ptr while still keeping the return value.
  9604. auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
  9605. this->TheTargetCodeGenInfo.reset(P);
  9606. return *P;
  9607. };
  9608. const llvm::Triple &Triple = getTarget().getTriple();
  9609. switch (Triple.getArch()) {
  9610. default:
  9611. return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
  9612. case llvm::Triple::le32:
  9613. return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
  9614. case llvm::Triple::m68k:
  9615. return SetCGInfo(new M68kTargetCodeGenInfo(Types));
  9616. case llvm::Triple::mips:
  9617. case llvm::Triple::mipsel:
  9618. if (Triple.getOS() == llvm::Triple::NaCl)
  9619. return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
  9620. return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
  9621. case llvm::Triple::mips64:
  9622. case llvm::Triple::mips64el:
  9623. return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
  9624. case llvm::Triple::avr: {
  9625. // For passing parameters, R8~R25 are used on avr, and R18~R25 are used
  9626. // on avrtiny. For passing return value, R18~R25 are used on avr, and
  9627. // R22~R25 are used on avrtiny.
  9628. unsigned NPR = getTarget().getABI() == "avrtiny" ? 6 : 18;
  9629. unsigned NRR = getTarget().getABI() == "avrtiny" ? 4 : 8;
  9630. return SetCGInfo(new AVRTargetCodeGenInfo(Types, NPR, NRR));
  9631. }
  9632. case llvm::Triple::aarch64:
  9633. case llvm::Triple::aarch64_32:
  9634. case llvm::Triple::aarch64_be: {
  9635. AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
  9636. if (getTarget().getABI() == "darwinpcs")
  9637. Kind = AArch64ABIInfo::DarwinPCS;
  9638. else if (Triple.isOSWindows())
  9639. return SetCGInfo(
  9640. new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
  9641. return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
  9642. }
  9643. case llvm::Triple::wasm32:
  9644. case llvm::Triple::wasm64: {
  9645. WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP;
  9646. if (getTarget().getABI() == "experimental-mv")
  9647. Kind = WebAssemblyABIInfo::ExperimentalMV;
  9648. return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind));
  9649. }
  9650. case llvm::Triple::arm:
  9651. case llvm::Triple::armeb:
  9652. case llvm::Triple::thumb:
  9653. case llvm::Triple::thumbeb: {
  9654. if (Triple.getOS() == llvm::Triple::Win32) {
  9655. return SetCGInfo(
  9656. new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
  9657. }
  9658. ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
  9659. StringRef ABIStr = getTarget().getABI();
  9660. if (ABIStr == "apcs-gnu")
  9661. Kind = ARMABIInfo::APCS;
  9662. else if (ABIStr == "aapcs16")
  9663. Kind = ARMABIInfo::AAPCS16_VFP;
  9664. else if (CodeGenOpts.FloatABI == "hard" ||
  9665. (CodeGenOpts.FloatABI != "soft" &&
  9666. (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
  9667. Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
  9668. Triple.getEnvironment() == llvm::Triple::EABIHF)))
  9669. Kind = ARMABIInfo::AAPCS_VFP;
  9670. return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
  9671. }
  9672. case llvm::Triple::ppc: {
  9673. if (Triple.isOSAIX())
  9674. return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false));
  9675. bool IsSoftFloat =
  9676. CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe");
  9677. bool RetSmallStructInRegABI =
  9678. PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
  9679. return SetCGInfo(
  9680. new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
  9681. }
  9682. case llvm::Triple::ppcle: {
  9683. bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
  9684. bool RetSmallStructInRegABI =
  9685. PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
  9686. return SetCGInfo(
  9687. new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
  9688. }
  9689. case llvm::Triple::ppc64:
  9690. if (Triple.isOSAIX())
  9691. return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true));
  9692. if (Triple.isOSBinFormatELF()) {
  9693. PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
  9694. if (getTarget().getABI() == "elfv2")
  9695. Kind = PPC64_SVR4_ABIInfo::ELFv2;
  9696. bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
  9697. return SetCGInfo(
  9698. new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
  9699. }
  9700. return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
  9701. case llvm::Triple::ppc64le: {
  9702. assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
  9703. PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
  9704. if (getTarget().getABI() == "elfv1")
  9705. Kind = PPC64_SVR4_ABIInfo::ELFv1;
  9706. bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
  9707. return SetCGInfo(
  9708. new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, IsSoftFloat));
  9709. }
  9710. case llvm::Triple::nvptx:
  9711. case llvm::Triple::nvptx64:
  9712. return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
  9713. case llvm::Triple::msp430:
  9714. return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
  9715. case llvm::Triple::riscv32:
  9716. case llvm::Triple::riscv64: {
  9717. StringRef ABIStr = getTarget().getABI();
  9718. unsigned XLen = getTarget().getPointerWidth(0);
  9719. unsigned ABIFLen = 0;
  9720. if (ABIStr.endswith("f"))
  9721. ABIFLen = 32;
  9722. else if (ABIStr.endswith("d"))
  9723. ABIFLen = 64;
  9724. return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
  9725. }
  9726. case llvm::Triple::systemz: {
  9727. bool SoftFloat = CodeGenOpts.FloatABI == "soft";
  9728. bool HasVector = !SoftFloat && getTarget().getABI() == "vector";
  9729. return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat));
  9730. }
  9731. case llvm::Triple::tce:
  9732. case llvm::Triple::tcele:
  9733. return SetCGInfo(new TCETargetCodeGenInfo(Types));
  9734. case llvm::Triple::x86: {
  9735. bool IsDarwinVectorABI = Triple.isOSDarwin();
  9736. bool RetSmallStructInRegABI =
  9737. X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
  9738. bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
  9739. if (Triple.getOS() == llvm::Triple::Win32) {
  9740. return SetCGInfo(new WinX86_32TargetCodeGenInfo(
  9741. Types, IsDarwinVectorABI, RetSmallStructInRegABI,
  9742. IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
  9743. } else {
  9744. return SetCGInfo(new X86_32TargetCodeGenInfo(
  9745. Types, IsDarwinVectorABI, RetSmallStructInRegABI,
  9746. IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
  9747. CodeGenOpts.FloatABI == "soft"));
  9748. }
  9749. }
  9750. case llvm::Triple::x86_64: {
  9751. StringRef ABI = getTarget().getABI();
  9752. X86AVXABILevel AVXLevel =
  9753. (ABI == "avx512"
  9754. ? X86AVXABILevel::AVX512
  9755. : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
  9756. switch (Triple.getOS()) {
  9757. case llvm::Triple::Win32:
  9758. return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
  9759. default:
  9760. return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
  9761. }
  9762. }
  9763. case llvm::Triple::hexagon:
  9764. return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
  9765. case llvm::Triple::lanai:
  9766. return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
  9767. case llvm::Triple::r600:
  9768. return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
  9769. case llvm::Triple::amdgcn:
  9770. return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
  9771. case llvm::Triple::sparc:
  9772. return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
  9773. case llvm::Triple::sparcv9:
  9774. return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
  9775. case llvm::Triple::xcore:
  9776. return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
  9777. case llvm::Triple::arc:
  9778. return SetCGInfo(new ARCTargetCodeGenInfo(Types));
  9779. case llvm::Triple::spir:
  9780. case llvm::Triple::spir64:
  9781. return SetCGInfo(new CommonSPIRTargetCodeGenInfo(Types));
  9782. case llvm::Triple::spirv32:
  9783. case llvm::Triple::spirv64:
  9784. return SetCGInfo(new SPIRVTargetCodeGenInfo(Types));
  9785. case llvm::Triple::ve:
  9786. return SetCGInfo(new VETargetCodeGenInfo(Types));
  9787. }
  9788. }
  9789. /// Create an OpenCL kernel for an enqueued block.
  9790. ///
  9791. /// The kernel has the same function type as the block invoke function. Its
  9792. /// name is the name of the block invoke function postfixed with "_kernel".
  9793. /// It simply calls the block invoke function then returns.
  9794. llvm::Function *
  9795. TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
  9796. llvm::Function *Invoke,
  9797. llvm::Value *BlockLiteral) const {
  9798. auto *InvokeFT = Invoke->getFunctionType();
  9799. llvm::SmallVector<llvm::Type *, 2> ArgTys;
  9800. for (auto &P : InvokeFT->params())
  9801. ArgTys.push_back(P);
  9802. auto &C = CGF.getLLVMContext();
  9803. std::string Name = Invoke->getName().str() + "_kernel";
  9804. auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
  9805. auto *F = llvm::Function::Create(FT, llvm::GlobalValue::ExternalLinkage, Name,
  9806. &CGF.CGM.getModule());
  9807. auto IP = CGF.Builder.saveIP();
  9808. auto *BB = llvm::BasicBlock::Create(C, "entry", F);
  9809. auto &Builder = CGF.Builder;
  9810. Builder.SetInsertPoint(BB);
  9811. llvm::SmallVector<llvm::Value *, 2> Args;
  9812. for (auto &A : F->args())
  9813. Args.push_back(&A);
  9814. llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
  9815. call->setCallingConv(Invoke->getCallingConv());
  9816. Builder.CreateRetVoid();
  9817. Builder.restoreIP(IP);
  9818. return F;
  9819. }
  9820. /// Create an OpenCL kernel for an enqueued block.
  9821. ///
  9822. /// The type of the first argument (the block literal) is the struct type
  9823. /// of the block literal instead of a pointer type. The first argument
  9824. /// (block literal) is passed directly by value to the kernel. The kernel
  9825. /// allocates the same type of struct on stack and stores the block literal
  9826. /// to it and passes its pointer to the block invoke function. The kernel
  9827. /// has "enqueued-block" function attribute and kernel argument metadata.
  9828. llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
  9829. CodeGenFunction &CGF, llvm::Function *Invoke,
  9830. llvm::Value *BlockLiteral) const {
  9831. auto &Builder = CGF.Builder;
  9832. auto &C = CGF.getLLVMContext();
  9833. auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
  9834. auto *InvokeFT = Invoke->getFunctionType();
  9835. llvm::SmallVector<llvm::Type *, 2> ArgTys;
  9836. llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
  9837. llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
  9838. llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
  9839. llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
  9840. llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
  9841. llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
  9842. ArgTys.push_back(BlockTy);
  9843. ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
  9844. AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
  9845. ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
  9846. ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
  9847. AccessQuals.push_back(llvm::MDString::get(C, "none"));
  9848. ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
  9849. for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
  9850. ArgTys.push_back(InvokeFT->getParamType(I));
  9851. ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
  9852. AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
  9853. AccessQuals.push_back(llvm::MDString::get(C, "none"));
  9854. ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
  9855. ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
  9856. ArgNames.push_back(
  9857. llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
  9858. }
  9859. std::string Name = Invoke->getName().str() + "_kernel";
  9860. auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
  9861. auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
  9862. &CGF.CGM.getModule());
  9863. F->addFnAttr("enqueued-block");
  9864. auto IP = CGF.Builder.saveIP();
  9865. auto *BB = llvm::BasicBlock::Create(C, "entry", F);
  9866. Builder.SetInsertPoint(BB);
  9867. const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy);
  9868. auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
  9869. BlockPtr->setAlignment(BlockAlign);
  9870. Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
  9871. auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
  9872. llvm::SmallVector<llvm::Value *, 2> Args;
  9873. Args.push_back(Cast);
  9874. for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
  9875. Args.push_back(I);
  9876. llvm::CallInst *call = Builder.CreateCall(Invoke, Args);
  9877. call->setCallingConv(Invoke->getCallingConv());
  9878. Builder.CreateRetVoid();
  9879. Builder.restoreIP(IP);
  9880. F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
  9881. F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
  9882. F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
  9883. F->setMetadata("kernel_arg_base_type",
  9884. llvm::MDNode::get(C, ArgBaseTypeNames));
  9885. F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
  9886. if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
  9887. F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
  9888. return F;
  9889. }