ASTContext.cpp 380 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549
  1. //===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
  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. // This file implements the ASTContext interface.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ASTContext.h"
  13. #include "CXXABI.h"
  14. #include "clang/AST/APValue.h"
  15. #include "clang/AST/ASTMutationListener.h"
  16. #include "clang/AST/ASTTypeTraits.h"
  17. #include "clang/AST/Attr.h"
  18. #include "clang/AST/AttrIterator.h"
  19. #include "clang/AST/CharUnits.h"
  20. #include "clang/AST/Comment.h"
  21. #include "clang/AST/Decl.h"
  22. #include "clang/AST/DeclBase.h"
  23. #include "clang/AST/DeclCXX.h"
  24. #include "clang/AST/DeclContextInternals.h"
  25. #include "clang/AST/DeclObjC.h"
  26. #include "clang/AST/DeclOpenMP.h"
  27. #include "clang/AST/DeclTemplate.h"
  28. #include "clang/AST/DeclarationName.h"
  29. #include "clang/AST/Expr.h"
  30. #include "clang/AST/ExprCXX.h"
  31. #include "clang/AST/ExternalASTSource.h"
  32. #include "clang/AST/Mangle.h"
  33. #include "clang/AST/MangleNumberingContext.h"
  34. #include "clang/AST/NestedNameSpecifier.h"
  35. #include "clang/AST/RawCommentList.h"
  36. #include "clang/AST/RecordLayout.h"
  37. #include "clang/AST/RecursiveASTVisitor.h"
  38. #include "clang/AST/Stmt.h"
  39. #include "clang/AST/TemplateBase.h"
  40. #include "clang/AST/TemplateName.h"
  41. #include "clang/AST/Type.h"
  42. #include "clang/AST/TypeLoc.h"
  43. #include "clang/AST/UnresolvedSet.h"
  44. #include "clang/AST/VTableBuilder.h"
  45. #include "clang/Basic/AddressSpaces.h"
  46. #include "clang/Basic/Builtins.h"
  47. #include "clang/Basic/CommentOptions.h"
  48. #include "clang/Basic/ExceptionSpecificationType.h"
  49. #include "clang/Basic/FixedPoint.h"
  50. #include "clang/Basic/IdentifierTable.h"
  51. #include "clang/Basic/LLVM.h"
  52. #include "clang/Basic/LangOptions.h"
  53. #include "clang/Basic/Linkage.h"
  54. #include "clang/Basic/ObjCRuntime.h"
  55. #include "clang/Basic/SanitizerBlacklist.h"
  56. #include "clang/Basic/SourceLocation.h"
  57. #include "clang/Basic/SourceManager.h"
  58. #include "clang/Basic/Specifiers.h"
  59. #include "clang/Basic/TargetCXXABI.h"
  60. #include "clang/Basic/TargetInfo.h"
  61. #include "clang/Basic/XRayLists.h"
  62. #include "llvm/ADT/APInt.h"
  63. #include "llvm/ADT/APSInt.h"
  64. #include "llvm/ADT/ArrayRef.h"
  65. #include "llvm/ADT/DenseMap.h"
  66. #include "llvm/ADT/DenseSet.h"
  67. #include "llvm/ADT/FoldingSet.h"
  68. #include "llvm/ADT/None.h"
  69. #include "llvm/ADT/Optional.h"
  70. #include "llvm/ADT/PointerUnion.h"
  71. #include "llvm/ADT/STLExtras.h"
  72. #include "llvm/ADT/SmallPtrSet.h"
  73. #include "llvm/ADT/SmallVector.h"
  74. #include "llvm/ADT/StringExtras.h"
  75. #include "llvm/ADT/StringRef.h"
  76. #include "llvm/ADT/Triple.h"
  77. #include "llvm/Support/Capacity.h"
  78. #include "llvm/Support/Casting.h"
  79. #include "llvm/Support/Compiler.h"
  80. #include "llvm/Support/ErrorHandling.h"
  81. #include "llvm/Support/MathExtras.h"
  82. #include "llvm/Support/raw_ostream.h"
  83. #include <algorithm>
  84. #include <cassert>
  85. #include <cstddef>
  86. #include <cstdint>
  87. #include <cstdlib>
  88. #include <map>
  89. #include <memory>
  90. #include <string>
  91. #include <tuple>
  92. #include <utility>
  93. using namespace clang;
  94. enum FloatingRank {
  95. Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
  96. };
  97. RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
  98. assert(D);
  99. // If we already tried to load comments but there are none,
  100. // we won't find anything.
  101. if (CommentsLoaded && Comments.getComments().empty())
  102. return nullptr;
  103. // User can not attach documentation to implicit declarations.
  104. if (D->isImplicit())
  105. return nullptr;
  106. // User can not attach documentation to implicit instantiations.
  107. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  108. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  109. return nullptr;
  110. }
  111. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  112. if (VD->isStaticDataMember() &&
  113. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  114. return nullptr;
  115. }
  116. if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
  117. if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  118. return nullptr;
  119. }
  120. if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
  121. TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
  122. if (TSK == TSK_ImplicitInstantiation ||
  123. TSK == TSK_Undeclared)
  124. return nullptr;
  125. }
  126. if (const auto *ED = dyn_cast<EnumDecl>(D)) {
  127. if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  128. return nullptr;
  129. }
  130. if (const auto *TD = dyn_cast<TagDecl>(D)) {
  131. // When tag declaration (but not definition!) is part of the
  132. // decl-specifier-seq of some other declaration, it doesn't get comment
  133. if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
  134. return nullptr;
  135. }
  136. // TODO: handle comments for function parameters properly.
  137. if (isa<ParmVarDecl>(D))
  138. return nullptr;
  139. // TODO: we could look up template parameter documentation in the template
  140. // documentation.
  141. if (isa<TemplateTypeParmDecl>(D) ||
  142. isa<NonTypeTemplateParmDecl>(D) ||
  143. isa<TemplateTemplateParmDecl>(D))
  144. return nullptr;
  145. // Find declaration location.
  146. // For Objective-C declarations we generally don't expect to have multiple
  147. // declarators, thus use declaration starting location as the "declaration
  148. // location".
  149. // For all other declarations multiple declarators are used quite frequently,
  150. // so we use the location of the identifier as the "declaration location".
  151. SourceLocation DeclLoc;
  152. if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
  153. isa<ObjCPropertyDecl>(D) ||
  154. isa<RedeclarableTemplateDecl>(D) ||
  155. isa<ClassTemplateSpecializationDecl>(D))
  156. DeclLoc = D->getBeginLoc();
  157. else {
  158. DeclLoc = D->getLocation();
  159. if (DeclLoc.isMacroID()) {
  160. if (isa<TypedefDecl>(D)) {
  161. // If location of the typedef name is in a macro, it is because being
  162. // declared via a macro. Try using declaration's starting location as
  163. // the "declaration location".
  164. DeclLoc = D->getBeginLoc();
  165. } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
  166. // If location of the tag decl is inside a macro, but the spelling of
  167. // the tag name comes from a macro argument, it looks like a special
  168. // macro like NS_ENUM is being used to define the tag decl. In that
  169. // case, adjust the source location to the expansion loc so that we can
  170. // attach the comment to the tag decl.
  171. if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
  172. TD->isCompleteDefinition())
  173. DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
  174. }
  175. }
  176. }
  177. // If the declaration doesn't map directly to a location in a file, we
  178. // can't find the comment.
  179. if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
  180. return nullptr;
  181. if (!CommentsLoaded && ExternalSource) {
  182. ExternalSource->ReadComments();
  183. #ifndef NDEBUG
  184. ArrayRef<RawComment *> RawComments = Comments.getComments();
  185. assert(std::is_sorted(RawComments.begin(), RawComments.end(),
  186. BeforeThanCompare<RawComment>(SourceMgr)));
  187. #endif
  188. CommentsLoaded = true;
  189. }
  190. ArrayRef<RawComment *> RawComments = Comments.getComments();
  191. // If there are no comments anywhere, we won't find anything.
  192. if (RawComments.empty())
  193. return nullptr;
  194. // Find the comment that occurs just after this declaration.
  195. ArrayRef<RawComment *>::iterator Comment;
  196. {
  197. // When searching for comments during parsing, the comment we are looking
  198. // for is usually among the last two comments we parsed -- check them
  199. // first.
  200. RawComment CommentAtDeclLoc(
  201. SourceMgr, SourceRange(DeclLoc), LangOpts.CommentOpts, false);
  202. BeforeThanCompare<RawComment> Compare(SourceMgr);
  203. ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
  204. bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
  205. if (!Found && RawComments.size() >= 2) {
  206. MaybeBeforeDecl--;
  207. Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
  208. }
  209. if (Found) {
  210. Comment = MaybeBeforeDecl + 1;
  211. assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
  212. &CommentAtDeclLoc, Compare));
  213. } else {
  214. // Slow path.
  215. Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
  216. &CommentAtDeclLoc, Compare);
  217. }
  218. }
  219. // Decompose the location for the declaration and find the beginning of the
  220. // file buffer.
  221. std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
  222. // First check whether we have a trailing comment.
  223. if (Comment != RawComments.end() &&
  224. ((*Comment)->isDocumentation() || LangOpts.CommentOpts.ParseAllComments)
  225. && (*Comment)->isTrailingComment() &&
  226. (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
  227. isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
  228. std::pair<FileID, unsigned> CommentBeginDecomp
  229. = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
  230. // Check that Doxygen trailing comment comes after the declaration, starts
  231. // on the same line and in the same file as the declaration.
  232. if (DeclLocDecomp.first == CommentBeginDecomp.first &&
  233. SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
  234. == SourceMgr.getLineNumber(CommentBeginDecomp.first,
  235. CommentBeginDecomp.second)) {
  236. return *Comment;
  237. }
  238. }
  239. // The comment just after the declaration was not a trailing comment.
  240. // Let's look at the previous comment.
  241. if (Comment == RawComments.begin())
  242. return nullptr;
  243. --Comment;
  244. // Check that we actually have a non-member Doxygen comment.
  245. if (!((*Comment)->isDocumentation() ||
  246. LangOpts.CommentOpts.ParseAllComments) ||
  247. (*Comment)->isTrailingComment())
  248. return nullptr;
  249. // Decompose the end of the comment.
  250. std::pair<FileID, unsigned> CommentEndDecomp
  251. = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
  252. // If the comment and the declaration aren't in the same file, then they
  253. // aren't related.
  254. if (DeclLocDecomp.first != CommentEndDecomp.first)
  255. return nullptr;
  256. // Get the corresponding buffer.
  257. bool Invalid = false;
  258. const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
  259. &Invalid).data();
  260. if (Invalid)
  261. return nullptr;
  262. // Extract text between the comment and declaration.
  263. StringRef Text(Buffer + CommentEndDecomp.second,
  264. DeclLocDecomp.second - CommentEndDecomp.second);
  265. // There should be no other declarations or preprocessor directives between
  266. // comment and declaration.
  267. if (Text.find_first_of(";{}#@") != StringRef::npos)
  268. return nullptr;
  269. return *Comment;
  270. }
  271. /// If we have a 'templated' declaration for a template, adjust 'D' to
  272. /// refer to the actual template.
  273. /// If we have an implicit instantiation, adjust 'D' to refer to template.
  274. static const Decl *adjustDeclToTemplate(const Decl *D) {
  275. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  276. // Is this function declaration part of a function template?
  277. if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
  278. return FTD;
  279. // Nothing to do if function is not an implicit instantiation.
  280. if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
  281. return D;
  282. // Function is an implicit instantiation of a function template?
  283. if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
  284. return FTD;
  285. // Function is instantiated from a member definition of a class template?
  286. if (const FunctionDecl *MemberDecl =
  287. FD->getInstantiatedFromMemberFunction())
  288. return MemberDecl;
  289. return D;
  290. }
  291. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  292. // Static data member is instantiated from a member definition of a class
  293. // template?
  294. if (VD->isStaticDataMember())
  295. if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
  296. return MemberDecl;
  297. return D;
  298. }
  299. if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
  300. // Is this class declaration part of a class template?
  301. if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
  302. return CTD;
  303. // Class is an implicit instantiation of a class template or partial
  304. // specialization?
  305. if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
  306. if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
  307. return D;
  308. llvm::PointerUnion<ClassTemplateDecl *,
  309. ClassTemplatePartialSpecializationDecl *>
  310. PU = CTSD->getSpecializedTemplateOrPartial();
  311. return PU.is<ClassTemplateDecl*>() ?
  312. static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
  313. static_cast<const Decl*>(
  314. PU.get<ClassTemplatePartialSpecializationDecl *>());
  315. }
  316. // Class is instantiated from a member definition of a class template?
  317. if (const MemberSpecializationInfo *Info =
  318. CRD->getMemberSpecializationInfo())
  319. return Info->getInstantiatedFrom();
  320. return D;
  321. }
  322. if (const auto *ED = dyn_cast<EnumDecl>(D)) {
  323. // Enum is instantiated from a member definition of a class template?
  324. if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
  325. return MemberDecl;
  326. return D;
  327. }
  328. // FIXME: Adjust alias templates?
  329. return D;
  330. }
  331. const RawComment *ASTContext::getRawCommentForAnyRedecl(
  332. const Decl *D,
  333. const Decl **OriginalDecl) const {
  334. D = adjustDeclToTemplate(D);
  335. // Check whether we have cached a comment for this declaration already.
  336. {
  337. llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
  338. RedeclComments.find(D);
  339. if (Pos != RedeclComments.end()) {
  340. const RawCommentAndCacheFlags &Raw = Pos->second;
  341. if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
  342. if (OriginalDecl)
  343. *OriginalDecl = Raw.getOriginalDecl();
  344. return Raw.getRaw();
  345. }
  346. }
  347. }
  348. // Search for comments attached to declarations in the redeclaration chain.
  349. const RawComment *RC = nullptr;
  350. const Decl *OriginalDeclForRC = nullptr;
  351. for (auto I : D->redecls()) {
  352. llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
  353. RedeclComments.find(I);
  354. if (Pos != RedeclComments.end()) {
  355. const RawCommentAndCacheFlags &Raw = Pos->second;
  356. if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
  357. RC = Raw.getRaw();
  358. OriginalDeclForRC = Raw.getOriginalDecl();
  359. break;
  360. }
  361. } else {
  362. RC = getRawCommentForDeclNoCache(I);
  363. OriginalDeclForRC = I;
  364. RawCommentAndCacheFlags Raw;
  365. if (RC) {
  366. // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
  367. // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
  368. Raw.setKind(RawCommentAndCacheFlags::FromDecl);
  369. Raw.setRaw(RC);
  370. } else
  371. Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
  372. Raw.setOriginalDecl(I);
  373. RedeclComments[I] = Raw;
  374. if (RC)
  375. break;
  376. }
  377. }
  378. // If we found a comment, it should be a documentation comment.
  379. assert(!RC || RC->isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
  380. if (OriginalDecl)
  381. *OriginalDecl = OriginalDeclForRC;
  382. // Update cache for every declaration in the redeclaration chain.
  383. RawCommentAndCacheFlags Raw;
  384. Raw.setRaw(RC);
  385. Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
  386. Raw.setOriginalDecl(OriginalDeclForRC);
  387. for (auto I : D->redecls()) {
  388. RawCommentAndCacheFlags &R = RedeclComments[I];
  389. if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
  390. R = Raw;
  391. }
  392. return RC;
  393. }
  394. static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
  395. SmallVectorImpl<const NamedDecl *> &Redeclared) {
  396. const DeclContext *DC = ObjCMethod->getDeclContext();
  397. if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
  398. const ObjCInterfaceDecl *ID = IMD->getClassInterface();
  399. if (!ID)
  400. return;
  401. // Add redeclared method here.
  402. for (const auto *Ext : ID->known_extensions()) {
  403. if (ObjCMethodDecl *RedeclaredMethod =
  404. Ext->getMethod(ObjCMethod->getSelector(),
  405. ObjCMethod->isInstanceMethod()))
  406. Redeclared.push_back(RedeclaredMethod);
  407. }
  408. }
  409. }
  410. comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
  411. const Decl *D) const {
  412. auto *ThisDeclInfo = new (*this) comments::DeclInfo;
  413. ThisDeclInfo->CommentDecl = D;
  414. ThisDeclInfo->IsFilled = false;
  415. ThisDeclInfo->fill();
  416. ThisDeclInfo->CommentDecl = FC->getDecl();
  417. if (!ThisDeclInfo->TemplateParameters)
  418. ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
  419. comments::FullComment *CFC =
  420. new (*this) comments::FullComment(FC->getBlocks(),
  421. ThisDeclInfo);
  422. return CFC;
  423. }
  424. comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
  425. const RawComment *RC = getRawCommentForDeclNoCache(D);
  426. return RC ? RC->parse(*this, nullptr, D) : nullptr;
  427. }
  428. comments::FullComment *ASTContext::getCommentForDecl(
  429. const Decl *D,
  430. const Preprocessor *PP) const {
  431. if (D->isInvalidDecl())
  432. return nullptr;
  433. D = adjustDeclToTemplate(D);
  434. const Decl *Canonical = D->getCanonicalDecl();
  435. llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
  436. ParsedComments.find(Canonical);
  437. if (Pos != ParsedComments.end()) {
  438. if (Canonical != D) {
  439. comments::FullComment *FC = Pos->second;
  440. comments::FullComment *CFC = cloneFullComment(FC, D);
  441. return CFC;
  442. }
  443. return Pos->second;
  444. }
  445. const Decl *OriginalDecl;
  446. const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
  447. if (!RC) {
  448. if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
  449. SmallVector<const NamedDecl*, 8> Overridden;
  450. const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
  451. if (OMD && OMD->isPropertyAccessor())
  452. if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
  453. if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
  454. return cloneFullComment(FC, D);
  455. if (OMD)
  456. addRedeclaredMethods(OMD, Overridden);
  457. getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
  458. for (unsigned i = 0, e = Overridden.size(); i < e; i++)
  459. if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
  460. return cloneFullComment(FC, D);
  461. }
  462. else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  463. // Attach any tag type's documentation to its typedef if latter
  464. // does not have one of its own.
  465. QualType QT = TD->getUnderlyingType();
  466. if (const auto *TT = QT->getAs<TagType>())
  467. if (const Decl *TD = TT->getDecl())
  468. if (comments::FullComment *FC = getCommentForDecl(TD, PP))
  469. return cloneFullComment(FC, D);
  470. }
  471. else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
  472. while (IC->getSuperClass()) {
  473. IC = IC->getSuperClass();
  474. if (comments::FullComment *FC = getCommentForDecl(IC, PP))
  475. return cloneFullComment(FC, D);
  476. }
  477. }
  478. else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
  479. if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
  480. if (comments::FullComment *FC = getCommentForDecl(IC, PP))
  481. return cloneFullComment(FC, D);
  482. }
  483. else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
  484. if (!(RD = RD->getDefinition()))
  485. return nullptr;
  486. // Check non-virtual bases.
  487. for (const auto &I : RD->bases()) {
  488. if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
  489. continue;
  490. QualType Ty = I.getType();
  491. if (Ty.isNull())
  492. continue;
  493. if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
  494. if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
  495. continue;
  496. if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
  497. return cloneFullComment(FC, D);
  498. }
  499. }
  500. // Check virtual bases.
  501. for (const auto &I : RD->vbases()) {
  502. if (I.getAccessSpecifier() != AS_public)
  503. continue;
  504. QualType Ty = I.getType();
  505. if (Ty.isNull())
  506. continue;
  507. if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
  508. if (!(VirtualBase= VirtualBase->getDefinition()))
  509. continue;
  510. if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
  511. return cloneFullComment(FC, D);
  512. }
  513. }
  514. }
  515. return nullptr;
  516. }
  517. // If the RawComment was attached to other redeclaration of this Decl, we
  518. // should parse the comment in context of that other Decl. This is important
  519. // because comments can contain references to parameter names which can be
  520. // different across redeclarations.
  521. if (D != OriginalDecl)
  522. return getCommentForDecl(OriginalDecl, PP);
  523. comments::FullComment *FC = RC->parse(*this, PP, D);
  524. ParsedComments[Canonical] = FC;
  525. return FC;
  526. }
  527. void
  528. ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
  529. TemplateTemplateParmDecl *Parm) {
  530. ID.AddInteger(Parm->getDepth());
  531. ID.AddInteger(Parm->getPosition());
  532. ID.AddBoolean(Parm->isParameterPack());
  533. TemplateParameterList *Params = Parm->getTemplateParameters();
  534. ID.AddInteger(Params->size());
  535. for (TemplateParameterList::const_iterator P = Params->begin(),
  536. PEnd = Params->end();
  537. P != PEnd; ++P) {
  538. if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
  539. ID.AddInteger(0);
  540. ID.AddBoolean(TTP->isParameterPack());
  541. continue;
  542. }
  543. if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
  544. ID.AddInteger(1);
  545. ID.AddBoolean(NTTP->isParameterPack());
  546. ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
  547. if (NTTP->isExpandedParameterPack()) {
  548. ID.AddBoolean(true);
  549. ID.AddInteger(NTTP->getNumExpansionTypes());
  550. for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
  551. QualType T = NTTP->getExpansionType(I);
  552. ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
  553. }
  554. } else
  555. ID.AddBoolean(false);
  556. continue;
  557. }
  558. auto *TTP = cast<TemplateTemplateParmDecl>(*P);
  559. ID.AddInteger(2);
  560. Profile(ID, TTP);
  561. }
  562. }
  563. TemplateTemplateParmDecl *
  564. ASTContext::getCanonicalTemplateTemplateParmDecl(
  565. TemplateTemplateParmDecl *TTP) const {
  566. // Check if we already have a canonical template template parameter.
  567. llvm::FoldingSetNodeID ID;
  568. CanonicalTemplateTemplateParm::Profile(ID, TTP);
  569. void *InsertPos = nullptr;
  570. CanonicalTemplateTemplateParm *Canonical
  571. = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
  572. if (Canonical)
  573. return Canonical->getParam();
  574. // Build a canonical template parameter list.
  575. TemplateParameterList *Params = TTP->getTemplateParameters();
  576. SmallVector<NamedDecl *, 4> CanonParams;
  577. CanonParams.reserve(Params->size());
  578. for (TemplateParameterList::const_iterator P = Params->begin(),
  579. PEnd = Params->end();
  580. P != PEnd; ++P) {
  581. if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
  582. CanonParams.push_back(
  583. TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
  584. SourceLocation(),
  585. SourceLocation(),
  586. TTP->getDepth(),
  587. TTP->getIndex(), nullptr, false,
  588. TTP->isParameterPack()));
  589. else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
  590. QualType T = getCanonicalType(NTTP->getType());
  591. TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
  592. NonTypeTemplateParmDecl *Param;
  593. if (NTTP->isExpandedParameterPack()) {
  594. SmallVector<QualType, 2> ExpandedTypes;
  595. SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
  596. for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
  597. ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
  598. ExpandedTInfos.push_back(
  599. getTrivialTypeSourceInfo(ExpandedTypes.back()));
  600. }
  601. Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
  602. SourceLocation(),
  603. SourceLocation(),
  604. NTTP->getDepth(),
  605. NTTP->getPosition(), nullptr,
  606. T,
  607. TInfo,
  608. ExpandedTypes,
  609. ExpandedTInfos);
  610. } else {
  611. Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
  612. SourceLocation(),
  613. SourceLocation(),
  614. NTTP->getDepth(),
  615. NTTP->getPosition(), nullptr,
  616. T,
  617. NTTP->isParameterPack(),
  618. TInfo);
  619. }
  620. CanonParams.push_back(Param);
  621. } else
  622. CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
  623. cast<TemplateTemplateParmDecl>(*P)));
  624. }
  625. assert(!TTP->getRequiresClause() &&
  626. "Unexpected requires-clause on template template-parameter");
  627. Expr *const CanonRequiresClause = nullptr;
  628. TemplateTemplateParmDecl *CanonTTP
  629. = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
  630. SourceLocation(), TTP->getDepth(),
  631. TTP->getPosition(),
  632. TTP->isParameterPack(),
  633. nullptr,
  634. TemplateParameterList::Create(*this, SourceLocation(),
  635. SourceLocation(),
  636. CanonParams,
  637. SourceLocation(),
  638. CanonRequiresClause));
  639. // Get the new insert position for the node we care about.
  640. Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
  641. assert(!Canonical && "Shouldn't be in the map!");
  642. (void)Canonical;
  643. // Create the canonical template template parameter entry.
  644. Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
  645. CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
  646. return CanonTTP;
  647. }
  648. CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
  649. if (!LangOpts.CPlusPlus) return nullptr;
  650. switch (T.getCXXABI().getKind()) {
  651. case TargetCXXABI::GenericARM: // Same as Itanium at this level
  652. case TargetCXXABI::iOS:
  653. case TargetCXXABI::iOS64:
  654. case TargetCXXABI::WatchOS:
  655. case TargetCXXABI::GenericAArch64:
  656. case TargetCXXABI::GenericMIPS:
  657. case TargetCXXABI::GenericItanium:
  658. case TargetCXXABI::WebAssembly:
  659. return CreateItaniumCXXABI(*this);
  660. case TargetCXXABI::Microsoft:
  661. return CreateMicrosoftCXXABI(*this);
  662. }
  663. llvm_unreachable("Invalid CXXABI type!");
  664. }
  665. static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
  666. const LangOptions &LOpts) {
  667. if (LOpts.FakeAddressSpaceMap) {
  668. // The fake address space map must have a distinct entry for each
  669. // language-specific address space.
  670. static const unsigned FakeAddrSpaceMap[] = {
  671. 0, // Default
  672. 1, // opencl_global
  673. 3, // opencl_local
  674. 2, // opencl_constant
  675. 0, // opencl_private
  676. 4, // opencl_generic
  677. 5, // cuda_device
  678. 6, // cuda_constant
  679. 7 // cuda_shared
  680. };
  681. return &FakeAddrSpaceMap;
  682. } else {
  683. return &T.getAddressSpaceMap();
  684. }
  685. }
  686. static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
  687. const LangOptions &LangOpts) {
  688. switch (LangOpts.getAddressSpaceMapMangling()) {
  689. case LangOptions::ASMM_Target:
  690. return TI.useAddressSpaceMapMangling();
  691. case LangOptions::ASMM_On:
  692. return true;
  693. case LangOptions::ASMM_Off:
  694. return false;
  695. }
  696. llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
  697. }
  698. ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
  699. IdentifierTable &idents, SelectorTable &sels,
  700. Builtin::Context &builtins)
  701. : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
  702. DependentTemplateSpecializationTypes(this_()),
  703. SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
  704. SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
  705. XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
  706. LangOpts.XRayNeverInstrumentFiles,
  707. LangOpts.XRayAttrListFiles, SM)),
  708. PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
  709. BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
  710. CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
  711. CompCategories(this_()), LastSDM(nullptr, 0) {
  712. TUDecl = TranslationUnitDecl::Create(*this);
  713. TraversalScope = {TUDecl};
  714. }
  715. ASTContext::~ASTContext() {
  716. // Release the DenseMaps associated with DeclContext objects.
  717. // FIXME: Is this the ideal solution?
  718. ReleaseDeclContextMaps();
  719. // Call all of the deallocation functions on all of their targets.
  720. for (auto &Pair : Deallocations)
  721. (Pair.first)(Pair.second);
  722. // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
  723. // because they can contain DenseMaps.
  724. for (llvm::DenseMap<const ObjCContainerDecl*,
  725. const ASTRecordLayout*>::iterator
  726. I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
  727. // Increment in loop to prevent using deallocated memory.
  728. if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
  729. R->Destroy(*this);
  730. for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
  731. I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
  732. // Increment in loop to prevent using deallocated memory.
  733. if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
  734. R->Destroy(*this);
  735. }
  736. for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
  737. AEnd = DeclAttrs.end();
  738. A != AEnd; ++A)
  739. A->second->~AttrVec();
  740. for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
  741. MaterializedTemporaryValues)
  742. MTVPair.second->~APValue();
  743. for (const auto &Value : ModuleInitializers)
  744. Value.second->~PerModuleInitializers();
  745. }
  746. class ASTContext::ParentMap {
  747. /// Contains parents of a node.
  748. using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>;
  749. /// Maps from a node to its parents. This is used for nodes that have
  750. /// pointer identity only, which are more common and we can save space by
  751. /// only storing a unique pointer to them.
  752. using ParentMapPointers = llvm::DenseMap<
  753. const void *,
  754. llvm::PointerUnion4<const Decl *, const Stmt *,
  755. ast_type_traits::DynTypedNode *, ParentVector *>>;
  756. /// Parent map for nodes without pointer identity. We store a full
  757. /// DynTypedNode for all keys.
  758. using ParentMapOtherNodes = llvm::DenseMap<
  759. ast_type_traits::DynTypedNode,
  760. llvm::PointerUnion4<const Decl *, const Stmt *,
  761. ast_type_traits::DynTypedNode *, ParentVector *>>;
  762. ParentMapPointers PointerParents;
  763. ParentMapOtherNodes OtherParents;
  764. class ASTVisitor;
  765. static ast_type_traits::DynTypedNode
  766. getSingleDynTypedNodeFromParentMap(ParentMapPointers::mapped_type U) {
  767. if (const auto *D = U.dyn_cast<const Decl *>())
  768. return ast_type_traits::DynTypedNode::create(*D);
  769. if (const auto *S = U.dyn_cast<const Stmt *>())
  770. return ast_type_traits::DynTypedNode::create(*S);
  771. return *U.get<ast_type_traits::DynTypedNode *>();
  772. }
  773. template <typename NodeTy, typename MapTy>
  774. static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
  775. const MapTy &Map) {
  776. auto I = Map.find(Node);
  777. if (I == Map.end()) {
  778. return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
  779. }
  780. if (const auto *V = I->second.template dyn_cast<ParentVector *>()) {
  781. return llvm::makeArrayRef(*V);
  782. }
  783. return getSingleDynTypedNodeFromParentMap(I->second);
  784. }
  785. public:
  786. ParentMap(ASTContext &Ctx);
  787. ~ParentMap() {
  788. for (const auto &Entry : PointerParents) {
  789. if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
  790. delete Entry.second.get<ast_type_traits::DynTypedNode *>();
  791. } else if (Entry.second.is<ParentVector *>()) {
  792. delete Entry.second.get<ParentVector *>();
  793. }
  794. }
  795. for (const auto &Entry : OtherParents) {
  796. if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
  797. delete Entry.second.get<ast_type_traits::DynTypedNode *>();
  798. } else if (Entry.second.is<ParentVector *>()) {
  799. delete Entry.second.get<ParentVector *>();
  800. }
  801. }
  802. }
  803. DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node) {
  804. if (Node.getNodeKind().hasPointerIdentity())
  805. return getDynNodeFromMap(Node.getMemoizationData(), PointerParents);
  806. return getDynNodeFromMap(Node, OtherParents);
  807. }
  808. };
  809. void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
  810. TraversalScope = TopLevelDecls;
  811. Parents.reset();
  812. }
  813. void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
  814. Deallocations.push_back({Callback, Data});
  815. }
  816. void
  817. ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
  818. ExternalSource = std::move(Source);
  819. }
  820. void ASTContext::PrintStats() const {
  821. llvm::errs() << "\n*** AST Context Stats:\n";
  822. llvm::errs() << " " << Types.size() << " types total.\n";
  823. unsigned counts[] = {
  824. #define TYPE(Name, Parent) 0,
  825. #define ABSTRACT_TYPE(Name, Parent)
  826. #include "clang/AST/TypeNodes.def"
  827. 0 // Extra
  828. };
  829. for (unsigned i = 0, e = Types.size(); i != e; ++i) {
  830. Type *T = Types[i];
  831. counts[(unsigned)T->getTypeClass()]++;
  832. }
  833. unsigned Idx = 0;
  834. unsigned TotalBytes = 0;
  835. #define TYPE(Name, Parent) \
  836. if (counts[Idx]) \
  837. llvm::errs() << " " << counts[Idx] << " " << #Name \
  838. << " types, " << sizeof(Name##Type) << " each " \
  839. << "(" << counts[Idx] * sizeof(Name##Type) \
  840. << " bytes)\n"; \
  841. TotalBytes += counts[Idx] * sizeof(Name##Type); \
  842. ++Idx;
  843. #define ABSTRACT_TYPE(Name, Parent)
  844. #include "clang/AST/TypeNodes.def"
  845. llvm::errs() << "Total bytes = " << TotalBytes << "\n";
  846. // Implicit special member functions.
  847. llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
  848. << NumImplicitDefaultConstructors
  849. << " implicit default constructors created\n";
  850. llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
  851. << NumImplicitCopyConstructors
  852. << " implicit copy constructors created\n";
  853. if (getLangOpts().CPlusPlus)
  854. llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
  855. << NumImplicitMoveConstructors
  856. << " implicit move constructors created\n";
  857. llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
  858. << NumImplicitCopyAssignmentOperators
  859. << " implicit copy assignment operators created\n";
  860. if (getLangOpts().CPlusPlus)
  861. llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
  862. << NumImplicitMoveAssignmentOperators
  863. << " implicit move assignment operators created\n";
  864. llvm::errs() << NumImplicitDestructorsDeclared << "/"
  865. << NumImplicitDestructors
  866. << " implicit destructors created\n";
  867. if (ExternalSource) {
  868. llvm::errs() << "\n";
  869. ExternalSource->PrintStats();
  870. }
  871. BumpAlloc.PrintStats();
  872. }
  873. void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
  874. bool NotifyListeners) {
  875. if (NotifyListeners)
  876. if (auto *Listener = getASTMutationListener())
  877. Listener->RedefinedHiddenDefinition(ND, M);
  878. MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
  879. }
  880. void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
  881. auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
  882. if (It == MergedDefModules.end())
  883. return;
  884. auto &Merged = It->second;
  885. llvm::DenseSet<Module*> Found;
  886. for (Module *&M : Merged)
  887. if (!Found.insert(M).second)
  888. M = nullptr;
  889. Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
  890. }
  891. void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
  892. if (LazyInitializers.empty())
  893. return;
  894. auto *Source = Ctx.getExternalSource();
  895. assert(Source && "lazy initializers but no external source");
  896. auto LazyInits = std::move(LazyInitializers);
  897. LazyInitializers.clear();
  898. for (auto ID : LazyInits)
  899. Initializers.push_back(Source->GetExternalDecl(ID));
  900. assert(LazyInitializers.empty() &&
  901. "GetExternalDecl for lazy module initializer added more inits");
  902. }
  903. void ASTContext::addModuleInitializer(Module *M, Decl *D) {
  904. // One special case: if we add a module initializer that imports another
  905. // module, and that module's only initializer is an ImportDecl, simplify.
  906. if (const auto *ID = dyn_cast<ImportDecl>(D)) {
  907. auto It = ModuleInitializers.find(ID->getImportedModule());
  908. // Maybe the ImportDecl does nothing at all. (Common case.)
  909. if (It == ModuleInitializers.end())
  910. return;
  911. // Maybe the ImportDecl only imports another ImportDecl.
  912. auto &Imported = *It->second;
  913. if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
  914. Imported.resolve(*this);
  915. auto *OnlyDecl = Imported.Initializers.front();
  916. if (isa<ImportDecl>(OnlyDecl))
  917. D = OnlyDecl;
  918. }
  919. }
  920. auto *&Inits = ModuleInitializers[M];
  921. if (!Inits)
  922. Inits = new (*this) PerModuleInitializers;
  923. Inits->Initializers.push_back(D);
  924. }
  925. void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
  926. auto *&Inits = ModuleInitializers[M];
  927. if (!Inits)
  928. Inits = new (*this) PerModuleInitializers;
  929. Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
  930. IDs.begin(), IDs.end());
  931. }
  932. ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
  933. auto It = ModuleInitializers.find(M);
  934. if (It == ModuleInitializers.end())
  935. return None;
  936. auto *Inits = It->second;
  937. Inits->resolve(*this);
  938. return Inits->Initializers;
  939. }
  940. ExternCContextDecl *ASTContext::getExternCContextDecl() const {
  941. if (!ExternCContext)
  942. ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
  943. return ExternCContext;
  944. }
  945. BuiltinTemplateDecl *
  946. ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
  947. const IdentifierInfo *II) const {
  948. auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
  949. BuiltinTemplate->setImplicit();
  950. TUDecl->addDecl(BuiltinTemplate);
  951. return BuiltinTemplate;
  952. }
  953. BuiltinTemplateDecl *
  954. ASTContext::getMakeIntegerSeqDecl() const {
  955. if (!MakeIntegerSeqDecl)
  956. MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
  957. getMakeIntegerSeqName());
  958. return MakeIntegerSeqDecl;
  959. }
  960. BuiltinTemplateDecl *
  961. ASTContext::getTypePackElementDecl() const {
  962. if (!TypePackElementDecl)
  963. TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
  964. getTypePackElementName());
  965. return TypePackElementDecl;
  966. }
  967. RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
  968. RecordDecl::TagKind TK) const {
  969. SourceLocation Loc;
  970. RecordDecl *NewDecl;
  971. if (getLangOpts().CPlusPlus)
  972. NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
  973. Loc, &Idents.get(Name));
  974. else
  975. NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
  976. &Idents.get(Name));
  977. NewDecl->setImplicit();
  978. NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
  979. const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
  980. return NewDecl;
  981. }
  982. TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
  983. StringRef Name) const {
  984. TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
  985. TypedefDecl *NewDecl = TypedefDecl::Create(
  986. const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
  987. SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
  988. NewDecl->setImplicit();
  989. return NewDecl;
  990. }
  991. TypedefDecl *ASTContext::getInt128Decl() const {
  992. if (!Int128Decl)
  993. Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
  994. return Int128Decl;
  995. }
  996. TypedefDecl *ASTContext::getUInt128Decl() const {
  997. if (!UInt128Decl)
  998. UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
  999. return UInt128Decl;
  1000. }
  1001. void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
  1002. auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
  1003. R = CanQualType::CreateUnsafe(QualType(Ty, 0));
  1004. Types.push_back(Ty);
  1005. }
  1006. void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
  1007. const TargetInfo *AuxTarget) {
  1008. assert((!this->Target || this->Target == &Target) &&
  1009. "Incorrect target reinitialization");
  1010. assert(VoidTy.isNull() && "Context reinitialized?");
  1011. this->Target = &Target;
  1012. this->AuxTarget = AuxTarget;
  1013. ABI.reset(createCXXABI(Target));
  1014. AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
  1015. AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
  1016. // C99 6.2.5p19.
  1017. InitBuiltinType(VoidTy, BuiltinType::Void);
  1018. // C99 6.2.5p2.
  1019. InitBuiltinType(BoolTy, BuiltinType::Bool);
  1020. // C99 6.2.5p3.
  1021. if (LangOpts.CharIsSigned)
  1022. InitBuiltinType(CharTy, BuiltinType::Char_S);
  1023. else
  1024. InitBuiltinType(CharTy, BuiltinType::Char_U);
  1025. // C99 6.2.5p4.
  1026. InitBuiltinType(SignedCharTy, BuiltinType::SChar);
  1027. InitBuiltinType(ShortTy, BuiltinType::Short);
  1028. InitBuiltinType(IntTy, BuiltinType::Int);
  1029. InitBuiltinType(LongTy, BuiltinType::Long);
  1030. InitBuiltinType(LongLongTy, BuiltinType::LongLong);
  1031. // C99 6.2.5p6.
  1032. InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
  1033. InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
  1034. InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
  1035. InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
  1036. InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
  1037. // C99 6.2.5p10.
  1038. InitBuiltinType(FloatTy, BuiltinType::Float);
  1039. InitBuiltinType(DoubleTy, BuiltinType::Double);
  1040. InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
  1041. // GNU extension, __float128 for IEEE quadruple precision
  1042. InitBuiltinType(Float128Ty, BuiltinType::Float128);
  1043. // C11 extension ISO/IEC TS 18661-3
  1044. InitBuiltinType(Float16Ty, BuiltinType::Float16);
  1045. // ISO/IEC JTC1 SC22 WG14 N1169 Extension
  1046. InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
  1047. InitBuiltinType(AccumTy, BuiltinType::Accum);
  1048. InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
  1049. InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
  1050. InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
  1051. InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
  1052. InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
  1053. InitBuiltinType(FractTy, BuiltinType::Fract);
  1054. InitBuiltinType(LongFractTy, BuiltinType::LongFract);
  1055. InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
  1056. InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
  1057. InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
  1058. InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
  1059. InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
  1060. InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
  1061. InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
  1062. InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
  1063. InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
  1064. InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
  1065. InitBuiltinType(SatFractTy, BuiltinType::SatFract);
  1066. InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
  1067. InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
  1068. InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
  1069. InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
  1070. // GNU extension, 128-bit integers.
  1071. InitBuiltinType(Int128Ty, BuiltinType::Int128);
  1072. InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
  1073. // C++ 3.9.1p5
  1074. if (TargetInfo::isTypeSigned(Target.getWCharType()))
  1075. InitBuiltinType(WCharTy, BuiltinType::WChar_S);
  1076. else // -fshort-wchar makes wchar_t be unsigned.
  1077. InitBuiltinType(WCharTy, BuiltinType::WChar_U);
  1078. if (LangOpts.CPlusPlus && LangOpts.WChar)
  1079. WideCharTy = WCharTy;
  1080. else {
  1081. // C99 (or C++ using -fno-wchar).
  1082. WideCharTy = getFromTargetType(Target.getWCharType());
  1083. }
  1084. WIntTy = getFromTargetType(Target.getWIntType());
  1085. // C++20 (proposed)
  1086. InitBuiltinType(Char8Ty, BuiltinType::Char8);
  1087. if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
  1088. InitBuiltinType(Char16Ty, BuiltinType::Char16);
  1089. else // C99
  1090. Char16Ty = getFromTargetType(Target.getChar16Type());
  1091. if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
  1092. InitBuiltinType(Char32Ty, BuiltinType::Char32);
  1093. else // C99
  1094. Char32Ty = getFromTargetType(Target.getChar32Type());
  1095. // Placeholder type for type-dependent expressions whose type is
  1096. // completely unknown. No code should ever check a type against
  1097. // DependentTy and users should never see it; however, it is here to
  1098. // help diagnose failures to properly check for type-dependent
  1099. // expressions.
  1100. InitBuiltinType(DependentTy, BuiltinType::Dependent);
  1101. // Placeholder type for functions.
  1102. InitBuiltinType(OverloadTy, BuiltinType::Overload);
  1103. // Placeholder type for bound members.
  1104. InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
  1105. // Placeholder type for pseudo-objects.
  1106. InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
  1107. // "any" type; useful for debugger-like clients.
  1108. InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
  1109. // Placeholder type for unbridged ARC casts.
  1110. InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
  1111. // Placeholder type for builtin functions.
  1112. InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
  1113. // Placeholder type for OMP array sections.
  1114. if (LangOpts.OpenMP)
  1115. InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
  1116. // C99 6.2.5p11.
  1117. FloatComplexTy = getComplexType(FloatTy);
  1118. DoubleComplexTy = getComplexType(DoubleTy);
  1119. LongDoubleComplexTy = getComplexType(LongDoubleTy);
  1120. Float128ComplexTy = getComplexType(Float128Ty);
  1121. // Builtin types for 'id', 'Class', and 'SEL'.
  1122. InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
  1123. InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
  1124. InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
  1125. if (LangOpts.OpenCL) {
  1126. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  1127. InitBuiltinType(SingletonId, BuiltinType::Id);
  1128. #include "clang/Basic/OpenCLImageTypes.def"
  1129. InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
  1130. InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
  1131. InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
  1132. InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
  1133. InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
  1134. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  1135. InitBuiltinType(Id##Ty, BuiltinType::Id);
  1136. #include "clang/Basic/OpenCLExtensionTypes.def"
  1137. }
  1138. // Builtin type for __objc_yes and __objc_no
  1139. ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
  1140. SignedCharTy : BoolTy);
  1141. ObjCConstantStringType = QualType();
  1142. ObjCSuperType = QualType();
  1143. // void * type
  1144. if (LangOpts.OpenCLVersion >= 200) {
  1145. auto Q = VoidTy.getQualifiers();
  1146. Q.setAddressSpace(LangAS::opencl_generic);
  1147. VoidPtrTy = getPointerType(getCanonicalType(
  1148. getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
  1149. } else {
  1150. VoidPtrTy = getPointerType(VoidTy);
  1151. }
  1152. // nullptr type (C++0x 2.14.7)
  1153. InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
  1154. // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
  1155. InitBuiltinType(HalfTy, BuiltinType::Half);
  1156. // Builtin type used to help define __builtin_va_list.
  1157. VaListTagDecl = nullptr;
  1158. }
  1159. DiagnosticsEngine &ASTContext::getDiagnostics() const {
  1160. return SourceMgr.getDiagnostics();
  1161. }
  1162. AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
  1163. AttrVec *&Result = DeclAttrs[D];
  1164. if (!Result) {
  1165. void *Mem = Allocate(sizeof(AttrVec));
  1166. Result = new (Mem) AttrVec;
  1167. }
  1168. return *Result;
  1169. }
  1170. /// Erase the attributes corresponding to the given declaration.
  1171. void ASTContext::eraseDeclAttrs(const Decl *D) {
  1172. llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
  1173. if (Pos != DeclAttrs.end()) {
  1174. Pos->second->~AttrVec();
  1175. DeclAttrs.erase(Pos);
  1176. }
  1177. }
  1178. // FIXME: Remove ?
  1179. MemberSpecializationInfo *
  1180. ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
  1181. assert(Var->isStaticDataMember() && "Not a static data member");
  1182. return getTemplateOrSpecializationInfo(Var)
  1183. .dyn_cast<MemberSpecializationInfo *>();
  1184. }
  1185. ASTContext::TemplateOrSpecializationInfo
  1186. ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
  1187. llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
  1188. TemplateOrInstantiation.find(Var);
  1189. if (Pos == TemplateOrInstantiation.end())
  1190. return {};
  1191. return Pos->second;
  1192. }
  1193. void
  1194. ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
  1195. TemplateSpecializationKind TSK,
  1196. SourceLocation PointOfInstantiation) {
  1197. assert(Inst->isStaticDataMember() && "Not a static data member");
  1198. assert(Tmpl->isStaticDataMember() && "Not a static data member");
  1199. setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
  1200. Tmpl, TSK, PointOfInstantiation));
  1201. }
  1202. void
  1203. ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
  1204. TemplateOrSpecializationInfo TSI) {
  1205. assert(!TemplateOrInstantiation[Inst] &&
  1206. "Already noted what the variable was instantiated from");
  1207. TemplateOrInstantiation[Inst] = TSI;
  1208. }
  1209. NamedDecl *
  1210. ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
  1211. auto Pos = InstantiatedFromUsingDecl.find(UUD);
  1212. if (Pos == InstantiatedFromUsingDecl.end())
  1213. return nullptr;
  1214. return Pos->second;
  1215. }
  1216. void
  1217. ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
  1218. assert((isa<UsingDecl>(Pattern) ||
  1219. isa<UnresolvedUsingValueDecl>(Pattern) ||
  1220. isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
  1221. "pattern decl is not a using decl");
  1222. assert((isa<UsingDecl>(Inst) ||
  1223. isa<UnresolvedUsingValueDecl>(Inst) ||
  1224. isa<UnresolvedUsingTypenameDecl>(Inst)) &&
  1225. "instantiation did not produce a using decl");
  1226. assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
  1227. InstantiatedFromUsingDecl[Inst] = Pattern;
  1228. }
  1229. UsingShadowDecl *
  1230. ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
  1231. llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
  1232. = InstantiatedFromUsingShadowDecl.find(Inst);
  1233. if (Pos == InstantiatedFromUsingShadowDecl.end())
  1234. return nullptr;
  1235. return Pos->second;
  1236. }
  1237. void
  1238. ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
  1239. UsingShadowDecl *Pattern) {
  1240. assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
  1241. InstantiatedFromUsingShadowDecl[Inst] = Pattern;
  1242. }
  1243. FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
  1244. llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
  1245. = InstantiatedFromUnnamedFieldDecl.find(Field);
  1246. if (Pos == InstantiatedFromUnnamedFieldDecl.end())
  1247. return nullptr;
  1248. return Pos->second;
  1249. }
  1250. void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
  1251. FieldDecl *Tmpl) {
  1252. assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
  1253. assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
  1254. assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
  1255. "Already noted what unnamed field was instantiated from");
  1256. InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
  1257. }
  1258. ASTContext::overridden_cxx_method_iterator
  1259. ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
  1260. return overridden_methods(Method).begin();
  1261. }
  1262. ASTContext::overridden_cxx_method_iterator
  1263. ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
  1264. return overridden_methods(Method).end();
  1265. }
  1266. unsigned
  1267. ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
  1268. auto Range = overridden_methods(Method);
  1269. return Range.end() - Range.begin();
  1270. }
  1271. ASTContext::overridden_method_range
  1272. ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
  1273. llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
  1274. OverriddenMethods.find(Method->getCanonicalDecl());
  1275. if (Pos == OverriddenMethods.end())
  1276. return overridden_method_range(nullptr, nullptr);
  1277. return overridden_method_range(Pos->second.begin(), Pos->second.end());
  1278. }
  1279. void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
  1280. const CXXMethodDecl *Overridden) {
  1281. assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
  1282. OverriddenMethods[Method].push_back(Overridden);
  1283. }
  1284. void ASTContext::getOverriddenMethods(
  1285. const NamedDecl *D,
  1286. SmallVectorImpl<const NamedDecl *> &Overridden) const {
  1287. assert(D);
  1288. if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
  1289. Overridden.append(overridden_methods_begin(CXXMethod),
  1290. overridden_methods_end(CXXMethod));
  1291. return;
  1292. }
  1293. const auto *Method = dyn_cast<ObjCMethodDecl>(D);
  1294. if (!Method)
  1295. return;
  1296. SmallVector<const ObjCMethodDecl *, 8> OverDecls;
  1297. Method->getOverriddenMethods(OverDecls);
  1298. Overridden.append(OverDecls.begin(), OverDecls.end());
  1299. }
  1300. void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
  1301. assert(!Import->NextLocalImport && "Import declaration already in the chain");
  1302. assert(!Import->isFromASTFile() && "Non-local import declaration");
  1303. if (!FirstLocalImport) {
  1304. FirstLocalImport = Import;
  1305. LastLocalImport = Import;
  1306. return;
  1307. }
  1308. LastLocalImport->NextLocalImport = Import;
  1309. LastLocalImport = Import;
  1310. }
  1311. //===----------------------------------------------------------------------===//
  1312. // Type Sizing and Analysis
  1313. //===----------------------------------------------------------------------===//
  1314. /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
  1315. /// scalar floating point type.
  1316. const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
  1317. const auto *BT = T->getAs<BuiltinType>();
  1318. assert(BT && "Not a floating point type!");
  1319. switch (BT->getKind()) {
  1320. default: llvm_unreachable("Not a floating point type!");
  1321. case BuiltinType::Float16:
  1322. case BuiltinType::Half:
  1323. return Target->getHalfFormat();
  1324. case BuiltinType::Float: return Target->getFloatFormat();
  1325. case BuiltinType::Double: return Target->getDoubleFormat();
  1326. case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
  1327. case BuiltinType::Float128: return Target->getFloat128Format();
  1328. }
  1329. }
  1330. CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
  1331. unsigned Align = Target->getCharWidth();
  1332. bool UseAlignAttrOnly = false;
  1333. if (unsigned AlignFromAttr = D->getMaxAlignment()) {
  1334. Align = AlignFromAttr;
  1335. // __attribute__((aligned)) can increase or decrease alignment
  1336. // *except* on a struct or struct member, where it only increases
  1337. // alignment unless 'packed' is also specified.
  1338. //
  1339. // It is an error for alignas to decrease alignment, so we can
  1340. // ignore that possibility; Sema should diagnose it.
  1341. if (isa<FieldDecl>(D)) {
  1342. UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
  1343. cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
  1344. } else {
  1345. UseAlignAttrOnly = true;
  1346. }
  1347. }
  1348. else if (isa<FieldDecl>(D))
  1349. UseAlignAttrOnly =
  1350. D->hasAttr<PackedAttr>() ||
  1351. cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
  1352. // If we're using the align attribute only, just ignore everything
  1353. // else about the declaration and its type.
  1354. if (UseAlignAttrOnly) {
  1355. // do nothing
  1356. } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
  1357. QualType T = VD->getType();
  1358. if (const auto *RT = T->getAs<ReferenceType>()) {
  1359. if (ForAlignof)
  1360. T = RT->getPointeeType();
  1361. else
  1362. T = getPointerType(RT->getPointeeType());
  1363. }
  1364. QualType BaseT = getBaseElementType(T);
  1365. if (T->isFunctionType())
  1366. Align = getTypeInfoImpl(T.getTypePtr()).Align;
  1367. else if (!BaseT->isIncompleteType()) {
  1368. // Adjust alignments of declarations with array type by the
  1369. // large-array alignment on the target.
  1370. if (const ArrayType *arrayType = getAsArrayType(T)) {
  1371. unsigned MinWidth = Target->getLargeArrayMinWidth();
  1372. if (!ForAlignof && MinWidth) {
  1373. if (isa<VariableArrayType>(arrayType))
  1374. Align = std::max(Align, Target->getLargeArrayAlign());
  1375. else if (isa<ConstantArrayType>(arrayType) &&
  1376. MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
  1377. Align = std::max(Align, Target->getLargeArrayAlign());
  1378. }
  1379. }
  1380. Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
  1381. if (BaseT.getQualifiers().hasUnaligned())
  1382. Align = Target->getCharWidth();
  1383. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  1384. if (VD->hasGlobalStorage() && !ForAlignof) {
  1385. uint64_t TypeSize = getTypeSize(T.getTypePtr());
  1386. Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
  1387. }
  1388. }
  1389. }
  1390. // Fields can be subject to extra alignment constraints, like if
  1391. // the field is packed, the struct is packed, or the struct has a
  1392. // a max-field-alignment constraint (#pragma pack). So calculate
  1393. // the actual alignment of the field within the struct, and then
  1394. // (as we're expected to) constrain that by the alignment of the type.
  1395. if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
  1396. const RecordDecl *Parent = Field->getParent();
  1397. // We can only produce a sensible answer if the record is valid.
  1398. if (!Parent->isInvalidDecl()) {
  1399. const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
  1400. // Start with the record's overall alignment.
  1401. unsigned FieldAlign = toBits(Layout.getAlignment());
  1402. // Use the GCD of that and the offset within the record.
  1403. uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
  1404. if (Offset > 0) {
  1405. // Alignment is always a power of 2, so the GCD will be a power of 2,
  1406. // which means we get to do this crazy thing instead of Euclid's.
  1407. uint64_t LowBitOfOffset = Offset & (~Offset + 1);
  1408. if (LowBitOfOffset < FieldAlign)
  1409. FieldAlign = static_cast<unsigned>(LowBitOfOffset);
  1410. }
  1411. Align = std::min(Align, FieldAlign);
  1412. }
  1413. }
  1414. }
  1415. return toCharUnitsFromBits(Align);
  1416. }
  1417. // getTypeInfoDataSizeInChars - Return the size of a type, in
  1418. // chars. If the type is a record, its data size is returned. This is
  1419. // the size of the memcpy that's performed when assigning this type
  1420. // using a trivial copy/move assignment operator.
  1421. std::pair<CharUnits, CharUnits>
  1422. ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
  1423. std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
  1424. // In C++, objects can sometimes be allocated into the tail padding
  1425. // of a base-class subobject. We decide whether that's possible
  1426. // during class layout, so here we can just trust the layout results.
  1427. if (getLangOpts().CPlusPlus) {
  1428. if (const auto *RT = T->getAs<RecordType>()) {
  1429. const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
  1430. sizeAndAlign.first = layout.getDataSize();
  1431. }
  1432. }
  1433. return sizeAndAlign;
  1434. }
  1435. /// getConstantArrayInfoInChars - Performing the computation in CharUnits
  1436. /// instead of in bits prevents overflowing the uint64_t for some large arrays.
  1437. std::pair<CharUnits, CharUnits>
  1438. static getConstantArrayInfoInChars(const ASTContext &Context,
  1439. const ConstantArrayType *CAT) {
  1440. std::pair<CharUnits, CharUnits> EltInfo =
  1441. Context.getTypeInfoInChars(CAT->getElementType());
  1442. uint64_t Size = CAT->getSize().getZExtValue();
  1443. assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
  1444. (uint64_t)(-1)/Size) &&
  1445. "Overflow in array type char size evaluation");
  1446. uint64_t Width = EltInfo.first.getQuantity() * Size;
  1447. unsigned Align = EltInfo.second.getQuantity();
  1448. if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
  1449. Context.getTargetInfo().getPointerWidth(0) == 64)
  1450. Width = llvm::alignTo(Width, Align);
  1451. return std::make_pair(CharUnits::fromQuantity(Width),
  1452. CharUnits::fromQuantity(Align));
  1453. }
  1454. std::pair<CharUnits, CharUnits>
  1455. ASTContext::getTypeInfoInChars(const Type *T) const {
  1456. if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
  1457. return getConstantArrayInfoInChars(*this, CAT);
  1458. TypeInfo Info = getTypeInfo(T);
  1459. return std::make_pair(toCharUnitsFromBits(Info.Width),
  1460. toCharUnitsFromBits(Info.Align));
  1461. }
  1462. std::pair<CharUnits, CharUnits>
  1463. ASTContext::getTypeInfoInChars(QualType T) const {
  1464. return getTypeInfoInChars(T.getTypePtr());
  1465. }
  1466. bool ASTContext::isAlignmentRequired(const Type *T) const {
  1467. return getTypeInfo(T).AlignIsRequired;
  1468. }
  1469. bool ASTContext::isAlignmentRequired(QualType T) const {
  1470. return isAlignmentRequired(T.getTypePtr());
  1471. }
  1472. unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
  1473. // An alignment on a typedef overrides anything else.
  1474. if (const auto *TT = T->getAs<TypedefType>())
  1475. if (unsigned Align = TT->getDecl()->getMaxAlignment())
  1476. return Align;
  1477. // If we have an (array of) complete type, we're done.
  1478. T = getBaseElementType(T);
  1479. if (!T->isIncompleteType())
  1480. return getTypeAlign(T);
  1481. // If we had an array type, its element type might be a typedef
  1482. // type with an alignment attribute.
  1483. if (const auto *TT = T->getAs<TypedefType>())
  1484. if (unsigned Align = TT->getDecl()->getMaxAlignment())
  1485. return Align;
  1486. // Otherwise, see if the declaration of the type had an attribute.
  1487. if (const auto *TT = T->getAs<TagType>())
  1488. return TT->getDecl()->getMaxAlignment();
  1489. return 0;
  1490. }
  1491. TypeInfo ASTContext::getTypeInfo(const Type *T) const {
  1492. TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
  1493. if (I != MemoizedTypeInfo.end())
  1494. return I->second;
  1495. // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
  1496. TypeInfo TI = getTypeInfoImpl(T);
  1497. MemoizedTypeInfo[T] = TI;
  1498. return TI;
  1499. }
  1500. /// getTypeInfoImpl - Return the size of the specified type, in bits. This
  1501. /// method does not work on incomplete types.
  1502. ///
  1503. /// FIXME: Pointers into different addr spaces could have different sizes and
  1504. /// alignment requirements: getPointerInfo should take an AddrSpace, this
  1505. /// should take a QualType, &c.
  1506. TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
  1507. uint64_t Width = 0;
  1508. unsigned Align = 8;
  1509. bool AlignIsRequired = false;
  1510. unsigned AS = 0;
  1511. switch (T->getTypeClass()) {
  1512. #define TYPE(Class, Base)
  1513. #define ABSTRACT_TYPE(Class, Base)
  1514. #define NON_CANONICAL_TYPE(Class, Base)
  1515. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1516. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
  1517. case Type::Class: \
  1518. assert(!T->isDependentType() && "should not see dependent types here"); \
  1519. return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
  1520. #include "clang/AST/TypeNodes.def"
  1521. llvm_unreachable("Should not see dependent types");
  1522. case Type::FunctionNoProto:
  1523. case Type::FunctionProto:
  1524. // GCC extension: alignof(function) = 32 bits
  1525. Width = 0;
  1526. Align = 32;
  1527. break;
  1528. case Type::IncompleteArray:
  1529. case Type::VariableArray:
  1530. Width = 0;
  1531. Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
  1532. break;
  1533. case Type::ConstantArray: {
  1534. const auto *CAT = cast<ConstantArrayType>(T);
  1535. TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
  1536. uint64_t Size = CAT->getSize().getZExtValue();
  1537. assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
  1538. "Overflow in array type bit size evaluation");
  1539. Width = EltInfo.Width * Size;
  1540. Align = EltInfo.Align;
  1541. if (!getTargetInfo().getCXXABI().isMicrosoft() ||
  1542. getTargetInfo().getPointerWidth(0) == 64)
  1543. Width = llvm::alignTo(Width, Align);
  1544. break;
  1545. }
  1546. case Type::ExtVector:
  1547. case Type::Vector: {
  1548. const auto *VT = cast<VectorType>(T);
  1549. TypeInfo EltInfo = getTypeInfo(VT->getElementType());
  1550. Width = EltInfo.Width * VT->getNumElements();
  1551. Align = Width;
  1552. // If the alignment is not a power of 2, round up to the next power of 2.
  1553. // This happens for non-power-of-2 length vectors.
  1554. if (Align & (Align-1)) {
  1555. Align = llvm::NextPowerOf2(Align);
  1556. Width = llvm::alignTo(Width, Align);
  1557. }
  1558. // Adjust the alignment based on the target max.
  1559. uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
  1560. if (TargetVectorAlign && TargetVectorAlign < Align)
  1561. Align = TargetVectorAlign;
  1562. break;
  1563. }
  1564. case Type::Builtin:
  1565. switch (cast<BuiltinType>(T)->getKind()) {
  1566. default: llvm_unreachable("Unknown builtin type!");
  1567. case BuiltinType::Void:
  1568. // GCC extension: alignof(void) = 8 bits.
  1569. Width = 0;
  1570. Align = 8;
  1571. break;
  1572. case BuiltinType::Bool:
  1573. Width = Target->getBoolWidth();
  1574. Align = Target->getBoolAlign();
  1575. break;
  1576. case BuiltinType::Char_S:
  1577. case BuiltinType::Char_U:
  1578. case BuiltinType::UChar:
  1579. case BuiltinType::SChar:
  1580. case BuiltinType::Char8:
  1581. Width = Target->getCharWidth();
  1582. Align = Target->getCharAlign();
  1583. break;
  1584. case BuiltinType::WChar_S:
  1585. case BuiltinType::WChar_U:
  1586. Width = Target->getWCharWidth();
  1587. Align = Target->getWCharAlign();
  1588. break;
  1589. case BuiltinType::Char16:
  1590. Width = Target->getChar16Width();
  1591. Align = Target->getChar16Align();
  1592. break;
  1593. case BuiltinType::Char32:
  1594. Width = Target->getChar32Width();
  1595. Align = Target->getChar32Align();
  1596. break;
  1597. case BuiltinType::UShort:
  1598. case BuiltinType::Short:
  1599. Width = Target->getShortWidth();
  1600. Align = Target->getShortAlign();
  1601. break;
  1602. case BuiltinType::UInt:
  1603. case BuiltinType::Int:
  1604. Width = Target->getIntWidth();
  1605. Align = Target->getIntAlign();
  1606. break;
  1607. case BuiltinType::ULong:
  1608. case BuiltinType::Long:
  1609. Width = Target->getLongWidth();
  1610. Align = Target->getLongAlign();
  1611. break;
  1612. case BuiltinType::ULongLong:
  1613. case BuiltinType::LongLong:
  1614. Width = Target->getLongLongWidth();
  1615. Align = Target->getLongLongAlign();
  1616. break;
  1617. case BuiltinType::Int128:
  1618. case BuiltinType::UInt128:
  1619. Width = 128;
  1620. Align = 128; // int128_t is 128-bit aligned on all targets.
  1621. break;
  1622. case BuiltinType::ShortAccum:
  1623. case BuiltinType::UShortAccum:
  1624. case BuiltinType::SatShortAccum:
  1625. case BuiltinType::SatUShortAccum:
  1626. Width = Target->getShortAccumWidth();
  1627. Align = Target->getShortAccumAlign();
  1628. break;
  1629. case BuiltinType::Accum:
  1630. case BuiltinType::UAccum:
  1631. case BuiltinType::SatAccum:
  1632. case BuiltinType::SatUAccum:
  1633. Width = Target->getAccumWidth();
  1634. Align = Target->getAccumAlign();
  1635. break;
  1636. case BuiltinType::LongAccum:
  1637. case BuiltinType::ULongAccum:
  1638. case BuiltinType::SatLongAccum:
  1639. case BuiltinType::SatULongAccum:
  1640. Width = Target->getLongAccumWidth();
  1641. Align = Target->getLongAccumAlign();
  1642. break;
  1643. case BuiltinType::ShortFract:
  1644. case BuiltinType::UShortFract:
  1645. case BuiltinType::SatShortFract:
  1646. case BuiltinType::SatUShortFract:
  1647. Width = Target->getShortFractWidth();
  1648. Align = Target->getShortFractAlign();
  1649. break;
  1650. case BuiltinType::Fract:
  1651. case BuiltinType::UFract:
  1652. case BuiltinType::SatFract:
  1653. case BuiltinType::SatUFract:
  1654. Width = Target->getFractWidth();
  1655. Align = Target->getFractAlign();
  1656. break;
  1657. case BuiltinType::LongFract:
  1658. case BuiltinType::ULongFract:
  1659. case BuiltinType::SatLongFract:
  1660. case BuiltinType::SatULongFract:
  1661. Width = Target->getLongFractWidth();
  1662. Align = Target->getLongFractAlign();
  1663. break;
  1664. case BuiltinType::Float16:
  1665. case BuiltinType::Half:
  1666. if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
  1667. !getLangOpts().OpenMPIsDevice) {
  1668. Width = Target->getHalfWidth();
  1669. Align = Target->getHalfAlign();
  1670. } else {
  1671. assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  1672. "Expected OpenMP device compilation.");
  1673. Width = AuxTarget->getHalfWidth();
  1674. Align = AuxTarget->getHalfAlign();
  1675. }
  1676. break;
  1677. case BuiltinType::Float:
  1678. Width = Target->getFloatWidth();
  1679. Align = Target->getFloatAlign();
  1680. break;
  1681. case BuiltinType::Double:
  1682. Width = Target->getDoubleWidth();
  1683. Align = Target->getDoubleAlign();
  1684. break;
  1685. case BuiltinType::LongDouble:
  1686. Width = Target->getLongDoubleWidth();
  1687. Align = Target->getLongDoubleAlign();
  1688. break;
  1689. case BuiltinType::Float128:
  1690. if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
  1691. !getLangOpts().OpenMPIsDevice) {
  1692. Width = Target->getFloat128Width();
  1693. Align = Target->getFloat128Align();
  1694. } else {
  1695. assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  1696. "Expected OpenMP device compilation.");
  1697. Width = AuxTarget->getFloat128Width();
  1698. Align = AuxTarget->getFloat128Align();
  1699. }
  1700. break;
  1701. case BuiltinType::NullPtr:
  1702. Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
  1703. Align = Target->getPointerAlign(0); // == sizeof(void*)
  1704. break;
  1705. case BuiltinType::ObjCId:
  1706. case BuiltinType::ObjCClass:
  1707. case BuiltinType::ObjCSel:
  1708. Width = Target->getPointerWidth(0);
  1709. Align = Target->getPointerAlign(0);
  1710. break;
  1711. case BuiltinType::OCLSampler:
  1712. case BuiltinType::OCLEvent:
  1713. case BuiltinType::OCLClkEvent:
  1714. case BuiltinType::OCLQueue:
  1715. case BuiltinType::OCLReserveID:
  1716. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  1717. case BuiltinType::Id:
  1718. #include "clang/Basic/OpenCLImageTypes.def"
  1719. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  1720. case BuiltinType::Id:
  1721. #include "clang/Basic/OpenCLExtensionTypes.def"
  1722. AS = getTargetAddressSpace(
  1723. Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
  1724. Width = Target->getPointerWidth(AS);
  1725. Align = Target->getPointerAlign(AS);
  1726. break;
  1727. }
  1728. break;
  1729. case Type::ObjCObjectPointer:
  1730. Width = Target->getPointerWidth(0);
  1731. Align = Target->getPointerAlign(0);
  1732. break;
  1733. case Type::BlockPointer:
  1734. AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
  1735. Width = Target->getPointerWidth(AS);
  1736. Align = Target->getPointerAlign(AS);
  1737. break;
  1738. case Type::LValueReference:
  1739. case Type::RValueReference:
  1740. // alignof and sizeof should never enter this code path here, so we go
  1741. // the pointer route.
  1742. AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
  1743. Width = Target->getPointerWidth(AS);
  1744. Align = Target->getPointerAlign(AS);
  1745. break;
  1746. case Type::Pointer:
  1747. AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
  1748. Width = Target->getPointerWidth(AS);
  1749. Align = Target->getPointerAlign(AS);
  1750. break;
  1751. case Type::MemberPointer: {
  1752. const auto *MPT = cast<MemberPointerType>(T);
  1753. CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
  1754. Width = MPI.Width;
  1755. Align = MPI.Align;
  1756. break;
  1757. }
  1758. case Type::Complex: {
  1759. // Complex types have the same alignment as their elements, but twice the
  1760. // size.
  1761. TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
  1762. Width = EltInfo.Width * 2;
  1763. Align = EltInfo.Align;
  1764. break;
  1765. }
  1766. case Type::ObjCObject:
  1767. return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
  1768. case Type::Adjusted:
  1769. case Type::Decayed:
  1770. return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
  1771. case Type::ObjCInterface: {
  1772. const auto *ObjCI = cast<ObjCInterfaceType>(T);
  1773. const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
  1774. Width = toBits(Layout.getSize());
  1775. Align = toBits(Layout.getAlignment());
  1776. break;
  1777. }
  1778. case Type::Record:
  1779. case Type::Enum: {
  1780. const auto *TT = cast<TagType>(T);
  1781. if (TT->getDecl()->isInvalidDecl()) {
  1782. Width = 8;
  1783. Align = 8;
  1784. break;
  1785. }
  1786. if (const auto *ET = dyn_cast<EnumType>(TT)) {
  1787. const EnumDecl *ED = ET->getDecl();
  1788. TypeInfo Info =
  1789. getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
  1790. if (unsigned AttrAlign = ED->getMaxAlignment()) {
  1791. Info.Align = AttrAlign;
  1792. Info.AlignIsRequired = true;
  1793. }
  1794. return Info;
  1795. }
  1796. const auto *RT = cast<RecordType>(TT);
  1797. const RecordDecl *RD = RT->getDecl();
  1798. const ASTRecordLayout &Layout = getASTRecordLayout(RD);
  1799. Width = toBits(Layout.getSize());
  1800. Align = toBits(Layout.getAlignment());
  1801. AlignIsRequired = RD->hasAttr<AlignedAttr>();
  1802. break;
  1803. }
  1804. case Type::SubstTemplateTypeParm:
  1805. return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
  1806. getReplacementType().getTypePtr());
  1807. case Type::Auto:
  1808. case Type::DeducedTemplateSpecialization: {
  1809. const auto *A = cast<DeducedType>(T);
  1810. assert(!A->getDeducedType().isNull() &&
  1811. "cannot request the size of an undeduced or dependent auto type");
  1812. return getTypeInfo(A->getDeducedType().getTypePtr());
  1813. }
  1814. case Type::Paren:
  1815. return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
  1816. case Type::ObjCTypeParam:
  1817. return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
  1818. case Type::Typedef: {
  1819. const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
  1820. TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
  1821. // If the typedef has an aligned attribute on it, it overrides any computed
  1822. // alignment we have. This violates the GCC documentation (which says that
  1823. // attribute(aligned) can only round up) but matches its implementation.
  1824. if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
  1825. Align = AttrAlign;
  1826. AlignIsRequired = true;
  1827. } else {
  1828. Align = Info.Align;
  1829. AlignIsRequired = Info.AlignIsRequired;
  1830. }
  1831. Width = Info.Width;
  1832. break;
  1833. }
  1834. case Type::Elaborated:
  1835. return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
  1836. case Type::Attributed:
  1837. return getTypeInfo(
  1838. cast<AttributedType>(T)->getEquivalentType().getTypePtr());
  1839. case Type::Atomic: {
  1840. // Start with the base type information.
  1841. TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
  1842. Width = Info.Width;
  1843. Align = Info.Align;
  1844. if (!Width) {
  1845. // An otherwise zero-sized type should still generate an
  1846. // atomic operation.
  1847. Width = Target->getCharWidth();
  1848. assert(Align);
  1849. } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
  1850. // If the size of the type doesn't exceed the platform's max
  1851. // atomic promotion width, make the size and alignment more
  1852. // favorable to atomic operations:
  1853. // Round the size up to a power of 2.
  1854. if (!llvm::isPowerOf2_64(Width))
  1855. Width = llvm::NextPowerOf2(Width);
  1856. // Set the alignment equal to the size.
  1857. Align = static_cast<unsigned>(Width);
  1858. }
  1859. }
  1860. break;
  1861. case Type::Pipe:
  1862. Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
  1863. Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
  1864. break;
  1865. }
  1866. assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
  1867. return TypeInfo(Width, Align, AlignIsRequired);
  1868. }
  1869. unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
  1870. UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
  1871. if (I != MemoizedUnadjustedAlign.end())
  1872. return I->second;
  1873. unsigned UnadjustedAlign;
  1874. if (const auto *RT = T->getAs<RecordType>()) {
  1875. const RecordDecl *RD = RT->getDecl();
  1876. const ASTRecordLayout &Layout = getASTRecordLayout(RD);
  1877. UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
  1878. } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
  1879. const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
  1880. UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
  1881. } else {
  1882. UnadjustedAlign = getTypeAlign(T);
  1883. }
  1884. MemoizedUnadjustedAlign[T] = UnadjustedAlign;
  1885. return UnadjustedAlign;
  1886. }
  1887. unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
  1888. unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
  1889. // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
  1890. if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
  1891. getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
  1892. getTargetInfo().getABI() == "elfv1-qpx" &&
  1893. T->isSpecificBuiltinType(BuiltinType::Double))
  1894. SimdAlign = 256;
  1895. return SimdAlign;
  1896. }
  1897. /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
  1898. CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
  1899. return CharUnits::fromQuantity(BitSize / getCharWidth());
  1900. }
  1901. /// toBits - Convert a size in characters to a size in characters.
  1902. int64_t ASTContext::toBits(CharUnits CharSize) const {
  1903. return CharSize.getQuantity() * getCharWidth();
  1904. }
  1905. /// getTypeSizeInChars - Return the size of the specified type, in characters.
  1906. /// This method does not work on incomplete types.
  1907. CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
  1908. return getTypeInfoInChars(T).first;
  1909. }
  1910. CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
  1911. return getTypeInfoInChars(T).first;
  1912. }
  1913. /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
  1914. /// characters. This method does not work on incomplete types.
  1915. CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
  1916. return toCharUnitsFromBits(getTypeAlign(T));
  1917. }
  1918. CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
  1919. return toCharUnitsFromBits(getTypeAlign(T));
  1920. }
  1921. /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
  1922. /// type, in characters, before alignment adustments. This method does
  1923. /// not work on incomplete types.
  1924. CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
  1925. return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
  1926. }
  1927. CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
  1928. return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
  1929. }
  1930. /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
  1931. /// type for the current target in bits. This can be different than the ABI
  1932. /// alignment in cases where it is beneficial for performance to overalign
  1933. /// a data type.
  1934. unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
  1935. TypeInfo TI = getTypeInfo(T);
  1936. unsigned ABIAlign = TI.Align;
  1937. T = T->getBaseElementTypeUnsafe();
  1938. // The preferred alignment of member pointers is that of a pointer.
  1939. if (T->isMemberPointerType())
  1940. return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
  1941. if (!Target->allowsLargerPreferedTypeAlignment())
  1942. return ABIAlign;
  1943. // Double and long long should be naturally aligned if possible.
  1944. if (const auto *CT = T->getAs<ComplexType>())
  1945. T = CT->getElementType().getTypePtr();
  1946. if (const auto *ET = T->getAs<EnumType>())
  1947. T = ET->getDecl()->getIntegerType().getTypePtr();
  1948. if (T->isSpecificBuiltinType(BuiltinType::Double) ||
  1949. T->isSpecificBuiltinType(BuiltinType::LongLong) ||
  1950. T->isSpecificBuiltinType(BuiltinType::ULongLong))
  1951. // Don't increase the alignment if an alignment attribute was specified on a
  1952. // typedef declaration.
  1953. if (!TI.AlignIsRequired)
  1954. return std::max(ABIAlign, (unsigned)getTypeSize(T));
  1955. return ABIAlign;
  1956. }
  1957. /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
  1958. /// for __attribute__((aligned)) on this target, to be used if no alignment
  1959. /// value is specified.
  1960. unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
  1961. return getTargetInfo().getDefaultAlignForAttributeAligned();
  1962. }
  1963. /// getAlignOfGlobalVar - Return the alignment in bits that should be given
  1964. /// to a global variable of the specified type.
  1965. unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
  1966. uint64_t TypeSize = getTypeSize(T.getTypePtr());
  1967. return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign(TypeSize));
  1968. }
  1969. /// getAlignOfGlobalVarInChars - Return the alignment in characters that
  1970. /// should be given to a global variable of the specified type.
  1971. CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
  1972. return toCharUnitsFromBits(getAlignOfGlobalVar(T));
  1973. }
  1974. CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
  1975. CharUnits Offset = CharUnits::Zero();
  1976. const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
  1977. while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
  1978. Offset += Layout->getBaseClassOffset(Base);
  1979. Layout = &getASTRecordLayout(Base);
  1980. }
  1981. return Offset;
  1982. }
  1983. /// DeepCollectObjCIvars -
  1984. /// This routine first collects all declared, but not synthesized, ivars in
  1985. /// super class and then collects all ivars, including those synthesized for
  1986. /// current class. This routine is used for implementation of current class
  1987. /// when all ivars, declared and synthesized are known.
  1988. void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
  1989. bool leafClass,
  1990. SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
  1991. if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
  1992. DeepCollectObjCIvars(SuperClass, false, Ivars);
  1993. if (!leafClass) {
  1994. for (const auto *I : OI->ivars())
  1995. Ivars.push_back(I);
  1996. } else {
  1997. auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
  1998. for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
  1999. Iv= Iv->getNextIvar())
  2000. Ivars.push_back(Iv);
  2001. }
  2002. }
  2003. /// CollectInheritedProtocols - Collect all protocols in current class and
  2004. /// those inherited by it.
  2005. void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
  2006. llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
  2007. if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
  2008. // We can use protocol_iterator here instead of
  2009. // all_referenced_protocol_iterator since we are walking all categories.
  2010. for (auto *Proto : OI->all_referenced_protocols()) {
  2011. CollectInheritedProtocols(Proto, Protocols);
  2012. }
  2013. // Categories of this Interface.
  2014. for (const auto *Cat : OI->visible_categories())
  2015. CollectInheritedProtocols(Cat, Protocols);
  2016. if (ObjCInterfaceDecl *SD = OI->getSuperClass())
  2017. while (SD) {
  2018. CollectInheritedProtocols(SD, Protocols);
  2019. SD = SD->getSuperClass();
  2020. }
  2021. } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
  2022. for (auto *Proto : OC->protocols()) {
  2023. CollectInheritedProtocols(Proto, Protocols);
  2024. }
  2025. } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
  2026. // Insert the protocol.
  2027. if (!Protocols.insert(
  2028. const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
  2029. return;
  2030. for (auto *Proto : OP->protocols())
  2031. CollectInheritedProtocols(Proto, Protocols);
  2032. }
  2033. }
  2034. static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
  2035. const RecordDecl *RD) {
  2036. assert(RD->isUnion() && "Must be union type");
  2037. CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
  2038. for (const auto *Field : RD->fields()) {
  2039. if (!Context.hasUniqueObjectRepresentations(Field->getType()))
  2040. return false;
  2041. CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
  2042. if (FieldSize != UnionSize)
  2043. return false;
  2044. }
  2045. return !RD->field_empty();
  2046. }
  2047. static bool isStructEmpty(QualType Ty) {
  2048. const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
  2049. if (!RD->field_empty())
  2050. return false;
  2051. if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
  2052. return ClassDecl->isEmpty();
  2053. return true;
  2054. }
  2055. static llvm::Optional<int64_t>
  2056. structHasUniqueObjectRepresentations(const ASTContext &Context,
  2057. const RecordDecl *RD) {
  2058. assert(!RD->isUnion() && "Must be struct/class type");
  2059. const auto &Layout = Context.getASTRecordLayout(RD);
  2060. int64_t CurOffsetInBits = 0;
  2061. if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
  2062. if (ClassDecl->isDynamicClass())
  2063. return llvm::None;
  2064. SmallVector<std::pair<QualType, int64_t>, 4> Bases;
  2065. for (const auto Base : ClassDecl->bases()) {
  2066. // Empty types can be inherited from, and non-empty types can potentially
  2067. // have tail padding, so just make sure there isn't an error.
  2068. if (!isStructEmpty(Base.getType())) {
  2069. llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
  2070. Context, Base.getType()->getAs<RecordType>()->getDecl());
  2071. if (!Size)
  2072. return llvm::None;
  2073. Bases.emplace_back(Base.getType(), Size.getValue());
  2074. }
  2075. }
  2076. llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
  2077. const std::pair<QualType, int64_t> &R) {
  2078. return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
  2079. Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
  2080. });
  2081. for (const auto Base : Bases) {
  2082. int64_t BaseOffset = Context.toBits(
  2083. Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
  2084. int64_t BaseSize = Base.second;
  2085. if (BaseOffset != CurOffsetInBits)
  2086. return llvm::None;
  2087. CurOffsetInBits = BaseOffset + BaseSize;
  2088. }
  2089. }
  2090. for (const auto *Field : RD->fields()) {
  2091. if (!Field->getType()->isReferenceType() &&
  2092. !Context.hasUniqueObjectRepresentations(Field->getType()))
  2093. return llvm::None;
  2094. int64_t FieldSizeInBits =
  2095. Context.toBits(Context.getTypeSizeInChars(Field->getType()));
  2096. if (Field->isBitField()) {
  2097. int64_t BitfieldSize = Field->getBitWidthValue(Context);
  2098. if (BitfieldSize > FieldSizeInBits)
  2099. return llvm::None;
  2100. FieldSizeInBits = BitfieldSize;
  2101. }
  2102. int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
  2103. if (FieldOffsetInBits != CurOffsetInBits)
  2104. return llvm::None;
  2105. CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
  2106. }
  2107. return CurOffsetInBits;
  2108. }
  2109. bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
  2110. // C++17 [meta.unary.prop]:
  2111. // The predicate condition for a template specialization
  2112. // has_unique_object_representations<T> shall be
  2113. // satisfied if and only if:
  2114. // (9.1) - T is trivially copyable, and
  2115. // (9.2) - any two objects of type T with the same value have the same
  2116. // object representation, where two objects
  2117. // of array or non-union class type are considered to have the same value
  2118. // if their respective sequences of
  2119. // direct subobjects have the same values, and two objects of union type
  2120. // are considered to have the same
  2121. // value if they have the same active member and the corresponding members
  2122. // have the same value.
  2123. // The set of scalar types for which this condition holds is
  2124. // implementation-defined. [ Note: If a type has padding
  2125. // bits, the condition does not hold; otherwise, the condition holds true
  2126. // for unsigned integral types. -- end note ]
  2127. assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
  2128. // Arrays are unique only if their element type is unique.
  2129. if (Ty->isArrayType())
  2130. return hasUniqueObjectRepresentations(getBaseElementType(Ty));
  2131. // (9.1) - T is trivially copyable...
  2132. if (!Ty.isTriviallyCopyableType(*this))
  2133. return false;
  2134. // All integrals and enums are unique.
  2135. if (Ty->isIntegralOrEnumerationType())
  2136. return true;
  2137. // All other pointers are unique.
  2138. if (Ty->isPointerType())
  2139. return true;
  2140. if (Ty->isMemberPointerType()) {
  2141. const auto *MPT = Ty->getAs<MemberPointerType>();
  2142. return !ABI->getMemberPointerInfo(MPT).HasPadding;
  2143. }
  2144. if (Ty->isRecordType()) {
  2145. const RecordDecl *Record = Ty->getAs<RecordType>()->getDecl();
  2146. if (Record->isInvalidDecl())
  2147. return false;
  2148. if (Record->isUnion())
  2149. return unionHasUniqueObjectRepresentations(*this, Record);
  2150. Optional<int64_t> StructSize =
  2151. structHasUniqueObjectRepresentations(*this, Record);
  2152. return StructSize &&
  2153. StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
  2154. }
  2155. // FIXME: More cases to handle here (list by rsmith):
  2156. // vectors (careful about, eg, vector of 3 foo)
  2157. // _Complex int and friends
  2158. // _Atomic T
  2159. // Obj-C block pointers
  2160. // Obj-C object pointers
  2161. // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
  2162. // clk_event_t, queue_t, reserve_id_t)
  2163. // There're also Obj-C class types and the Obj-C selector type, but I think it
  2164. // makes sense for those to return false here.
  2165. return false;
  2166. }
  2167. unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
  2168. unsigned count = 0;
  2169. // Count ivars declared in class extension.
  2170. for (const auto *Ext : OI->known_extensions())
  2171. count += Ext->ivar_size();
  2172. // Count ivar defined in this class's implementation. This
  2173. // includes synthesized ivars.
  2174. if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
  2175. count += ImplDecl->ivar_size();
  2176. return count;
  2177. }
  2178. bool ASTContext::isSentinelNullExpr(const Expr *E) {
  2179. if (!E)
  2180. return false;
  2181. // nullptr_t is always treated as null.
  2182. if (E->getType()->isNullPtrType()) return true;
  2183. if (E->getType()->isAnyPointerType() &&
  2184. E->IgnoreParenCasts()->isNullPointerConstant(*this,
  2185. Expr::NPC_ValueDependentIsNull))
  2186. return true;
  2187. // Unfortunately, __null has type 'int'.
  2188. if (isa<GNUNullExpr>(E)) return true;
  2189. return false;
  2190. }
  2191. /// Get the implementation of ObjCInterfaceDecl, or nullptr if none
  2192. /// exists.
  2193. ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
  2194. llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
  2195. I = ObjCImpls.find(D);
  2196. if (I != ObjCImpls.end())
  2197. return cast<ObjCImplementationDecl>(I->second);
  2198. return nullptr;
  2199. }
  2200. /// Get the implementation of ObjCCategoryDecl, or nullptr if none
  2201. /// exists.
  2202. ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
  2203. llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
  2204. I = ObjCImpls.find(D);
  2205. if (I != ObjCImpls.end())
  2206. return cast<ObjCCategoryImplDecl>(I->second);
  2207. return nullptr;
  2208. }
  2209. /// Set the implementation of ObjCInterfaceDecl.
  2210. void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
  2211. ObjCImplementationDecl *ImplD) {
  2212. assert(IFaceD && ImplD && "Passed null params");
  2213. ObjCImpls[IFaceD] = ImplD;
  2214. }
  2215. /// Set the implementation of ObjCCategoryDecl.
  2216. void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
  2217. ObjCCategoryImplDecl *ImplD) {
  2218. assert(CatD && ImplD && "Passed null params");
  2219. ObjCImpls[CatD] = ImplD;
  2220. }
  2221. const ObjCMethodDecl *
  2222. ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
  2223. return ObjCMethodRedecls.lookup(MD);
  2224. }
  2225. void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
  2226. const ObjCMethodDecl *Redecl) {
  2227. assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
  2228. ObjCMethodRedecls[MD] = Redecl;
  2229. }
  2230. const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
  2231. const NamedDecl *ND) const {
  2232. if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
  2233. return ID;
  2234. if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
  2235. return CD->getClassInterface();
  2236. if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
  2237. return IMD->getClassInterface();
  2238. return nullptr;
  2239. }
  2240. /// Get the copy initialization expression of VarDecl, or nullptr if
  2241. /// none exists.
  2242. ASTContext::BlockVarCopyInit
  2243. ASTContext::getBlockVarCopyInit(const VarDecl*VD) const {
  2244. assert(VD && "Passed null params");
  2245. assert(VD->hasAttr<BlocksAttr>() &&
  2246. "getBlockVarCopyInits - not __block var");
  2247. auto I = BlockVarCopyInits.find(VD);
  2248. if (I != BlockVarCopyInits.end())
  2249. return I->second;
  2250. return {nullptr, false};
  2251. }
  2252. /// Set the copy initialization expression of a block var decl.
  2253. void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
  2254. bool CanThrow) {
  2255. assert(VD && CopyExpr && "Passed null params");
  2256. assert(VD->hasAttr<BlocksAttr>() &&
  2257. "setBlockVarCopyInits - not __block var");
  2258. BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
  2259. }
  2260. TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
  2261. unsigned DataSize) const {
  2262. if (!DataSize)
  2263. DataSize = TypeLoc::getFullDataSizeForType(T);
  2264. else
  2265. assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
  2266. "incorrect data size provided to CreateTypeSourceInfo!");
  2267. auto *TInfo =
  2268. (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
  2269. new (TInfo) TypeSourceInfo(T);
  2270. return TInfo;
  2271. }
  2272. TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
  2273. SourceLocation L) const {
  2274. TypeSourceInfo *DI = CreateTypeSourceInfo(T);
  2275. DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
  2276. return DI;
  2277. }
  2278. const ASTRecordLayout &
  2279. ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
  2280. return getObjCLayout(D, nullptr);
  2281. }
  2282. const ASTRecordLayout &
  2283. ASTContext::getASTObjCImplementationLayout(
  2284. const ObjCImplementationDecl *D) const {
  2285. return getObjCLayout(D->getClassInterface(), D);
  2286. }
  2287. //===----------------------------------------------------------------------===//
  2288. // Type creation/memoization methods
  2289. //===----------------------------------------------------------------------===//
  2290. QualType
  2291. ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
  2292. unsigned fastQuals = quals.getFastQualifiers();
  2293. quals.removeFastQualifiers();
  2294. // Check if we've already instantiated this type.
  2295. llvm::FoldingSetNodeID ID;
  2296. ExtQuals::Profile(ID, baseType, quals);
  2297. void *insertPos = nullptr;
  2298. if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
  2299. assert(eq->getQualifiers() == quals);
  2300. return QualType(eq, fastQuals);
  2301. }
  2302. // If the base type is not canonical, make the appropriate canonical type.
  2303. QualType canon;
  2304. if (!baseType->isCanonicalUnqualified()) {
  2305. SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
  2306. canonSplit.Quals.addConsistentQualifiers(quals);
  2307. canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
  2308. // Re-find the insert position.
  2309. (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
  2310. }
  2311. auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
  2312. ExtQualNodes.InsertNode(eq, insertPos);
  2313. return QualType(eq, fastQuals);
  2314. }
  2315. QualType ASTContext::getAddrSpaceQualType(QualType T,
  2316. LangAS AddressSpace) const {
  2317. QualType CanT = getCanonicalType(T);
  2318. if (CanT.getAddressSpace() == AddressSpace)
  2319. return T;
  2320. // If we are composing extended qualifiers together, merge together
  2321. // into one ExtQuals node.
  2322. QualifierCollector Quals;
  2323. const Type *TypeNode = Quals.strip(T);
  2324. // If this type already has an address space specified, it cannot get
  2325. // another one.
  2326. assert(!Quals.hasAddressSpace() &&
  2327. "Type cannot be in multiple addr spaces!");
  2328. Quals.addAddressSpace(AddressSpace);
  2329. return getExtQualType(TypeNode, Quals);
  2330. }
  2331. QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
  2332. // If we are composing extended qualifiers together, merge together
  2333. // into one ExtQuals node.
  2334. QualifierCollector Quals;
  2335. const Type *TypeNode = Quals.strip(T);
  2336. // If the qualifier doesn't have an address space just return it.
  2337. if (!Quals.hasAddressSpace())
  2338. return T;
  2339. Quals.removeAddressSpace();
  2340. // Removal of the address space can mean there are no longer any
  2341. // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
  2342. // or required.
  2343. if (Quals.hasNonFastQualifiers())
  2344. return getExtQualType(TypeNode, Quals);
  2345. else
  2346. return QualType(TypeNode, Quals.getFastQualifiers());
  2347. }
  2348. QualType ASTContext::getObjCGCQualType(QualType T,
  2349. Qualifiers::GC GCAttr) const {
  2350. QualType CanT = getCanonicalType(T);
  2351. if (CanT.getObjCGCAttr() == GCAttr)
  2352. return T;
  2353. if (const auto *ptr = T->getAs<PointerType>()) {
  2354. QualType Pointee = ptr->getPointeeType();
  2355. if (Pointee->isAnyPointerType()) {
  2356. QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
  2357. return getPointerType(ResultType);
  2358. }
  2359. }
  2360. // If we are composing extended qualifiers together, merge together
  2361. // into one ExtQuals node.
  2362. QualifierCollector Quals;
  2363. const Type *TypeNode = Quals.strip(T);
  2364. // If this type already has an ObjCGC specified, it cannot get
  2365. // another one.
  2366. assert(!Quals.hasObjCGCAttr() &&
  2367. "Type cannot have multiple ObjCGCs!");
  2368. Quals.addObjCGCAttr(GCAttr);
  2369. return getExtQualType(TypeNode, Quals);
  2370. }
  2371. const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
  2372. FunctionType::ExtInfo Info) {
  2373. if (T->getExtInfo() == Info)
  2374. return T;
  2375. QualType Result;
  2376. if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
  2377. Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
  2378. } else {
  2379. const auto *FPT = cast<FunctionProtoType>(T);
  2380. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  2381. EPI.ExtInfo = Info;
  2382. Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
  2383. }
  2384. return cast<FunctionType>(Result.getTypePtr());
  2385. }
  2386. void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
  2387. QualType ResultType) {
  2388. FD = FD->getMostRecentDecl();
  2389. while (true) {
  2390. const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
  2391. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  2392. FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
  2393. if (FunctionDecl *Next = FD->getPreviousDecl())
  2394. FD = Next;
  2395. else
  2396. break;
  2397. }
  2398. if (ASTMutationListener *L = getASTMutationListener())
  2399. L->DeducedReturnType(FD, ResultType);
  2400. }
  2401. /// Get a function type and produce the equivalent function type with the
  2402. /// specified exception specification. Type sugar that can be present on a
  2403. /// declaration of a function with an exception specification is permitted
  2404. /// and preserved. Other type sugar (for instance, typedefs) is not.
  2405. QualType ASTContext::getFunctionTypeWithExceptionSpec(
  2406. QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
  2407. // Might have some parens.
  2408. if (const auto *PT = dyn_cast<ParenType>(Orig))
  2409. return getParenType(
  2410. getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
  2411. // Might have a calling-convention attribute.
  2412. if (const auto *AT = dyn_cast<AttributedType>(Orig))
  2413. return getAttributedType(
  2414. AT->getAttrKind(),
  2415. getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
  2416. getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
  2417. // Anything else must be a function type. Rebuild it with the new exception
  2418. // specification.
  2419. const auto *Proto = Orig->getAs<FunctionProtoType>();
  2420. return getFunctionType(
  2421. Proto->getReturnType(), Proto->getParamTypes(),
  2422. Proto->getExtProtoInfo().withExceptionSpec(ESI));
  2423. }
  2424. bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
  2425. QualType U) {
  2426. return hasSameType(T, U) ||
  2427. (getLangOpts().CPlusPlus17 &&
  2428. hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
  2429. getFunctionTypeWithExceptionSpec(U, EST_None)));
  2430. }
  2431. void ASTContext::adjustExceptionSpec(
  2432. FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
  2433. bool AsWritten) {
  2434. // Update the type.
  2435. QualType Updated =
  2436. getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
  2437. FD->setType(Updated);
  2438. if (!AsWritten)
  2439. return;
  2440. // Update the type in the type source information too.
  2441. if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
  2442. // If the type and the type-as-written differ, we may need to update
  2443. // the type-as-written too.
  2444. if (TSInfo->getType() != FD->getType())
  2445. Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
  2446. // FIXME: When we get proper type location information for exceptions,
  2447. // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
  2448. // up the TypeSourceInfo;
  2449. assert(TypeLoc::getFullDataSizeForType(Updated) ==
  2450. TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
  2451. "TypeLoc size mismatch from updating exception specification");
  2452. TSInfo->overrideType(Updated);
  2453. }
  2454. }
  2455. /// getComplexType - Return the uniqued reference to the type for a complex
  2456. /// number with the specified element type.
  2457. QualType ASTContext::getComplexType(QualType T) const {
  2458. // Unique pointers, to guarantee there is only one pointer of a particular
  2459. // structure.
  2460. llvm::FoldingSetNodeID ID;
  2461. ComplexType::Profile(ID, T);
  2462. void *InsertPos = nullptr;
  2463. if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
  2464. return QualType(CT, 0);
  2465. // If the pointee type isn't canonical, this won't be a canonical type either,
  2466. // so fill in the canonical type field.
  2467. QualType Canonical;
  2468. if (!T.isCanonical()) {
  2469. Canonical = getComplexType(getCanonicalType(T));
  2470. // Get the new insert position for the node we care about.
  2471. ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
  2472. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2473. }
  2474. auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
  2475. Types.push_back(New);
  2476. ComplexTypes.InsertNode(New, InsertPos);
  2477. return QualType(New, 0);
  2478. }
  2479. /// getPointerType - Return the uniqued reference to the type for a pointer to
  2480. /// the specified type.
  2481. QualType ASTContext::getPointerType(QualType T) const {
  2482. // Unique pointers, to guarantee there is only one pointer of a particular
  2483. // structure.
  2484. llvm::FoldingSetNodeID ID;
  2485. PointerType::Profile(ID, T);
  2486. void *InsertPos = nullptr;
  2487. if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  2488. return QualType(PT, 0);
  2489. // If the pointee type isn't canonical, this won't be a canonical type either,
  2490. // so fill in the canonical type field.
  2491. QualType Canonical;
  2492. if (!T.isCanonical()) {
  2493. Canonical = getPointerType(getCanonicalType(T));
  2494. // Get the new insert position for the node we care about.
  2495. PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  2496. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2497. }
  2498. auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
  2499. Types.push_back(New);
  2500. PointerTypes.InsertNode(New, InsertPos);
  2501. return QualType(New, 0);
  2502. }
  2503. QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
  2504. llvm::FoldingSetNodeID ID;
  2505. AdjustedType::Profile(ID, Orig, New);
  2506. void *InsertPos = nullptr;
  2507. AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2508. if (AT)
  2509. return QualType(AT, 0);
  2510. QualType Canonical = getCanonicalType(New);
  2511. // Get the new insert position for the node we care about.
  2512. AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2513. assert(!AT && "Shouldn't be in the map!");
  2514. AT = new (*this, TypeAlignment)
  2515. AdjustedType(Type::Adjusted, Orig, New, Canonical);
  2516. Types.push_back(AT);
  2517. AdjustedTypes.InsertNode(AT, InsertPos);
  2518. return QualType(AT, 0);
  2519. }
  2520. QualType ASTContext::getDecayedType(QualType T) const {
  2521. assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
  2522. QualType Decayed;
  2523. // C99 6.7.5.3p7:
  2524. // A declaration of a parameter as "array of type" shall be
  2525. // adjusted to "qualified pointer to type", where the type
  2526. // qualifiers (if any) are those specified within the [ and ] of
  2527. // the array type derivation.
  2528. if (T->isArrayType())
  2529. Decayed = getArrayDecayedType(T);
  2530. // C99 6.7.5.3p8:
  2531. // A declaration of a parameter as "function returning type"
  2532. // shall be adjusted to "pointer to function returning type", as
  2533. // in 6.3.2.1.
  2534. if (T->isFunctionType())
  2535. Decayed = getPointerType(T);
  2536. llvm::FoldingSetNodeID ID;
  2537. AdjustedType::Profile(ID, T, Decayed);
  2538. void *InsertPos = nullptr;
  2539. AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2540. if (AT)
  2541. return QualType(AT, 0);
  2542. QualType Canonical = getCanonicalType(Decayed);
  2543. // Get the new insert position for the node we care about.
  2544. AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2545. assert(!AT && "Shouldn't be in the map!");
  2546. AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
  2547. Types.push_back(AT);
  2548. AdjustedTypes.InsertNode(AT, InsertPos);
  2549. return QualType(AT, 0);
  2550. }
  2551. /// getBlockPointerType - Return the uniqued reference to the type for
  2552. /// a pointer to the specified block.
  2553. QualType ASTContext::getBlockPointerType(QualType T) const {
  2554. assert(T->isFunctionType() && "block of function types only");
  2555. // Unique pointers, to guarantee there is only one block of a particular
  2556. // structure.
  2557. llvm::FoldingSetNodeID ID;
  2558. BlockPointerType::Profile(ID, T);
  2559. void *InsertPos = nullptr;
  2560. if (BlockPointerType *PT =
  2561. BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  2562. return QualType(PT, 0);
  2563. // If the block pointee type isn't canonical, this won't be a canonical
  2564. // type either so fill in the canonical type field.
  2565. QualType Canonical;
  2566. if (!T.isCanonical()) {
  2567. Canonical = getBlockPointerType(getCanonicalType(T));
  2568. // Get the new insert position for the node we care about.
  2569. BlockPointerType *NewIP =
  2570. BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  2571. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2572. }
  2573. auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
  2574. Types.push_back(New);
  2575. BlockPointerTypes.InsertNode(New, InsertPos);
  2576. return QualType(New, 0);
  2577. }
  2578. /// getLValueReferenceType - Return the uniqued reference to the type for an
  2579. /// lvalue reference to the specified type.
  2580. QualType
  2581. ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
  2582. assert(getCanonicalType(T) != OverloadTy &&
  2583. "Unresolved overloaded function type");
  2584. // Unique pointers, to guarantee there is only one pointer of a particular
  2585. // structure.
  2586. llvm::FoldingSetNodeID ID;
  2587. ReferenceType::Profile(ID, T, SpelledAsLValue);
  2588. void *InsertPos = nullptr;
  2589. if (LValueReferenceType *RT =
  2590. LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
  2591. return QualType(RT, 0);
  2592. const auto *InnerRef = T->getAs<ReferenceType>();
  2593. // If the referencee type isn't canonical, this won't be a canonical type
  2594. // either, so fill in the canonical type field.
  2595. QualType Canonical;
  2596. if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
  2597. QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
  2598. Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
  2599. // Get the new insert position for the node we care about.
  2600. LValueReferenceType *NewIP =
  2601. LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
  2602. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2603. }
  2604. auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
  2605. SpelledAsLValue);
  2606. Types.push_back(New);
  2607. LValueReferenceTypes.InsertNode(New, InsertPos);
  2608. return QualType(New, 0);
  2609. }
  2610. /// getRValueReferenceType - Return the uniqued reference to the type for an
  2611. /// rvalue reference to the specified type.
  2612. QualType ASTContext::getRValueReferenceType(QualType T) const {
  2613. // Unique pointers, to guarantee there is only one pointer of a particular
  2614. // structure.
  2615. llvm::FoldingSetNodeID ID;
  2616. ReferenceType::Profile(ID, T, false);
  2617. void *InsertPos = nullptr;
  2618. if (RValueReferenceType *RT =
  2619. RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
  2620. return QualType(RT, 0);
  2621. const auto *InnerRef = T->getAs<ReferenceType>();
  2622. // If the referencee type isn't canonical, this won't be a canonical type
  2623. // either, so fill in the canonical type field.
  2624. QualType Canonical;
  2625. if (InnerRef || !T.isCanonical()) {
  2626. QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
  2627. Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
  2628. // Get the new insert position for the node we care about.
  2629. RValueReferenceType *NewIP =
  2630. RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
  2631. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2632. }
  2633. auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
  2634. Types.push_back(New);
  2635. RValueReferenceTypes.InsertNode(New, InsertPos);
  2636. return QualType(New, 0);
  2637. }
  2638. /// getMemberPointerType - Return the uniqued reference to the type for a
  2639. /// member pointer to the specified type, in the specified class.
  2640. QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
  2641. // Unique pointers, to guarantee there is only one pointer of a particular
  2642. // structure.
  2643. llvm::FoldingSetNodeID ID;
  2644. MemberPointerType::Profile(ID, T, Cls);
  2645. void *InsertPos = nullptr;
  2646. if (MemberPointerType *PT =
  2647. MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  2648. return QualType(PT, 0);
  2649. // If the pointee or class type isn't canonical, this won't be a canonical
  2650. // type either, so fill in the canonical type field.
  2651. QualType Canonical;
  2652. if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
  2653. Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
  2654. // Get the new insert position for the node we care about.
  2655. MemberPointerType *NewIP =
  2656. MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  2657. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2658. }
  2659. auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
  2660. Types.push_back(New);
  2661. MemberPointerTypes.InsertNode(New, InsertPos);
  2662. return QualType(New, 0);
  2663. }
  2664. /// getConstantArrayType - Return the unique reference to the type for an
  2665. /// array of the specified element type.
  2666. QualType ASTContext::getConstantArrayType(QualType EltTy,
  2667. const llvm::APInt &ArySizeIn,
  2668. ArrayType::ArraySizeModifier ASM,
  2669. unsigned IndexTypeQuals) const {
  2670. assert((EltTy->isDependentType() ||
  2671. EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
  2672. "Constant array of VLAs is illegal!");
  2673. // Convert the array size into a canonical width matching the pointer size for
  2674. // the target.
  2675. llvm::APInt ArySize(ArySizeIn);
  2676. ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
  2677. llvm::FoldingSetNodeID ID;
  2678. ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
  2679. void *InsertPos = nullptr;
  2680. if (ConstantArrayType *ATP =
  2681. ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
  2682. return QualType(ATP, 0);
  2683. // If the element type isn't canonical or has qualifiers, this won't
  2684. // be a canonical type either, so fill in the canonical type field.
  2685. QualType Canon;
  2686. if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
  2687. SplitQualType canonSplit = getCanonicalType(EltTy).split();
  2688. Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
  2689. ASM, IndexTypeQuals);
  2690. Canon = getQualifiedType(Canon, canonSplit.Quals);
  2691. // Get the new insert position for the node we care about.
  2692. ConstantArrayType *NewIP =
  2693. ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
  2694. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2695. }
  2696. auto *New = new (*this,TypeAlignment)
  2697. ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
  2698. ConstantArrayTypes.InsertNode(New, InsertPos);
  2699. Types.push_back(New);
  2700. return QualType(New, 0);
  2701. }
  2702. /// getVariableArrayDecayedType - Turns the given type, which may be
  2703. /// variably-modified, into the corresponding type with all the known
  2704. /// sizes replaced with [*].
  2705. QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
  2706. // Vastly most common case.
  2707. if (!type->isVariablyModifiedType()) return type;
  2708. QualType result;
  2709. SplitQualType split = type.getSplitDesugaredType();
  2710. const Type *ty = split.Ty;
  2711. switch (ty->getTypeClass()) {
  2712. #define TYPE(Class, Base)
  2713. #define ABSTRACT_TYPE(Class, Base)
  2714. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  2715. #include "clang/AST/TypeNodes.def"
  2716. llvm_unreachable("didn't desugar past all non-canonical types?");
  2717. // These types should never be variably-modified.
  2718. case Type::Builtin:
  2719. case Type::Complex:
  2720. case Type::Vector:
  2721. case Type::DependentVector:
  2722. case Type::ExtVector:
  2723. case Type::DependentSizedExtVector:
  2724. case Type::DependentAddressSpace:
  2725. case Type::ObjCObject:
  2726. case Type::ObjCInterface:
  2727. case Type::ObjCObjectPointer:
  2728. case Type::Record:
  2729. case Type::Enum:
  2730. case Type::UnresolvedUsing:
  2731. case Type::TypeOfExpr:
  2732. case Type::TypeOf:
  2733. case Type::Decltype:
  2734. case Type::UnaryTransform:
  2735. case Type::DependentName:
  2736. case Type::InjectedClassName:
  2737. case Type::TemplateSpecialization:
  2738. case Type::DependentTemplateSpecialization:
  2739. case Type::TemplateTypeParm:
  2740. case Type::SubstTemplateTypeParmPack:
  2741. case Type::Auto:
  2742. case Type::DeducedTemplateSpecialization:
  2743. case Type::PackExpansion:
  2744. llvm_unreachable("type should never be variably-modified");
  2745. // These types can be variably-modified but should never need to
  2746. // further decay.
  2747. case Type::FunctionNoProto:
  2748. case Type::FunctionProto:
  2749. case Type::BlockPointer:
  2750. case Type::MemberPointer:
  2751. case Type::Pipe:
  2752. return type;
  2753. // These types can be variably-modified. All these modifications
  2754. // preserve structure except as noted by comments.
  2755. // TODO: if we ever care about optimizing VLAs, there are no-op
  2756. // optimizations available here.
  2757. case Type::Pointer:
  2758. result = getPointerType(getVariableArrayDecayedType(
  2759. cast<PointerType>(ty)->getPointeeType()));
  2760. break;
  2761. case Type::LValueReference: {
  2762. const auto *lv = cast<LValueReferenceType>(ty);
  2763. result = getLValueReferenceType(
  2764. getVariableArrayDecayedType(lv->getPointeeType()),
  2765. lv->isSpelledAsLValue());
  2766. break;
  2767. }
  2768. case Type::RValueReference: {
  2769. const auto *lv = cast<RValueReferenceType>(ty);
  2770. result = getRValueReferenceType(
  2771. getVariableArrayDecayedType(lv->getPointeeType()));
  2772. break;
  2773. }
  2774. case Type::Atomic: {
  2775. const auto *at = cast<AtomicType>(ty);
  2776. result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
  2777. break;
  2778. }
  2779. case Type::ConstantArray: {
  2780. const auto *cat = cast<ConstantArrayType>(ty);
  2781. result = getConstantArrayType(
  2782. getVariableArrayDecayedType(cat->getElementType()),
  2783. cat->getSize(),
  2784. cat->getSizeModifier(),
  2785. cat->getIndexTypeCVRQualifiers());
  2786. break;
  2787. }
  2788. case Type::DependentSizedArray: {
  2789. const auto *dat = cast<DependentSizedArrayType>(ty);
  2790. result = getDependentSizedArrayType(
  2791. getVariableArrayDecayedType(dat->getElementType()),
  2792. dat->getSizeExpr(),
  2793. dat->getSizeModifier(),
  2794. dat->getIndexTypeCVRQualifiers(),
  2795. dat->getBracketsRange());
  2796. break;
  2797. }
  2798. // Turn incomplete types into [*] types.
  2799. case Type::IncompleteArray: {
  2800. const auto *iat = cast<IncompleteArrayType>(ty);
  2801. result = getVariableArrayType(
  2802. getVariableArrayDecayedType(iat->getElementType()),
  2803. /*size*/ nullptr,
  2804. ArrayType::Normal,
  2805. iat->getIndexTypeCVRQualifiers(),
  2806. SourceRange());
  2807. break;
  2808. }
  2809. // Turn VLA types into [*] types.
  2810. case Type::VariableArray: {
  2811. const auto *vat = cast<VariableArrayType>(ty);
  2812. result = getVariableArrayType(
  2813. getVariableArrayDecayedType(vat->getElementType()),
  2814. /*size*/ nullptr,
  2815. ArrayType::Star,
  2816. vat->getIndexTypeCVRQualifiers(),
  2817. vat->getBracketsRange());
  2818. break;
  2819. }
  2820. }
  2821. // Apply the top-level qualifiers from the original.
  2822. return getQualifiedType(result, split.Quals);
  2823. }
  2824. /// getVariableArrayType - Returns a non-unique reference to the type for a
  2825. /// variable array of the specified element type.
  2826. QualType ASTContext::getVariableArrayType(QualType EltTy,
  2827. Expr *NumElts,
  2828. ArrayType::ArraySizeModifier ASM,
  2829. unsigned IndexTypeQuals,
  2830. SourceRange Brackets) const {
  2831. // Since we don't unique expressions, it isn't possible to unique VLA's
  2832. // that have an expression provided for their size.
  2833. QualType Canon;
  2834. // Be sure to pull qualifiers off the element type.
  2835. if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
  2836. SplitQualType canonSplit = getCanonicalType(EltTy).split();
  2837. Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
  2838. IndexTypeQuals, Brackets);
  2839. Canon = getQualifiedType(Canon, canonSplit.Quals);
  2840. }
  2841. auto *New = new (*this, TypeAlignment)
  2842. VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
  2843. VariableArrayTypes.push_back(New);
  2844. Types.push_back(New);
  2845. return QualType(New, 0);
  2846. }
  2847. /// getDependentSizedArrayType - Returns a non-unique reference to
  2848. /// the type for a dependently-sized array of the specified element
  2849. /// type.
  2850. QualType ASTContext::getDependentSizedArrayType(QualType elementType,
  2851. Expr *numElements,
  2852. ArrayType::ArraySizeModifier ASM,
  2853. unsigned elementTypeQuals,
  2854. SourceRange brackets) const {
  2855. assert((!numElements || numElements->isTypeDependent() ||
  2856. numElements->isValueDependent()) &&
  2857. "Size must be type- or value-dependent!");
  2858. // Dependently-sized array types that do not have a specified number
  2859. // of elements will have their sizes deduced from a dependent
  2860. // initializer. We do no canonicalization here at all, which is okay
  2861. // because they can't be used in most locations.
  2862. if (!numElements) {
  2863. auto *newType
  2864. = new (*this, TypeAlignment)
  2865. DependentSizedArrayType(*this, elementType, QualType(),
  2866. numElements, ASM, elementTypeQuals,
  2867. brackets);
  2868. Types.push_back(newType);
  2869. return QualType(newType, 0);
  2870. }
  2871. // Otherwise, we actually build a new type every time, but we
  2872. // also build a canonical type.
  2873. SplitQualType canonElementType = getCanonicalType(elementType).split();
  2874. void *insertPos = nullptr;
  2875. llvm::FoldingSetNodeID ID;
  2876. DependentSizedArrayType::Profile(ID, *this,
  2877. QualType(canonElementType.Ty, 0),
  2878. ASM, elementTypeQuals, numElements);
  2879. // Look for an existing type with these properties.
  2880. DependentSizedArrayType *canonTy =
  2881. DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
  2882. // If we don't have one, build one.
  2883. if (!canonTy) {
  2884. canonTy = new (*this, TypeAlignment)
  2885. DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
  2886. QualType(), numElements, ASM, elementTypeQuals,
  2887. brackets);
  2888. DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
  2889. Types.push_back(canonTy);
  2890. }
  2891. // Apply qualifiers from the element type to the array.
  2892. QualType canon = getQualifiedType(QualType(canonTy,0),
  2893. canonElementType.Quals);
  2894. // If we didn't need extra canonicalization for the element type or the size
  2895. // expression, then just use that as our result.
  2896. if (QualType(canonElementType.Ty, 0) == elementType &&
  2897. canonTy->getSizeExpr() == numElements)
  2898. return canon;
  2899. // Otherwise, we need to build a type which follows the spelling
  2900. // of the element type.
  2901. auto *sugaredType
  2902. = new (*this, TypeAlignment)
  2903. DependentSizedArrayType(*this, elementType, canon, numElements,
  2904. ASM, elementTypeQuals, brackets);
  2905. Types.push_back(sugaredType);
  2906. return QualType(sugaredType, 0);
  2907. }
  2908. QualType ASTContext::getIncompleteArrayType(QualType elementType,
  2909. ArrayType::ArraySizeModifier ASM,
  2910. unsigned elementTypeQuals) const {
  2911. llvm::FoldingSetNodeID ID;
  2912. IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
  2913. void *insertPos = nullptr;
  2914. if (IncompleteArrayType *iat =
  2915. IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
  2916. return QualType(iat, 0);
  2917. // If the element type isn't canonical, this won't be a canonical type
  2918. // either, so fill in the canonical type field. We also have to pull
  2919. // qualifiers off the element type.
  2920. QualType canon;
  2921. if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
  2922. SplitQualType canonSplit = getCanonicalType(elementType).split();
  2923. canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
  2924. ASM, elementTypeQuals);
  2925. canon = getQualifiedType(canon, canonSplit.Quals);
  2926. // Get the new insert position for the node we care about.
  2927. IncompleteArrayType *existing =
  2928. IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
  2929. assert(!existing && "Shouldn't be in the map!"); (void) existing;
  2930. }
  2931. auto *newType = new (*this, TypeAlignment)
  2932. IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
  2933. IncompleteArrayTypes.InsertNode(newType, insertPos);
  2934. Types.push_back(newType);
  2935. return QualType(newType, 0);
  2936. }
  2937. /// getVectorType - Return the unique reference to a vector type of
  2938. /// the specified element type and size. VectorType must be a built-in type.
  2939. QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
  2940. VectorType::VectorKind VecKind) const {
  2941. assert(vecType->isBuiltinType());
  2942. // Check if we've already instantiated a vector of this type.
  2943. llvm::FoldingSetNodeID ID;
  2944. VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
  2945. void *InsertPos = nullptr;
  2946. if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
  2947. return QualType(VTP, 0);
  2948. // If the element type isn't canonical, this won't be a canonical type either,
  2949. // so fill in the canonical type field.
  2950. QualType Canonical;
  2951. if (!vecType.isCanonical()) {
  2952. Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
  2953. // Get the new insert position for the node we care about.
  2954. VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  2955. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2956. }
  2957. auto *New = new (*this, TypeAlignment)
  2958. VectorType(vecType, NumElts, Canonical, VecKind);
  2959. VectorTypes.InsertNode(New, InsertPos);
  2960. Types.push_back(New);
  2961. return QualType(New, 0);
  2962. }
  2963. QualType
  2964. ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
  2965. SourceLocation AttrLoc,
  2966. VectorType::VectorKind VecKind) const {
  2967. llvm::FoldingSetNodeID ID;
  2968. DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
  2969. VecKind);
  2970. void *InsertPos = nullptr;
  2971. DependentVectorType *Canon =
  2972. DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  2973. DependentVectorType *New;
  2974. if (Canon) {
  2975. New = new (*this, TypeAlignment) DependentVectorType(
  2976. *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
  2977. } else {
  2978. QualType CanonVecTy = getCanonicalType(VecType);
  2979. if (CanonVecTy == VecType) {
  2980. New = new (*this, TypeAlignment) DependentVectorType(
  2981. *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
  2982. DependentVectorType *CanonCheck =
  2983. DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  2984. assert(!CanonCheck &&
  2985. "Dependent-sized vector_size canonical type broken");
  2986. (void)CanonCheck;
  2987. DependentVectorTypes.InsertNode(New, InsertPos);
  2988. } else {
  2989. QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
  2990. SourceLocation());
  2991. New = new (*this, TypeAlignment) DependentVectorType(
  2992. *this, VecType, Canon, SizeExpr, AttrLoc, VecKind);
  2993. }
  2994. }
  2995. Types.push_back(New);
  2996. return QualType(New, 0);
  2997. }
  2998. /// getExtVectorType - Return the unique reference to an extended vector type of
  2999. /// the specified element type and size. VectorType must be a built-in type.
  3000. QualType
  3001. ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
  3002. assert(vecType->isBuiltinType() || vecType->isDependentType());
  3003. // Check if we've already instantiated a vector of this type.
  3004. llvm::FoldingSetNodeID ID;
  3005. VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
  3006. VectorType::GenericVector);
  3007. void *InsertPos = nullptr;
  3008. if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
  3009. return QualType(VTP, 0);
  3010. // If the element type isn't canonical, this won't be a canonical type either,
  3011. // so fill in the canonical type field.
  3012. QualType Canonical;
  3013. if (!vecType.isCanonical()) {
  3014. Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
  3015. // Get the new insert position for the node we care about.
  3016. VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  3017. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3018. }
  3019. auto *New = new (*this, TypeAlignment)
  3020. ExtVectorType(vecType, NumElts, Canonical);
  3021. VectorTypes.InsertNode(New, InsertPos);
  3022. Types.push_back(New);
  3023. return QualType(New, 0);
  3024. }
  3025. QualType
  3026. ASTContext::getDependentSizedExtVectorType(QualType vecType,
  3027. Expr *SizeExpr,
  3028. SourceLocation AttrLoc) const {
  3029. llvm::FoldingSetNodeID ID;
  3030. DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
  3031. SizeExpr);
  3032. void *InsertPos = nullptr;
  3033. DependentSizedExtVectorType *Canon
  3034. = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  3035. DependentSizedExtVectorType *New;
  3036. if (Canon) {
  3037. // We already have a canonical version of this array type; use it as
  3038. // the canonical type for a newly-built type.
  3039. New = new (*this, TypeAlignment)
  3040. DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
  3041. SizeExpr, AttrLoc);
  3042. } else {
  3043. QualType CanonVecTy = getCanonicalType(vecType);
  3044. if (CanonVecTy == vecType) {
  3045. New = new (*this, TypeAlignment)
  3046. DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
  3047. AttrLoc);
  3048. DependentSizedExtVectorType *CanonCheck
  3049. = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  3050. assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
  3051. (void)CanonCheck;
  3052. DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
  3053. } else {
  3054. QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
  3055. SourceLocation());
  3056. New = new (*this, TypeAlignment)
  3057. DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
  3058. }
  3059. }
  3060. Types.push_back(New);
  3061. return QualType(New, 0);
  3062. }
  3063. QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
  3064. Expr *AddrSpaceExpr,
  3065. SourceLocation AttrLoc) const {
  3066. assert(AddrSpaceExpr->isInstantiationDependent());
  3067. QualType canonPointeeType = getCanonicalType(PointeeType);
  3068. void *insertPos = nullptr;
  3069. llvm::FoldingSetNodeID ID;
  3070. DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
  3071. AddrSpaceExpr);
  3072. DependentAddressSpaceType *canonTy =
  3073. DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
  3074. if (!canonTy) {
  3075. canonTy = new (*this, TypeAlignment)
  3076. DependentAddressSpaceType(*this, canonPointeeType,
  3077. QualType(), AddrSpaceExpr, AttrLoc);
  3078. DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
  3079. Types.push_back(canonTy);
  3080. }
  3081. if (canonPointeeType == PointeeType &&
  3082. canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
  3083. return QualType(canonTy, 0);
  3084. auto *sugaredType
  3085. = new (*this, TypeAlignment)
  3086. DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
  3087. AddrSpaceExpr, AttrLoc);
  3088. Types.push_back(sugaredType);
  3089. return QualType(sugaredType, 0);
  3090. }
  3091. /// Determine whether \p T is canonical as the result type of a function.
  3092. static bool isCanonicalResultType(QualType T) {
  3093. return T.isCanonical() &&
  3094. (T.getObjCLifetime() == Qualifiers::OCL_None ||
  3095. T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
  3096. }
  3097. /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
  3098. QualType
  3099. ASTContext::getFunctionNoProtoType(QualType ResultTy,
  3100. const FunctionType::ExtInfo &Info) const {
  3101. // Unique functions, to guarantee there is only one function of a particular
  3102. // structure.
  3103. llvm::FoldingSetNodeID ID;
  3104. FunctionNoProtoType::Profile(ID, ResultTy, Info);
  3105. void *InsertPos = nullptr;
  3106. if (FunctionNoProtoType *FT =
  3107. FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
  3108. return QualType(FT, 0);
  3109. QualType Canonical;
  3110. if (!isCanonicalResultType(ResultTy)) {
  3111. Canonical =
  3112. getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
  3113. // Get the new insert position for the node we care about.
  3114. FunctionNoProtoType *NewIP =
  3115. FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
  3116. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3117. }
  3118. auto *New = new (*this, TypeAlignment)
  3119. FunctionNoProtoType(ResultTy, Canonical, Info);
  3120. Types.push_back(New);
  3121. FunctionNoProtoTypes.InsertNode(New, InsertPos);
  3122. return QualType(New, 0);
  3123. }
  3124. CanQualType
  3125. ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
  3126. CanQualType CanResultType = getCanonicalType(ResultType);
  3127. // Canonical result types do not have ARC lifetime qualifiers.
  3128. if (CanResultType.getQualifiers().hasObjCLifetime()) {
  3129. Qualifiers Qs = CanResultType.getQualifiers();
  3130. Qs.removeObjCLifetime();
  3131. return CanQualType::CreateUnsafe(
  3132. getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
  3133. }
  3134. return CanResultType;
  3135. }
  3136. static bool isCanonicalExceptionSpecification(
  3137. const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
  3138. if (ESI.Type == EST_None)
  3139. return true;
  3140. if (!NoexceptInType)
  3141. return false;
  3142. // C++17 onwards: exception specification is part of the type, as a simple
  3143. // boolean "can this function type throw".
  3144. if (ESI.Type == EST_BasicNoexcept)
  3145. return true;
  3146. // A noexcept(expr) specification is (possibly) canonical if expr is
  3147. // value-dependent.
  3148. if (ESI.Type == EST_DependentNoexcept)
  3149. return true;
  3150. // A dynamic exception specification is canonical if it only contains pack
  3151. // expansions (so we can't tell whether it's non-throwing) and all its
  3152. // contained types are canonical.
  3153. if (ESI.Type == EST_Dynamic) {
  3154. bool AnyPackExpansions = false;
  3155. for (QualType ET : ESI.Exceptions) {
  3156. if (!ET.isCanonical())
  3157. return false;
  3158. if (ET->getAs<PackExpansionType>())
  3159. AnyPackExpansions = true;
  3160. }
  3161. return AnyPackExpansions;
  3162. }
  3163. return false;
  3164. }
  3165. QualType ASTContext::getFunctionTypeInternal(
  3166. QualType ResultTy, ArrayRef<QualType> ArgArray,
  3167. const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
  3168. size_t NumArgs = ArgArray.size();
  3169. // Unique functions, to guarantee there is only one function of a particular
  3170. // structure.
  3171. llvm::FoldingSetNodeID ID;
  3172. FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
  3173. *this, true);
  3174. QualType Canonical;
  3175. bool Unique = false;
  3176. void *InsertPos = nullptr;
  3177. if (FunctionProtoType *FPT =
  3178. FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
  3179. QualType Existing = QualType(FPT, 0);
  3180. // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
  3181. // it so long as our exception specification doesn't contain a dependent
  3182. // noexcept expression, or we're just looking for a canonical type.
  3183. // Otherwise, we're going to need to create a type
  3184. // sugar node to hold the concrete expression.
  3185. if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
  3186. EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
  3187. return Existing;
  3188. // We need a new type sugar node for this one, to hold the new noexcept
  3189. // expression. We do no canonicalization here, but that's OK since we don't
  3190. // expect to see the same noexcept expression much more than once.
  3191. Canonical = getCanonicalType(Existing);
  3192. Unique = true;
  3193. }
  3194. bool NoexceptInType = getLangOpts().CPlusPlus17;
  3195. bool IsCanonicalExceptionSpec =
  3196. isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
  3197. // Determine whether the type being created is already canonical or not.
  3198. bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
  3199. isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
  3200. for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
  3201. if (!ArgArray[i].isCanonicalAsParam())
  3202. isCanonical = false;
  3203. if (OnlyWantCanonical)
  3204. assert(isCanonical &&
  3205. "given non-canonical parameters constructing canonical type");
  3206. // If this type isn't canonical, get the canonical version of it if we don't
  3207. // already have it. The exception spec is only partially part of the
  3208. // canonical type, and only in C++17 onwards.
  3209. if (!isCanonical && Canonical.isNull()) {
  3210. SmallVector<QualType, 16> CanonicalArgs;
  3211. CanonicalArgs.reserve(NumArgs);
  3212. for (unsigned i = 0; i != NumArgs; ++i)
  3213. CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
  3214. llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
  3215. FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
  3216. CanonicalEPI.HasTrailingReturn = false;
  3217. if (IsCanonicalExceptionSpec) {
  3218. // Exception spec is already OK.
  3219. } else if (NoexceptInType) {
  3220. switch (EPI.ExceptionSpec.Type) {
  3221. case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
  3222. // We don't know yet. It shouldn't matter what we pick here; no-one
  3223. // should ever look at this.
  3224. LLVM_FALLTHROUGH;
  3225. case EST_None: case EST_MSAny: case EST_NoexceptFalse:
  3226. CanonicalEPI.ExceptionSpec.Type = EST_None;
  3227. break;
  3228. // A dynamic exception specification is almost always "not noexcept",
  3229. // with the exception that a pack expansion might expand to no types.
  3230. case EST_Dynamic: {
  3231. bool AnyPacks = false;
  3232. for (QualType ET : EPI.ExceptionSpec.Exceptions) {
  3233. if (ET->getAs<PackExpansionType>())
  3234. AnyPacks = true;
  3235. ExceptionTypeStorage.push_back(getCanonicalType(ET));
  3236. }
  3237. if (!AnyPacks)
  3238. CanonicalEPI.ExceptionSpec.Type = EST_None;
  3239. else {
  3240. CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
  3241. CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
  3242. }
  3243. break;
  3244. }
  3245. case EST_DynamicNone: case EST_BasicNoexcept: case EST_NoexceptTrue:
  3246. CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
  3247. break;
  3248. case EST_DependentNoexcept:
  3249. llvm_unreachable("dependent noexcept is already canonical");
  3250. }
  3251. } else {
  3252. CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
  3253. }
  3254. // Adjust the canonical function result type.
  3255. CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
  3256. Canonical =
  3257. getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
  3258. // Get the new insert position for the node we care about.
  3259. FunctionProtoType *NewIP =
  3260. FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
  3261. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3262. }
  3263. // Compute the needed size to hold this FunctionProtoType and the
  3264. // various trailing objects.
  3265. auto ESH = FunctionProtoType::getExceptionSpecSize(
  3266. EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
  3267. size_t Size = FunctionProtoType::totalSizeToAlloc<
  3268. QualType, FunctionType::FunctionTypeExtraBitfields,
  3269. FunctionType::ExceptionType, Expr *, FunctionDecl *,
  3270. FunctionProtoType::ExtParameterInfo, Qualifiers>(
  3271. NumArgs, FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
  3272. ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
  3273. EPI.ExtParameterInfos ? NumArgs : 0,
  3274. EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
  3275. auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
  3276. FunctionProtoType::ExtProtoInfo newEPI = EPI;
  3277. new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
  3278. Types.push_back(FTP);
  3279. if (!Unique)
  3280. FunctionProtoTypes.InsertNode(FTP, InsertPos);
  3281. return QualType(FTP, 0);
  3282. }
  3283. QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
  3284. llvm::FoldingSetNodeID ID;
  3285. PipeType::Profile(ID, T, ReadOnly);
  3286. void *InsertPos = nullptr;
  3287. if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
  3288. return QualType(PT, 0);
  3289. // If the pipe element type isn't canonical, this won't be a canonical type
  3290. // either, so fill in the canonical type field.
  3291. QualType Canonical;
  3292. if (!T.isCanonical()) {
  3293. Canonical = getPipeType(getCanonicalType(T), ReadOnly);
  3294. // Get the new insert position for the node we care about.
  3295. PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
  3296. assert(!NewIP && "Shouldn't be in the map!");
  3297. (void)NewIP;
  3298. }
  3299. auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
  3300. Types.push_back(New);
  3301. PipeTypes.InsertNode(New, InsertPos);
  3302. return QualType(New, 0);
  3303. }
  3304. QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
  3305. // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
  3306. return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
  3307. : Ty;
  3308. }
  3309. QualType ASTContext::getReadPipeType(QualType T) const {
  3310. return getPipeType(T, true);
  3311. }
  3312. QualType ASTContext::getWritePipeType(QualType T) const {
  3313. return getPipeType(T, false);
  3314. }
  3315. #ifndef NDEBUG
  3316. static bool NeedsInjectedClassNameType(const RecordDecl *D) {
  3317. if (!isa<CXXRecordDecl>(D)) return false;
  3318. const auto *RD = cast<CXXRecordDecl>(D);
  3319. if (isa<ClassTemplatePartialSpecializationDecl>(RD))
  3320. return true;
  3321. if (RD->getDescribedClassTemplate() &&
  3322. !isa<ClassTemplateSpecializationDecl>(RD))
  3323. return true;
  3324. return false;
  3325. }
  3326. #endif
  3327. /// getInjectedClassNameType - Return the unique reference to the
  3328. /// injected class name type for the specified templated declaration.
  3329. QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
  3330. QualType TST) const {
  3331. assert(NeedsInjectedClassNameType(Decl));
  3332. if (Decl->TypeForDecl) {
  3333. assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
  3334. } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
  3335. assert(PrevDecl->TypeForDecl && "previous declaration has no type");
  3336. Decl->TypeForDecl = PrevDecl->TypeForDecl;
  3337. assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
  3338. } else {
  3339. Type *newType =
  3340. new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
  3341. Decl->TypeForDecl = newType;
  3342. Types.push_back(newType);
  3343. }
  3344. return QualType(Decl->TypeForDecl, 0);
  3345. }
  3346. /// getTypeDeclType - Return the unique reference to the type for the
  3347. /// specified type declaration.
  3348. QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
  3349. assert(Decl && "Passed null for Decl param");
  3350. assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
  3351. if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
  3352. return getTypedefType(Typedef);
  3353. assert(!isa<TemplateTypeParmDecl>(Decl) &&
  3354. "Template type parameter types are always available.");
  3355. if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
  3356. assert(Record->isFirstDecl() && "struct/union has previous declaration");
  3357. assert(!NeedsInjectedClassNameType(Record));
  3358. return getRecordType(Record);
  3359. } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
  3360. assert(Enum->isFirstDecl() && "enum has previous declaration");
  3361. return getEnumType(Enum);
  3362. } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
  3363. Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
  3364. Decl->TypeForDecl = newType;
  3365. Types.push_back(newType);
  3366. } else
  3367. llvm_unreachable("TypeDecl without a type?");
  3368. return QualType(Decl->TypeForDecl, 0);
  3369. }
  3370. /// getTypedefType - Return the unique reference to the type for the
  3371. /// specified typedef name decl.
  3372. QualType
  3373. ASTContext::getTypedefType(const TypedefNameDecl *Decl,
  3374. QualType Canonical) const {
  3375. if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
  3376. if (Canonical.isNull())
  3377. Canonical = getCanonicalType(Decl->getUnderlyingType());
  3378. auto *newType = new (*this, TypeAlignment)
  3379. TypedefType(Type::Typedef, Decl, Canonical);
  3380. Decl->TypeForDecl = newType;
  3381. Types.push_back(newType);
  3382. return QualType(newType, 0);
  3383. }
  3384. QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
  3385. if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
  3386. if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
  3387. if (PrevDecl->TypeForDecl)
  3388. return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
  3389. auto *newType = new (*this, TypeAlignment) RecordType(Decl);
  3390. Decl->TypeForDecl = newType;
  3391. Types.push_back(newType);
  3392. return QualType(newType, 0);
  3393. }
  3394. QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
  3395. if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
  3396. if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
  3397. if (PrevDecl->TypeForDecl)
  3398. return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
  3399. auto *newType = new (*this, TypeAlignment) EnumType(Decl);
  3400. Decl->TypeForDecl = newType;
  3401. Types.push_back(newType);
  3402. return QualType(newType, 0);
  3403. }
  3404. QualType ASTContext::getAttributedType(attr::Kind attrKind,
  3405. QualType modifiedType,
  3406. QualType equivalentType) {
  3407. llvm::FoldingSetNodeID id;
  3408. AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
  3409. void *insertPos = nullptr;
  3410. AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
  3411. if (type) return QualType(type, 0);
  3412. QualType canon = getCanonicalType(equivalentType);
  3413. type = new (*this, TypeAlignment)
  3414. AttributedType(canon, attrKind, modifiedType, equivalentType);
  3415. Types.push_back(type);
  3416. AttributedTypes.InsertNode(type, insertPos);
  3417. return QualType(type, 0);
  3418. }
  3419. /// Retrieve a substitution-result type.
  3420. QualType
  3421. ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
  3422. QualType Replacement) const {
  3423. assert(Replacement.isCanonical()
  3424. && "replacement types must always be canonical");
  3425. llvm::FoldingSetNodeID ID;
  3426. SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
  3427. void *InsertPos = nullptr;
  3428. SubstTemplateTypeParmType *SubstParm
  3429. = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
  3430. if (!SubstParm) {
  3431. SubstParm = new (*this, TypeAlignment)
  3432. SubstTemplateTypeParmType(Parm, Replacement);
  3433. Types.push_back(SubstParm);
  3434. SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
  3435. }
  3436. return QualType(SubstParm, 0);
  3437. }
  3438. /// Retrieve a
  3439. QualType ASTContext::getSubstTemplateTypeParmPackType(
  3440. const TemplateTypeParmType *Parm,
  3441. const TemplateArgument &ArgPack) {
  3442. #ifndef NDEBUG
  3443. for (const auto &P : ArgPack.pack_elements()) {
  3444. assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
  3445. assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
  3446. }
  3447. #endif
  3448. llvm::FoldingSetNodeID ID;
  3449. SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
  3450. void *InsertPos = nullptr;
  3451. if (SubstTemplateTypeParmPackType *SubstParm
  3452. = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
  3453. return QualType(SubstParm, 0);
  3454. QualType Canon;
  3455. if (!Parm->isCanonicalUnqualified()) {
  3456. Canon = getCanonicalType(QualType(Parm, 0));
  3457. Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
  3458. ArgPack);
  3459. SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
  3460. }
  3461. auto *SubstParm
  3462. = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
  3463. ArgPack);
  3464. Types.push_back(SubstParm);
  3465. SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
  3466. return QualType(SubstParm, 0);
  3467. }
  3468. /// Retrieve the template type parameter type for a template
  3469. /// parameter or parameter pack with the given depth, index, and (optionally)
  3470. /// name.
  3471. QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
  3472. bool ParameterPack,
  3473. TemplateTypeParmDecl *TTPDecl) const {
  3474. llvm::FoldingSetNodeID ID;
  3475. TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
  3476. void *InsertPos = nullptr;
  3477. TemplateTypeParmType *TypeParm
  3478. = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
  3479. if (TypeParm)
  3480. return QualType(TypeParm, 0);
  3481. if (TTPDecl) {
  3482. QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
  3483. TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
  3484. TemplateTypeParmType *TypeCheck
  3485. = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
  3486. assert(!TypeCheck && "Template type parameter canonical type broken");
  3487. (void)TypeCheck;
  3488. } else
  3489. TypeParm = new (*this, TypeAlignment)
  3490. TemplateTypeParmType(Depth, Index, ParameterPack);
  3491. Types.push_back(TypeParm);
  3492. TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
  3493. return QualType(TypeParm, 0);
  3494. }
  3495. TypeSourceInfo *
  3496. ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
  3497. SourceLocation NameLoc,
  3498. const TemplateArgumentListInfo &Args,
  3499. QualType Underlying) const {
  3500. assert(!Name.getAsDependentTemplateName() &&
  3501. "No dependent template names here!");
  3502. QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
  3503. TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
  3504. TemplateSpecializationTypeLoc TL =
  3505. DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
  3506. TL.setTemplateKeywordLoc(SourceLocation());
  3507. TL.setTemplateNameLoc(NameLoc);
  3508. TL.setLAngleLoc(Args.getLAngleLoc());
  3509. TL.setRAngleLoc(Args.getRAngleLoc());
  3510. for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
  3511. TL.setArgLocInfo(i, Args[i].getLocInfo());
  3512. return DI;
  3513. }
  3514. QualType
  3515. ASTContext::getTemplateSpecializationType(TemplateName Template,
  3516. const TemplateArgumentListInfo &Args,
  3517. QualType Underlying) const {
  3518. assert(!Template.getAsDependentTemplateName() &&
  3519. "No dependent template names here!");
  3520. SmallVector<TemplateArgument, 4> ArgVec;
  3521. ArgVec.reserve(Args.size());
  3522. for (const TemplateArgumentLoc &Arg : Args.arguments())
  3523. ArgVec.push_back(Arg.getArgument());
  3524. return getTemplateSpecializationType(Template, ArgVec, Underlying);
  3525. }
  3526. #ifndef NDEBUG
  3527. static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
  3528. for (const TemplateArgument &Arg : Args)
  3529. if (Arg.isPackExpansion())
  3530. return true;
  3531. return true;
  3532. }
  3533. #endif
  3534. QualType
  3535. ASTContext::getTemplateSpecializationType(TemplateName Template,
  3536. ArrayRef<TemplateArgument> Args,
  3537. QualType Underlying) const {
  3538. assert(!Template.getAsDependentTemplateName() &&
  3539. "No dependent template names here!");
  3540. // Look through qualified template names.
  3541. if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
  3542. Template = TemplateName(QTN->getTemplateDecl());
  3543. bool IsTypeAlias =
  3544. Template.getAsTemplateDecl() &&
  3545. isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
  3546. QualType CanonType;
  3547. if (!Underlying.isNull())
  3548. CanonType = getCanonicalType(Underlying);
  3549. else {
  3550. // We can get here with an alias template when the specialization contains
  3551. // a pack expansion that does not match up with a parameter pack.
  3552. assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
  3553. "Caller must compute aliased type");
  3554. IsTypeAlias = false;
  3555. CanonType = getCanonicalTemplateSpecializationType(Template, Args);
  3556. }
  3557. // Allocate the (non-canonical) template specialization type, but don't
  3558. // try to unique it: these types typically have location information that
  3559. // we don't unique and don't want to lose.
  3560. void *Mem = Allocate(sizeof(TemplateSpecializationType) +
  3561. sizeof(TemplateArgument) * Args.size() +
  3562. (IsTypeAlias? sizeof(QualType) : 0),
  3563. TypeAlignment);
  3564. auto *Spec
  3565. = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
  3566. IsTypeAlias ? Underlying : QualType());
  3567. Types.push_back(Spec);
  3568. return QualType(Spec, 0);
  3569. }
  3570. QualType ASTContext::getCanonicalTemplateSpecializationType(
  3571. TemplateName Template, ArrayRef<TemplateArgument> Args) const {
  3572. assert(!Template.getAsDependentTemplateName() &&
  3573. "No dependent template names here!");
  3574. // Look through qualified template names.
  3575. if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
  3576. Template = TemplateName(QTN->getTemplateDecl());
  3577. // Build the canonical template specialization type.
  3578. TemplateName CanonTemplate = getCanonicalTemplateName(Template);
  3579. SmallVector<TemplateArgument, 4> CanonArgs;
  3580. unsigned NumArgs = Args.size();
  3581. CanonArgs.reserve(NumArgs);
  3582. for (const TemplateArgument &Arg : Args)
  3583. CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
  3584. // Determine whether this canonical template specialization type already
  3585. // exists.
  3586. llvm::FoldingSetNodeID ID;
  3587. TemplateSpecializationType::Profile(ID, CanonTemplate,
  3588. CanonArgs, *this);
  3589. void *InsertPos = nullptr;
  3590. TemplateSpecializationType *Spec
  3591. = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
  3592. if (!Spec) {
  3593. // Allocate a new canonical template specialization type.
  3594. void *Mem = Allocate((sizeof(TemplateSpecializationType) +
  3595. sizeof(TemplateArgument) * NumArgs),
  3596. TypeAlignment);
  3597. Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
  3598. CanonArgs,
  3599. QualType(), QualType());
  3600. Types.push_back(Spec);
  3601. TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
  3602. }
  3603. assert(Spec->isDependentType() &&
  3604. "Non-dependent template-id type must have a canonical type");
  3605. return QualType(Spec, 0);
  3606. }
  3607. QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
  3608. NestedNameSpecifier *NNS,
  3609. QualType NamedType,
  3610. TagDecl *OwnedTagDecl) const {
  3611. llvm::FoldingSetNodeID ID;
  3612. ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
  3613. void *InsertPos = nullptr;
  3614. ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
  3615. if (T)
  3616. return QualType(T, 0);
  3617. QualType Canon = NamedType;
  3618. if (!Canon.isCanonical()) {
  3619. Canon = getCanonicalType(NamedType);
  3620. ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
  3621. assert(!CheckT && "Elaborated canonical type broken");
  3622. (void)CheckT;
  3623. }
  3624. void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
  3625. TypeAlignment);
  3626. T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
  3627. Types.push_back(T);
  3628. ElaboratedTypes.InsertNode(T, InsertPos);
  3629. return QualType(T, 0);
  3630. }
  3631. QualType
  3632. ASTContext::getParenType(QualType InnerType) const {
  3633. llvm::FoldingSetNodeID ID;
  3634. ParenType::Profile(ID, InnerType);
  3635. void *InsertPos = nullptr;
  3636. ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
  3637. if (T)
  3638. return QualType(T, 0);
  3639. QualType Canon = InnerType;
  3640. if (!Canon.isCanonical()) {
  3641. Canon = getCanonicalType(InnerType);
  3642. ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
  3643. assert(!CheckT && "Paren canonical type broken");
  3644. (void)CheckT;
  3645. }
  3646. T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
  3647. Types.push_back(T);
  3648. ParenTypes.InsertNode(T, InsertPos);
  3649. return QualType(T, 0);
  3650. }
  3651. QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
  3652. NestedNameSpecifier *NNS,
  3653. const IdentifierInfo *Name,
  3654. QualType Canon) const {
  3655. if (Canon.isNull()) {
  3656. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  3657. if (CanonNNS != NNS)
  3658. Canon = getDependentNameType(Keyword, CanonNNS, Name);
  3659. }
  3660. llvm::FoldingSetNodeID ID;
  3661. DependentNameType::Profile(ID, Keyword, NNS, Name);
  3662. void *InsertPos = nullptr;
  3663. DependentNameType *T
  3664. = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
  3665. if (T)
  3666. return QualType(T, 0);
  3667. T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
  3668. Types.push_back(T);
  3669. DependentNameTypes.InsertNode(T, InsertPos);
  3670. return QualType(T, 0);
  3671. }
  3672. QualType
  3673. ASTContext::getDependentTemplateSpecializationType(
  3674. ElaboratedTypeKeyword Keyword,
  3675. NestedNameSpecifier *NNS,
  3676. const IdentifierInfo *Name,
  3677. const TemplateArgumentListInfo &Args) const {
  3678. // TODO: avoid this copy
  3679. SmallVector<TemplateArgument, 16> ArgCopy;
  3680. for (unsigned I = 0, E = Args.size(); I != E; ++I)
  3681. ArgCopy.push_back(Args[I].getArgument());
  3682. return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
  3683. }
  3684. QualType
  3685. ASTContext::getDependentTemplateSpecializationType(
  3686. ElaboratedTypeKeyword Keyword,
  3687. NestedNameSpecifier *NNS,
  3688. const IdentifierInfo *Name,
  3689. ArrayRef<TemplateArgument> Args) const {
  3690. assert((!NNS || NNS->isDependent()) &&
  3691. "nested-name-specifier must be dependent");
  3692. llvm::FoldingSetNodeID ID;
  3693. DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
  3694. Name, Args);
  3695. void *InsertPos = nullptr;
  3696. DependentTemplateSpecializationType *T
  3697. = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
  3698. if (T)
  3699. return QualType(T, 0);
  3700. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  3701. ElaboratedTypeKeyword CanonKeyword = Keyword;
  3702. if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
  3703. bool AnyNonCanonArgs = false;
  3704. unsigned NumArgs = Args.size();
  3705. SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
  3706. for (unsigned I = 0; I != NumArgs; ++I) {
  3707. CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
  3708. if (!CanonArgs[I].structurallyEquals(Args[I]))
  3709. AnyNonCanonArgs = true;
  3710. }
  3711. QualType Canon;
  3712. if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
  3713. Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
  3714. Name,
  3715. CanonArgs);
  3716. // Find the insert position again.
  3717. DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
  3718. }
  3719. void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
  3720. sizeof(TemplateArgument) * NumArgs),
  3721. TypeAlignment);
  3722. T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
  3723. Name, Args, Canon);
  3724. Types.push_back(T);
  3725. DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
  3726. return QualType(T, 0);
  3727. }
  3728. TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
  3729. TemplateArgument Arg;
  3730. if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
  3731. QualType ArgType = getTypeDeclType(TTP);
  3732. if (TTP->isParameterPack())
  3733. ArgType = getPackExpansionType(ArgType, None);
  3734. Arg = TemplateArgument(ArgType);
  3735. } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  3736. Expr *E = new (*this) DeclRefExpr(
  3737. *this, NTTP, /*enclosing*/ false,
  3738. NTTP->getType().getNonLValueExprType(*this),
  3739. Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
  3740. if (NTTP->isParameterPack())
  3741. E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
  3742. None);
  3743. Arg = TemplateArgument(E);
  3744. } else {
  3745. auto *TTP = cast<TemplateTemplateParmDecl>(Param);
  3746. if (TTP->isParameterPack())
  3747. Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
  3748. else
  3749. Arg = TemplateArgument(TemplateName(TTP));
  3750. }
  3751. if (Param->isTemplateParameterPack())
  3752. Arg = TemplateArgument::CreatePackCopy(*this, Arg);
  3753. return Arg;
  3754. }
  3755. void
  3756. ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
  3757. SmallVectorImpl<TemplateArgument> &Args) {
  3758. Args.reserve(Args.size() + Params->size());
  3759. for (NamedDecl *Param : *Params)
  3760. Args.push_back(getInjectedTemplateArg(Param));
  3761. }
  3762. QualType ASTContext::getPackExpansionType(QualType Pattern,
  3763. Optional<unsigned> NumExpansions) {
  3764. llvm::FoldingSetNodeID ID;
  3765. PackExpansionType::Profile(ID, Pattern, NumExpansions);
  3766. assert(Pattern->containsUnexpandedParameterPack() &&
  3767. "Pack expansions must expand one or more parameter packs");
  3768. void *InsertPos = nullptr;
  3769. PackExpansionType *T
  3770. = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
  3771. if (T)
  3772. return QualType(T, 0);
  3773. QualType Canon;
  3774. if (!Pattern.isCanonical()) {
  3775. Canon = getCanonicalType(Pattern);
  3776. // The canonical type might not contain an unexpanded parameter pack, if it
  3777. // contains an alias template specialization which ignores one of its
  3778. // parameters.
  3779. if (Canon->containsUnexpandedParameterPack()) {
  3780. Canon = getPackExpansionType(Canon, NumExpansions);
  3781. // Find the insert position again, in case we inserted an element into
  3782. // PackExpansionTypes and invalidated our insert position.
  3783. PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
  3784. }
  3785. }
  3786. T = new (*this, TypeAlignment)
  3787. PackExpansionType(Pattern, Canon, NumExpansions);
  3788. Types.push_back(T);
  3789. PackExpansionTypes.InsertNode(T, InsertPos);
  3790. return QualType(T, 0);
  3791. }
  3792. /// CmpProtocolNames - Comparison predicate for sorting protocols
  3793. /// alphabetically.
  3794. static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
  3795. ObjCProtocolDecl *const *RHS) {
  3796. return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
  3797. }
  3798. static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
  3799. if (Protocols.empty()) return true;
  3800. if (Protocols[0]->getCanonicalDecl() != Protocols[0])
  3801. return false;
  3802. for (unsigned i = 1; i != Protocols.size(); ++i)
  3803. if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
  3804. Protocols[i]->getCanonicalDecl() != Protocols[i])
  3805. return false;
  3806. return true;
  3807. }
  3808. static void
  3809. SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
  3810. // Sort protocols, keyed by name.
  3811. llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
  3812. // Canonicalize.
  3813. for (ObjCProtocolDecl *&P : Protocols)
  3814. P = P->getCanonicalDecl();
  3815. // Remove duplicates.
  3816. auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
  3817. Protocols.erase(ProtocolsEnd, Protocols.end());
  3818. }
  3819. QualType ASTContext::getObjCObjectType(QualType BaseType,
  3820. ObjCProtocolDecl * const *Protocols,
  3821. unsigned NumProtocols) const {
  3822. return getObjCObjectType(BaseType, {},
  3823. llvm::makeArrayRef(Protocols, NumProtocols),
  3824. /*isKindOf=*/false);
  3825. }
  3826. QualType ASTContext::getObjCObjectType(
  3827. QualType baseType,
  3828. ArrayRef<QualType> typeArgs,
  3829. ArrayRef<ObjCProtocolDecl *> protocols,
  3830. bool isKindOf) const {
  3831. // If the base type is an interface and there aren't any protocols or
  3832. // type arguments to add, then the interface type will do just fine.
  3833. if (typeArgs.empty() && protocols.empty() && !isKindOf &&
  3834. isa<ObjCInterfaceType>(baseType))
  3835. return baseType;
  3836. // Look in the folding set for an existing type.
  3837. llvm::FoldingSetNodeID ID;
  3838. ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
  3839. void *InsertPos = nullptr;
  3840. if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
  3841. return QualType(QT, 0);
  3842. // Determine the type arguments to be used for canonicalization,
  3843. // which may be explicitly specified here or written on the base
  3844. // type.
  3845. ArrayRef<QualType> effectiveTypeArgs = typeArgs;
  3846. if (effectiveTypeArgs.empty()) {
  3847. if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
  3848. effectiveTypeArgs = baseObject->getTypeArgs();
  3849. }
  3850. // Build the canonical type, which has the canonical base type and a
  3851. // sorted-and-uniqued list of protocols and the type arguments
  3852. // canonicalized.
  3853. QualType canonical;
  3854. bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
  3855. effectiveTypeArgs.end(),
  3856. [&](QualType type) {
  3857. return type.isCanonical();
  3858. });
  3859. bool protocolsSorted = areSortedAndUniqued(protocols);
  3860. if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
  3861. // Determine the canonical type arguments.
  3862. ArrayRef<QualType> canonTypeArgs;
  3863. SmallVector<QualType, 4> canonTypeArgsVec;
  3864. if (!typeArgsAreCanonical) {
  3865. canonTypeArgsVec.reserve(effectiveTypeArgs.size());
  3866. for (auto typeArg : effectiveTypeArgs)
  3867. canonTypeArgsVec.push_back(getCanonicalType(typeArg));
  3868. canonTypeArgs = canonTypeArgsVec;
  3869. } else {
  3870. canonTypeArgs = effectiveTypeArgs;
  3871. }
  3872. ArrayRef<ObjCProtocolDecl *> canonProtocols;
  3873. SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
  3874. if (!protocolsSorted) {
  3875. canonProtocolsVec.append(protocols.begin(), protocols.end());
  3876. SortAndUniqueProtocols(canonProtocolsVec);
  3877. canonProtocols = canonProtocolsVec;
  3878. } else {
  3879. canonProtocols = protocols;
  3880. }
  3881. canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
  3882. canonProtocols, isKindOf);
  3883. // Regenerate InsertPos.
  3884. ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
  3885. }
  3886. unsigned size = sizeof(ObjCObjectTypeImpl);
  3887. size += typeArgs.size() * sizeof(QualType);
  3888. size += protocols.size() * sizeof(ObjCProtocolDecl *);
  3889. void *mem = Allocate(size, TypeAlignment);
  3890. auto *T =
  3891. new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
  3892. isKindOf);
  3893. Types.push_back(T);
  3894. ObjCObjectTypes.InsertNode(T, InsertPos);
  3895. return QualType(T, 0);
  3896. }
  3897. /// Apply Objective-C protocol qualifiers to the given type.
  3898. /// If this is for the canonical type of a type parameter, we can apply
  3899. /// protocol qualifiers on the ObjCObjectPointerType.
  3900. QualType
  3901. ASTContext::applyObjCProtocolQualifiers(QualType type,
  3902. ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
  3903. bool allowOnPointerType) const {
  3904. hasError = false;
  3905. if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
  3906. return getObjCTypeParamType(objT->getDecl(), protocols);
  3907. }
  3908. // Apply protocol qualifiers to ObjCObjectPointerType.
  3909. if (allowOnPointerType) {
  3910. if (const auto *objPtr =
  3911. dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
  3912. const ObjCObjectType *objT = objPtr->getObjectType();
  3913. // Merge protocol lists and construct ObjCObjectType.
  3914. SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
  3915. protocolsVec.append(objT->qual_begin(),
  3916. objT->qual_end());
  3917. protocolsVec.append(protocols.begin(), protocols.end());
  3918. ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
  3919. type = getObjCObjectType(
  3920. objT->getBaseType(),
  3921. objT->getTypeArgsAsWritten(),
  3922. protocols,
  3923. objT->isKindOfTypeAsWritten());
  3924. return getObjCObjectPointerType(type);
  3925. }
  3926. }
  3927. // Apply protocol qualifiers to ObjCObjectType.
  3928. if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
  3929. // FIXME: Check for protocols to which the class type is already
  3930. // known to conform.
  3931. return getObjCObjectType(objT->getBaseType(),
  3932. objT->getTypeArgsAsWritten(),
  3933. protocols,
  3934. objT->isKindOfTypeAsWritten());
  3935. }
  3936. // If the canonical type is ObjCObjectType, ...
  3937. if (type->isObjCObjectType()) {
  3938. // Silently overwrite any existing protocol qualifiers.
  3939. // TODO: determine whether that's the right thing to do.
  3940. // FIXME: Check for protocols to which the class type is already
  3941. // known to conform.
  3942. return getObjCObjectType(type, {}, protocols, false);
  3943. }
  3944. // id<protocol-list>
  3945. if (type->isObjCIdType()) {
  3946. const auto *objPtr = type->castAs<ObjCObjectPointerType>();
  3947. type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
  3948. objPtr->isKindOfType());
  3949. return getObjCObjectPointerType(type);
  3950. }
  3951. // Class<protocol-list>
  3952. if (type->isObjCClassType()) {
  3953. const auto *objPtr = type->castAs<ObjCObjectPointerType>();
  3954. type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
  3955. objPtr->isKindOfType());
  3956. return getObjCObjectPointerType(type);
  3957. }
  3958. hasError = true;
  3959. return type;
  3960. }
  3961. QualType
  3962. ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
  3963. ArrayRef<ObjCProtocolDecl *> protocols,
  3964. QualType Canonical) const {
  3965. // Look in the folding set for an existing type.
  3966. llvm::FoldingSetNodeID ID;
  3967. ObjCTypeParamType::Profile(ID, Decl, protocols);
  3968. void *InsertPos = nullptr;
  3969. if (ObjCTypeParamType *TypeParam =
  3970. ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
  3971. return QualType(TypeParam, 0);
  3972. if (Canonical.isNull()) {
  3973. // We canonicalize to the underlying type.
  3974. Canonical = getCanonicalType(Decl->getUnderlyingType());
  3975. if (!protocols.empty()) {
  3976. // Apply the protocol qualifers.
  3977. bool hasError;
  3978. Canonical = getCanonicalType(applyObjCProtocolQualifiers(
  3979. Canonical, protocols, hasError, true /*allowOnPointerType*/));
  3980. assert(!hasError && "Error when apply protocol qualifier to bound type");
  3981. }
  3982. }
  3983. unsigned size = sizeof(ObjCTypeParamType);
  3984. size += protocols.size() * sizeof(ObjCProtocolDecl *);
  3985. void *mem = Allocate(size, TypeAlignment);
  3986. auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
  3987. Types.push_back(newType);
  3988. ObjCTypeParamTypes.InsertNode(newType, InsertPos);
  3989. return QualType(newType, 0);
  3990. }
  3991. /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
  3992. /// protocol list adopt all protocols in QT's qualified-id protocol
  3993. /// list.
  3994. bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
  3995. ObjCInterfaceDecl *IC) {
  3996. if (!QT->isObjCQualifiedIdType())
  3997. return false;
  3998. if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
  3999. // If both the right and left sides have qualifiers.
  4000. for (auto *Proto : OPT->quals()) {
  4001. if (!IC->ClassImplementsProtocol(Proto, false))
  4002. return false;
  4003. }
  4004. return true;
  4005. }
  4006. return false;
  4007. }
  4008. /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
  4009. /// QT's qualified-id protocol list adopt all protocols in IDecl's list
  4010. /// of protocols.
  4011. bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
  4012. ObjCInterfaceDecl *IDecl) {
  4013. if (!QT->isObjCQualifiedIdType())
  4014. return false;
  4015. const auto *OPT = QT->getAs<ObjCObjectPointerType>();
  4016. if (!OPT)
  4017. return false;
  4018. if (!IDecl->hasDefinition())
  4019. return false;
  4020. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
  4021. CollectInheritedProtocols(IDecl, InheritedProtocols);
  4022. if (InheritedProtocols.empty())
  4023. return false;
  4024. // Check that if every protocol in list of id<plist> conforms to a protocol
  4025. // of IDecl's, then bridge casting is ok.
  4026. bool Conforms = false;
  4027. for (auto *Proto : OPT->quals()) {
  4028. Conforms = false;
  4029. for (auto *PI : InheritedProtocols) {
  4030. if (ProtocolCompatibleWithProtocol(Proto, PI)) {
  4031. Conforms = true;
  4032. break;
  4033. }
  4034. }
  4035. if (!Conforms)
  4036. break;
  4037. }
  4038. if (Conforms)
  4039. return true;
  4040. for (auto *PI : InheritedProtocols) {
  4041. // If both the right and left sides have qualifiers.
  4042. bool Adopts = false;
  4043. for (auto *Proto : OPT->quals()) {
  4044. // return 'true' if 'PI' is in the inheritance hierarchy of Proto
  4045. if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
  4046. break;
  4047. }
  4048. if (!Adopts)
  4049. return false;
  4050. }
  4051. return true;
  4052. }
  4053. /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
  4054. /// the given object type.
  4055. QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
  4056. llvm::FoldingSetNodeID ID;
  4057. ObjCObjectPointerType::Profile(ID, ObjectT);
  4058. void *InsertPos = nullptr;
  4059. if (ObjCObjectPointerType *QT =
  4060. ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  4061. return QualType(QT, 0);
  4062. // Find the canonical object type.
  4063. QualType Canonical;
  4064. if (!ObjectT.isCanonical()) {
  4065. Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
  4066. // Regenerate InsertPos.
  4067. ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  4068. }
  4069. // No match.
  4070. void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
  4071. auto *QType =
  4072. new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
  4073. Types.push_back(QType);
  4074. ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
  4075. return QualType(QType, 0);
  4076. }
  4077. /// getObjCInterfaceType - Return the unique reference to the type for the
  4078. /// specified ObjC interface decl. The list of protocols is optional.
  4079. QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
  4080. ObjCInterfaceDecl *PrevDecl) const {
  4081. if (Decl->TypeForDecl)
  4082. return QualType(Decl->TypeForDecl, 0);
  4083. if (PrevDecl) {
  4084. assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
  4085. Decl->TypeForDecl = PrevDecl->TypeForDecl;
  4086. return QualType(PrevDecl->TypeForDecl, 0);
  4087. }
  4088. // Prefer the definition, if there is one.
  4089. if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
  4090. Decl = Def;
  4091. void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
  4092. auto *T = new (Mem) ObjCInterfaceType(Decl);
  4093. Decl->TypeForDecl = T;
  4094. Types.push_back(T);
  4095. return QualType(T, 0);
  4096. }
  4097. /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
  4098. /// TypeOfExprType AST's (since expression's are never shared). For example,
  4099. /// multiple declarations that refer to "typeof(x)" all contain different
  4100. /// DeclRefExpr's. This doesn't effect the type checker, since it operates
  4101. /// on canonical type's (which are always unique).
  4102. QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
  4103. TypeOfExprType *toe;
  4104. if (tofExpr->isTypeDependent()) {
  4105. llvm::FoldingSetNodeID ID;
  4106. DependentTypeOfExprType::Profile(ID, *this, tofExpr);
  4107. void *InsertPos = nullptr;
  4108. DependentTypeOfExprType *Canon
  4109. = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
  4110. if (Canon) {
  4111. // We already have a "canonical" version of an identical, dependent
  4112. // typeof(expr) type. Use that as our canonical type.
  4113. toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
  4114. QualType((TypeOfExprType*)Canon, 0));
  4115. } else {
  4116. // Build a new, canonical typeof(expr) type.
  4117. Canon
  4118. = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
  4119. DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
  4120. toe = Canon;
  4121. }
  4122. } else {
  4123. QualType Canonical = getCanonicalType(tofExpr->getType());
  4124. toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
  4125. }
  4126. Types.push_back(toe);
  4127. return QualType(toe, 0);
  4128. }
  4129. /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
  4130. /// TypeOfType nodes. The only motivation to unique these nodes would be
  4131. /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
  4132. /// an issue. This doesn't affect the type checker, since it operates
  4133. /// on canonical types (which are always unique).
  4134. QualType ASTContext::getTypeOfType(QualType tofType) const {
  4135. QualType Canonical = getCanonicalType(tofType);
  4136. auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
  4137. Types.push_back(tot);
  4138. return QualType(tot, 0);
  4139. }
  4140. /// Unlike many "get<Type>" functions, we don't unique DecltypeType
  4141. /// nodes. This would never be helpful, since each such type has its own
  4142. /// expression, and would not give a significant memory saving, since there
  4143. /// is an Expr tree under each such type.
  4144. QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
  4145. DecltypeType *dt;
  4146. // C++11 [temp.type]p2:
  4147. // If an expression e involves a template parameter, decltype(e) denotes a
  4148. // unique dependent type. Two such decltype-specifiers refer to the same
  4149. // type only if their expressions are equivalent (14.5.6.1).
  4150. if (e->isInstantiationDependent()) {
  4151. llvm::FoldingSetNodeID ID;
  4152. DependentDecltypeType::Profile(ID, *this, e);
  4153. void *InsertPos = nullptr;
  4154. DependentDecltypeType *Canon
  4155. = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
  4156. if (!Canon) {
  4157. // Build a new, canonical decltype(expr) type.
  4158. Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
  4159. DependentDecltypeTypes.InsertNode(Canon, InsertPos);
  4160. }
  4161. dt = new (*this, TypeAlignment)
  4162. DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
  4163. } else {
  4164. dt = new (*this, TypeAlignment)
  4165. DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
  4166. }
  4167. Types.push_back(dt);
  4168. return QualType(dt, 0);
  4169. }
  4170. /// getUnaryTransformationType - We don't unique these, since the memory
  4171. /// savings are minimal and these are rare.
  4172. QualType ASTContext::getUnaryTransformType(QualType BaseType,
  4173. QualType UnderlyingType,
  4174. UnaryTransformType::UTTKind Kind)
  4175. const {
  4176. UnaryTransformType *ut = nullptr;
  4177. if (BaseType->isDependentType()) {
  4178. // Look in the folding set for an existing type.
  4179. llvm::FoldingSetNodeID ID;
  4180. DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
  4181. void *InsertPos = nullptr;
  4182. DependentUnaryTransformType *Canon
  4183. = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
  4184. if (!Canon) {
  4185. // Build a new, canonical __underlying_type(type) type.
  4186. Canon = new (*this, TypeAlignment)
  4187. DependentUnaryTransformType(*this, getCanonicalType(BaseType),
  4188. Kind);
  4189. DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
  4190. }
  4191. ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
  4192. QualType(), Kind,
  4193. QualType(Canon, 0));
  4194. } else {
  4195. QualType CanonType = getCanonicalType(UnderlyingType);
  4196. ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
  4197. UnderlyingType, Kind,
  4198. CanonType);
  4199. }
  4200. Types.push_back(ut);
  4201. return QualType(ut, 0);
  4202. }
  4203. /// getAutoType - Return the uniqued reference to the 'auto' type which has been
  4204. /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
  4205. /// canonical deduced-but-dependent 'auto' type.
  4206. QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
  4207. bool IsDependent) const {
  4208. if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
  4209. return getAutoDeductType();
  4210. // Look in the folding set for an existing type.
  4211. void *InsertPos = nullptr;
  4212. llvm::FoldingSetNodeID ID;
  4213. AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
  4214. if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
  4215. return QualType(AT, 0);
  4216. auto *AT = new (*this, TypeAlignment)
  4217. AutoType(DeducedType, Keyword, IsDependent);
  4218. Types.push_back(AT);
  4219. if (InsertPos)
  4220. AutoTypes.InsertNode(AT, InsertPos);
  4221. return QualType(AT, 0);
  4222. }
  4223. /// Return the uniqued reference to the deduced template specialization type
  4224. /// which has been deduced to the given type, or to the canonical undeduced
  4225. /// such type, or the canonical deduced-but-dependent such type.
  4226. QualType ASTContext::getDeducedTemplateSpecializationType(
  4227. TemplateName Template, QualType DeducedType, bool IsDependent) const {
  4228. // Look in the folding set for an existing type.
  4229. void *InsertPos = nullptr;
  4230. llvm::FoldingSetNodeID ID;
  4231. DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
  4232. IsDependent);
  4233. if (DeducedTemplateSpecializationType *DTST =
  4234. DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
  4235. return QualType(DTST, 0);
  4236. auto *DTST = new (*this, TypeAlignment)
  4237. DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
  4238. Types.push_back(DTST);
  4239. if (InsertPos)
  4240. DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
  4241. return QualType(DTST, 0);
  4242. }
  4243. /// getAtomicType - Return the uniqued reference to the atomic type for
  4244. /// the given value type.
  4245. QualType ASTContext::getAtomicType(QualType T) const {
  4246. // Unique pointers, to guarantee there is only one pointer of a particular
  4247. // structure.
  4248. llvm::FoldingSetNodeID ID;
  4249. AtomicType::Profile(ID, T);
  4250. void *InsertPos = nullptr;
  4251. if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
  4252. return QualType(AT, 0);
  4253. // If the atomic value type isn't canonical, this won't be a canonical type
  4254. // either, so fill in the canonical type field.
  4255. QualType Canonical;
  4256. if (!T.isCanonical()) {
  4257. Canonical = getAtomicType(getCanonicalType(T));
  4258. // Get the new insert position for the node we care about.
  4259. AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
  4260. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  4261. }
  4262. auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
  4263. Types.push_back(New);
  4264. AtomicTypes.InsertNode(New, InsertPos);
  4265. return QualType(New, 0);
  4266. }
  4267. /// getAutoDeductType - Get type pattern for deducing against 'auto'.
  4268. QualType ASTContext::getAutoDeductType() const {
  4269. if (AutoDeductTy.isNull())
  4270. AutoDeductTy = QualType(
  4271. new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
  4272. /*dependent*/false),
  4273. 0);
  4274. return AutoDeductTy;
  4275. }
  4276. /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
  4277. QualType ASTContext::getAutoRRefDeductType() const {
  4278. if (AutoRRefDeductTy.isNull())
  4279. AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
  4280. assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
  4281. return AutoRRefDeductTy;
  4282. }
  4283. /// getTagDeclType - Return the unique reference to the type for the
  4284. /// specified TagDecl (struct/union/class/enum) decl.
  4285. QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
  4286. assert(Decl);
  4287. // FIXME: What is the design on getTagDeclType when it requires casting
  4288. // away const? mutable?
  4289. return getTypeDeclType(const_cast<TagDecl*>(Decl));
  4290. }
  4291. /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
  4292. /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
  4293. /// needs to agree with the definition in <stddef.h>.
  4294. CanQualType ASTContext::getSizeType() const {
  4295. return getFromTargetType(Target->getSizeType());
  4296. }
  4297. /// Return the unique signed counterpart of the integer type
  4298. /// corresponding to size_t.
  4299. CanQualType ASTContext::getSignedSizeType() const {
  4300. return getFromTargetType(Target->getSignedSizeType());
  4301. }
  4302. /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
  4303. CanQualType ASTContext::getIntMaxType() const {
  4304. return getFromTargetType(Target->getIntMaxType());
  4305. }
  4306. /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
  4307. CanQualType ASTContext::getUIntMaxType() const {
  4308. return getFromTargetType(Target->getUIntMaxType());
  4309. }
  4310. /// getSignedWCharType - Return the type of "signed wchar_t".
  4311. /// Used when in C++, as a GCC extension.
  4312. QualType ASTContext::getSignedWCharType() const {
  4313. // FIXME: derive from "Target" ?
  4314. return WCharTy;
  4315. }
  4316. /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
  4317. /// Used when in C++, as a GCC extension.
  4318. QualType ASTContext::getUnsignedWCharType() const {
  4319. // FIXME: derive from "Target" ?
  4320. return UnsignedIntTy;
  4321. }
  4322. QualType ASTContext::getIntPtrType() const {
  4323. return getFromTargetType(Target->getIntPtrType());
  4324. }
  4325. QualType ASTContext::getUIntPtrType() const {
  4326. return getCorrespondingUnsignedType(getIntPtrType());
  4327. }
  4328. /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
  4329. /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
  4330. QualType ASTContext::getPointerDiffType() const {
  4331. return getFromTargetType(Target->getPtrDiffType(0));
  4332. }
  4333. /// Return the unique unsigned counterpart of "ptrdiff_t"
  4334. /// integer type. The standard (C11 7.21.6.1p7) refers to this type
  4335. /// in the definition of %tu format specifier.
  4336. QualType ASTContext::getUnsignedPointerDiffType() const {
  4337. return getFromTargetType(Target->getUnsignedPtrDiffType(0));
  4338. }
  4339. /// Return the unique type for "pid_t" defined in
  4340. /// <sys/types.h>. We need this to compute the correct type for vfork().
  4341. QualType ASTContext::getProcessIDType() const {
  4342. return getFromTargetType(Target->getProcessIDType());
  4343. }
  4344. //===----------------------------------------------------------------------===//
  4345. // Type Operators
  4346. //===----------------------------------------------------------------------===//
  4347. CanQualType ASTContext::getCanonicalParamType(QualType T) const {
  4348. // Push qualifiers into arrays, and then discard any remaining
  4349. // qualifiers.
  4350. T = getCanonicalType(T);
  4351. T = getVariableArrayDecayedType(T);
  4352. const Type *Ty = T.getTypePtr();
  4353. QualType Result;
  4354. if (isa<ArrayType>(Ty)) {
  4355. Result = getArrayDecayedType(QualType(Ty,0));
  4356. } else if (isa<FunctionType>(Ty)) {
  4357. Result = getPointerType(QualType(Ty, 0));
  4358. } else {
  4359. Result = QualType(Ty, 0);
  4360. }
  4361. return CanQualType::CreateUnsafe(Result);
  4362. }
  4363. QualType ASTContext::getUnqualifiedArrayType(QualType type,
  4364. Qualifiers &quals) {
  4365. SplitQualType splitType = type.getSplitUnqualifiedType();
  4366. // FIXME: getSplitUnqualifiedType() actually walks all the way to
  4367. // the unqualified desugared type and then drops it on the floor.
  4368. // We then have to strip that sugar back off with
  4369. // getUnqualifiedDesugaredType(), which is silly.
  4370. const auto *AT =
  4371. dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
  4372. // If we don't have an array, just use the results in splitType.
  4373. if (!AT) {
  4374. quals = splitType.Quals;
  4375. return QualType(splitType.Ty, 0);
  4376. }
  4377. // Otherwise, recurse on the array's element type.
  4378. QualType elementType = AT->getElementType();
  4379. QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
  4380. // If that didn't change the element type, AT has no qualifiers, so we
  4381. // can just use the results in splitType.
  4382. if (elementType == unqualElementType) {
  4383. assert(quals.empty()); // from the recursive call
  4384. quals = splitType.Quals;
  4385. return QualType(splitType.Ty, 0);
  4386. }
  4387. // Otherwise, add in the qualifiers from the outermost type, then
  4388. // build the type back up.
  4389. quals.addConsistentQualifiers(splitType.Quals);
  4390. if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  4391. return getConstantArrayType(unqualElementType, CAT->getSize(),
  4392. CAT->getSizeModifier(), 0);
  4393. }
  4394. if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
  4395. return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
  4396. }
  4397. if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
  4398. return getVariableArrayType(unqualElementType,
  4399. VAT->getSizeExpr(),
  4400. VAT->getSizeModifier(),
  4401. VAT->getIndexTypeCVRQualifiers(),
  4402. VAT->getBracketsRange());
  4403. }
  4404. const auto *DSAT = cast<DependentSizedArrayType>(AT);
  4405. return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
  4406. DSAT->getSizeModifier(), 0,
  4407. SourceRange());
  4408. }
  4409. /// Attempt to unwrap two types that may both be array types with the same bound
  4410. /// (or both be array types of unknown bound) for the purpose of comparing the
  4411. /// cv-decomposition of two types per C++ [conv.qual].
  4412. bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
  4413. bool UnwrappedAny = false;
  4414. while (true) {
  4415. auto *AT1 = getAsArrayType(T1);
  4416. if (!AT1) return UnwrappedAny;
  4417. auto *AT2 = getAsArrayType(T2);
  4418. if (!AT2) return UnwrappedAny;
  4419. // If we don't have two array types with the same constant bound nor two
  4420. // incomplete array types, we've unwrapped everything we can.
  4421. if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
  4422. auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
  4423. if (!CAT2 || CAT1->getSize() != CAT2->getSize())
  4424. return UnwrappedAny;
  4425. } else if (!isa<IncompleteArrayType>(AT1) ||
  4426. !isa<IncompleteArrayType>(AT2)) {
  4427. return UnwrappedAny;
  4428. }
  4429. T1 = AT1->getElementType();
  4430. T2 = AT2->getElementType();
  4431. UnwrappedAny = true;
  4432. }
  4433. }
  4434. /// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
  4435. ///
  4436. /// If T1 and T2 are both pointer types of the same kind, or both array types
  4437. /// with the same bound, unwraps layers from T1 and T2 until a pointer type is
  4438. /// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
  4439. ///
  4440. /// This function will typically be called in a loop that successively
  4441. /// "unwraps" pointer and pointer-to-member types to compare them at each
  4442. /// level.
  4443. ///
  4444. /// \return \c true if a pointer type was unwrapped, \c false if we reached a
  4445. /// pair of types that can't be unwrapped further.
  4446. bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
  4447. UnwrapSimilarArrayTypes(T1, T2);
  4448. const auto *T1PtrType = T1->getAs<PointerType>();
  4449. const auto *T2PtrType = T2->getAs<PointerType>();
  4450. if (T1PtrType && T2PtrType) {
  4451. T1 = T1PtrType->getPointeeType();
  4452. T2 = T2PtrType->getPointeeType();
  4453. return true;
  4454. }
  4455. const auto *T1MPType = T1->getAs<MemberPointerType>();
  4456. const auto *T2MPType = T2->getAs<MemberPointerType>();
  4457. if (T1MPType && T2MPType &&
  4458. hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
  4459. QualType(T2MPType->getClass(), 0))) {
  4460. T1 = T1MPType->getPointeeType();
  4461. T2 = T2MPType->getPointeeType();
  4462. return true;
  4463. }
  4464. if (getLangOpts().ObjC) {
  4465. const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
  4466. const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
  4467. if (T1OPType && T2OPType) {
  4468. T1 = T1OPType->getPointeeType();
  4469. T2 = T2OPType->getPointeeType();
  4470. return true;
  4471. }
  4472. }
  4473. // FIXME: Block pointers, too?
  4474. return false;
  4475. }
  4476. bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
  4477. while (true) {
  4478. Qualifiers Quals;
  4479. T1 = getUnqualifiedArrayType(T1, Quals);
  4480. T2 = getUnqualifiedArrayType(T2, Quals);
  4481. if (hasSameType(T1, T2))
  4482. return true;
  4483. if (!UnwrapSimilarTypes(T1, T2))
  4484. return false;
  4485. }
  4486. }
  4487. bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
  4488. while (true) {
  4489. Qualifiers Quals1, Quals2;
  4490. T1 = getUnqualifiedArrayType(T1, Quals1);
  4491. T2 = getUnqualifiedArrayType(T2, Quals2);
  4492. Quals1.removeCVRQualifiers();
  4493. Quals2.removeCVRQualifiers();
  4494. if (Quals1 != Quals2)
  4495. return false;
  4496. if (hasSameType(T1, T2))
  4497. return true;
  4498. if (!UnwrapSimilarTypes(T1, T2))
  4499. return false;
  4500. }
  4501. }
  4502. DeclarationNameInfo
  4503. ASTContext::getNameForTemplate(TemplateName Name,
  4504. SourceLocation NameLoc) const {
  4505. switch (Name.getKind()) {
  4506. case TemplateName::QualifiedTemplate:
  4507. case TemplateName::Template:
  4508. // DNInfo work in progress: CHECKME: what about DNLoc?
  4509. return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
  4510. NameLoc);
  4511. case TemplateName::OverloadedTemplate: {
  4512. OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
  4513. // DNInfo work in progress: CHECKME: what about DNLoc?
  4514. return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
  4515. }
  4516. case TemplateName::DependentTemplate: {
  4517. DependentTemplateName *DTN = Name.getAsDependentTemplateName();
  4518. DeclarationName DName;
  4519. if (DTN->isIdentifier()) {
  4520. DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
  4521. return DeclarationNameInfo(DName, NameLoc);
  4522. } else {
  4523. DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
  4524. // DNInfo work in progress: FIXME: source locations?
  4525. DeclarationNameLoc DNLoc;
  4526. DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
  4527. DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
  4528. return DeclarationNameInfo(DName, NameLoc, DNLoc);
  4529. }
  4530. }
  4531. case TemplateName::SubstTemplateTemplateParm: {
  4532. SubstTemplateTemplateParmStorage *subst
  4533. = Name.getAsSubstTemplateTemplateParm();
  4534. return DeclarationNameInfo(subst->getParameter()->getDeclName(),
  4535. NameLoc);
  4536. }
  4537. case TemplateName::SubstTemplateTemplateParmPack: {
  4538. SubstTemplateTemplateParmPackStorage *subst
  4539. = Name.getAsSubstTemplateTemplateParmPack();
  4540. return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
  4541. NameLoc);
  4542. }
  4543. }
  4544. llvm_unreachable("bad template name kind!");
  4545. }
  4546. TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
  4547. switch (Name.getKind()) {
  4548. case TemplateName::QualifiedTemplate:
  4549. case TemplateName::Template: {
  4550. TemplateDecl *Template = Name.getAsTemplateDecl();
  4551. if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
  4552. Template = getCanonicalTemplateTemplateParmDecl(TTP);
  4553. // The canonical template name is the canonical template declaration.
  4554. return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
  4555. }
  4556. case TemplateName::OverloadedTemplate:
  4557. llvm_unreachable("cannot canonicalize overloaded template");
  4558. case TemplateName::DependentTemplate: {
  4559. DependentTemplateName *DTN = Name.getAsDependentTemplateName();
  4560. assert(DTN && "Non-dependent template names must refer to template decls.");
  4561. return DTN->CanonicalTemplateName;
  4562. }
  4563. case TemplateName::SubstTemplateTemplateParm: {
  4564. SubstTemplateTemplateParmStorage *subst
  4565. = Name.getAsSubstTemplateTemplateParm();
  4566. return getCanonicalTemplateName(subst->getReplacement());
  4567. }
  4568. case TemplateName::SubstTemplateTemplateParmPack: {
  4569. SubstTemplateTemplateParmPackStorage *subst
  4570. = Name.getAsSubstTemplateTemplateParmPack();
  4571. TemplateTemplateParmDecl *canonParameter
  4572. = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
  4573. TemplateArgument canonArgPack
  4574. = getCanonicalTemplateArgument(subst->getArgumentPack());
  4575. return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
  4576. }
  4577. }
  4578. llvm_unreachable("bad template name!");
  4579. }
  4580. bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
  4581. X = getCanonicalTemplateName(X);
  4582. Y = getCanonicalTemplateName(Y);
  4583. return X.getAsVoidPointer() == Y.getAsVoidPointer();
  4584. }
  4585. TemplateArgument
  4586. ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
  4587. switch (Arg.getKind()) {
  4588. case TemplateArgument::Null:
  4589. return Arg;
  4590. case TemplateArgument::Expression:
  4591. return Arg;
  4592. case TemplateArgument::Declaration: {
  4593. auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
  4594. return TemplateArgument(D, Arg.getParamTypeForDecl());
  4595. }
  4596. case TemplateArgument::NullPtr:
  4597. return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
  4598. /*isNullPtr*/true);
  4599. case TemplateArgument::Template:
  4600. return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
  4601. case TemplateArgument::TemplateExpansion:
  4602. return TemplateArgument(getCanonicalTemplateName(
  4603. Arg.getAsTemplateOrTemplatePattern()),
  4604. Arg.getNumTemplateExpansions());
  4605. case TemplateArgument::Integral:
  4606. return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
  4607. case TemplateArgument::Type:
  4608. return TemplateArgument(getCanonicalType(Arg.getAsType()));
  4609. case TemplateArgument::Pack: {
  4610. if (Arg.pack_size() == 0)
  4611. return Arg;
  4612. auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
  4613. unsigned Idx = 0;
  4614. for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
  4615. AEnd = Arg.pack_end();
  4616. A != AEnd; (void)++A, ++Idx)
  4617. CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
  4618. return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
  4619. }
  4620. }
  4621. // Silence GCC warning
  4622. llvm_unreachable("Unhandled template argument kind");
  4623. }
  4624. NestedNameSpecifier *
  4625. ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
  4626. if (!NNS)
  4627. return nullptr;
  4628. switch (NNS->getKind()) {
  4629. case NestedNameSpecifier::Identifier:
  4630. // Canonicalize the prefix but keep the identifier the same.
  4631. return NestedNameSpecifier::Create(*this,
  4632. getCanonicalNestedNameSpecifier(NNS->getPrefix()),
  4633. NNS->getAsIdentifier());
  4634. case NestedNameSpecifier::Namespace:
  4635. // A namespace is canonical; build a nested-name-specifier with
  4636. // this namespace and no prefix.
  4637. return NestedNameSpecifier::Create(*this, nullptr,
  4638. NNS->getAsNamespace()->getOriginalNamespace());
  4639. case NestedNameSpecifier::NamespaceAlias:
  4640. // A namespace is canonical; build a nested-name-specifier with
  4641. // this namespace and no prefix.
  4642. return NestedNameSpecifier::Create(*this, nullptr,
  4643. NNS->getAsNamespaceAlias()->getNamespace()
  4644. ->getOriginalNamespace());
  4645. case NestedNameSpecifier::TypeSpec:
  4646. case NestedNameSpecifier::TypeSpecWithTemplate: {
  4647. QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
  4648. // If we have some kind of dependent-named type (e.g., "typename T::type"),
  4649. // break it apart into its prefix and identifier, then reconsititute those
  4650. // as the canonical nested-name-specifier. This is required to canonicalize
  4651. // a dependent nested-name-specifier involving typedefs of dependent-name
  4652. // types, e.g.,
  4653. // typedef typename T::type T1;
  4654. // typedef typename T1::type T2;
  4655. if (const auto *DNT = T->getAs<DependentNameType>())
  4656. return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
  4657. const_cast<IdentifierInfo *>(DNT->getIdentifier()));
  4658. // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
  4659. // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
  4660. // first place?
  4661. return NestedNameSpecifier::Create(*this, nullptr, false,
  4662. const_cast<Type *>(T.getTypePtr()));
  4663. }
  4664. case NestedNameSpecifier::Global:
  4665. case NestedNameSpecifier::Super:
  4666. // The global specifier and __super specifer are canonical and unique.
  4667. return NNS;
  4668. }
  4669. llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
  4670. }
  4671. const ArrayType *ASTContext::getAsArrayType(QualType T) const {
  4672. // Handle the non-qualified case efficiently.
  4673. if (!T.hasLocalQualifiers()) {
  4674. // Handle the common positive case fast.
  4675. if (const auto *AT = dyn_cast<ArrayType>(T))
  4676. return AT;
  4677. }
  4678. // Handle the common negative case fast.
  4679. if (!isa<ArrayType>(T.getCanonicalType()))
  4680. return nullptr;
  4681. // Apply any qualifiers from the array type to the element type. This
  4682. // implements C99 6.7.3p8: "If the specification of an array type includes
  4683. // any type qualifiers, the element type is so qualified, not the array type."
  4684. // If we get here, we either have type qualifiers on the type, or we have
  4685. // sugar such as a typedef in the way. If we have type qualifiers on the type
  4686. // we must propagate them down into the element type.
  4687. SplitQualType split = T.getSplitDesugaredType();
  4688. Qualifiers qs = split.Quals;
  4689. // If we have a simple case, just return now.
  4690. const auto *ATy = dyn_cast<ArrayType>(split.Ty);
  4691. if (!ATy || qs.empty())
  4692. return ATy;
  4693. // Otherwise, we have an array and we have qualifiers on it. Push the
  4694. // qualifiers into the array element type and return a new array type.
  4695. QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
  4696. if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
  4697. return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
  4698. CAT->getSizeModifier(),
  4699. CAT->getIndexTypeCVRQualifiers()));
  4700. if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
  4701. return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
  4702. IAT->getSizeModifier(),
  4703. IAT->getIndexTypeCVRQualifiers()));
  4704. if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
  4705. return cast<ArrayType>(
  4706. getDependentSizedArrayType(NewEltTy,
  4707. DSAT->getSizeExpr(),
  4708. DSAT->getSizeModifier(),
  4709. DSAT->getIndexTypeCVRQualifiers(),
  4710. DSAT->getBracketsRange()));
  4711. const auto *VAT = cast<VariableArrayType>(ATy);
  4712. return cast<ArrayType>(getVariableArrayType(NewEltTy,
  4713. VAT->getSizeExpr(),
  4714. VAT->getSizeModifier(),
  4715. VAT->getIndexTypeCVRQualifiers(),
  4716. VAT->getBracketsRange()));
  4717. }
  4718. QualType ASTContext::getAdjustedParameterType(QualType T) const {
  4719. if (T->isArrayType() || T->isFunctionType())
  4720. return getDecayedType(T);
  4721. return T;
  4722. }
  4723. QualType ASTContext::getSignatureParameterType(QualType T) const {
  4724. T = getVariableArrayDecayedType(T);
  4725. T = getAdjustedParameterType(T);
  4726. return T.getUnqualifiedType();
  4727. }
  4728. QualType ASTContext::getExceptionObjectType(QualType T) const {
  4729. // C++ [except.throw]p3:
  4730. // A throw-expression initializes a temporary object, called the exception
  4731. // object, the type of which is determined by removing any top-level
  4732. // cv-qualifiers from the static type of the operand of throw and adjusting
  4733. // the type from "array of T" or "function returning T" to "pointer to T"
  4734. // or "pointer to function returning T", [...]
  4735. T = getVariableArrayDecayedType(T);
  4736. if (T->isArrayType() || T->isFunctionType())
  4737. T = getDecayedType(T);
  4738. return T.getUnqualifiedType();
  4739. }
  4740. /// getArrayDecayedType - Return the properly qualified result of decaying the
  4741. /// specified array type to a pointer. This operation is non-trivial when
  4742. /// handling typedefs etc. The canonical type of "T" must be an array type,
  4743. /// this returns a pointer to a properly qualified element of the array.
  4744. ///
  4745. /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
  4746. QualType ASTContext::getArrayDecayedType(QualType Ty) const {
  4747. // Get the element type with 'getAsArrayType' so that we don't lose any
  4748. // typedefs in the element type of the array. This also handles propagation
  4749. // of type qualifiers from the array type into the element type if present
  4750. // (C99 6.7.3p8).
  4751. const ArrayType *PrettyArrayType = getAsArrayType(Ty);
  4752. assert(PrettyArrayType && "Not an array type!");
  4753. QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
  4754. // int x[restrict 4] -> int *restrict
  4755. QualType Result = getQualifiedType(PtrTy,
  4756. PrettyArrayType->getIndexTypeQualifiers());
  4757. // int x[_Nullable] -> int * _Nullable
  4758. if (auto Nullability = Ty->getNullability(*this)) {
  4759. Result = const_cast<ASTContext *>(this)->getAttributedType(
  4760. AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
  4761. }
  4762. return Result;
  4763. }
  4764. QualType ASTContext::getBaseElementType(const ArrayType *array) const {
  4765. return getBaseElementType(array->getElementType());
  4766. }
  4767. QualType ASTContext::getBaseElementType(QualType type) const {
  4768. Qualifiers qs;
  4769. while (true) {
  4770. SplitQualType split = type.getSplitDesugaredType();
  4771. const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
  4772. if (!array) break;
  4773. type = array->getElementType();
  4774. qs.addConsistentQualifiers(split.Quals);
  4775. }
  4776. return getQualifiedType(type, qs);
  4777. }
  4778. /// getConstantArrayElementCount - Returns number of constant array elements.
  4779. uint64_t
  4780. ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
  4781. uint64_t ElementCount = 1;
  4782. do {
  4783. ElementCount *= CA->getSize().getZExtValue();
  4784. CA = dyn_cast_or_null<ConstantArrayType>(
  4785. CA->getElementType()->getAsArrayTypeUnsafe());
  4786. } while (CA);
  4787. return ElementCount;
  4788. }
  4789. /// getFloatingRank - Return a relative rank for floating point types.
  4790. /// This routine will assert if passed a built-in type that isn't a float.
  4791. static FloatingRank getFloatingRank(QualType T) {
  4792. if (const auto *CT = T->getAs<ComplexType>())
  4793. return getFloatingRank(CT->getElementType());
  4794. assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
  4795. switch (T->getAs<BuiltinType>()->getKind()) {
  4796. default: llvm_unreachable("getFloatingRank(): not a floating type");
  4797. case BuiltinType::Float16: return Float16Rank;
  4798. case BuiltinType::Half: return HalfRank;
  4799. case BuiltinType::Float: return FloatRank;
  4800. case BuiltinType::Double: return DoubleRank;
  4801. case BuiltinType::LongDouble: return LongDoubleRank;
  4802. case BuiltinType::Float128: return Float128Rank;
  4803. }
  4804. }
  4805. /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
  4806. /// point or a complex type (based on typeDomain/typeSize).
  4807. /// 'typeDomain' is a real floating point or complex type.
  4808. /// 'typeSize' is a real floating point or complex type.
  4809. QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
  4810. QualType Domain) const {
  4811. FloatingRank EltRank = getFloatingRank(Size);
  4812. if (Domain->isComplexType()) {
  4813. switch (EltRank) {
  4814. case Float16Rank:
  4815. case HalfRank: llvm_unreachable("Complex half is not supported");
  4816. case FloatRank: return FloatComplexTy;
  4817. case DoubleRank: return DoubleComplexTy;
  4818. case LongDoubleRank: return LongDoubleComplexTy;
  4819. case Float128Rank: return Float128ComplexTy;
  4820. }
  4821. }
  4822. assert(Domain->isRealFloatingType() && "Unknown domain!");
  4823. switch (EltRank) {
  4824. case Float16Rank: return HalfTy;
  4825. case HalfRank: return HalfTy;
  4826. case FloatRank: return FloatTy;
  4827. case DoubleRank: return DoubleTy;
  4828. case LongDoubleRank: return LongDoubleTy;
  4829. case Float128Rank: return Float128Ty;
  4830. }
  4831. llvm_unreachable("getFloatingRank(): illegal value for rank");
  4832. }
  4833. /// getFloatingTypeOrder - Compare the rank of the two specified floating
  4834. /// point types, ignoring the domain of the type (i.e. 'double' ==
  4835. /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
  4836. /// LHS < RHS, return -1.
  4837. int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
  4838. FloatingRank LHSR = getFloatingRank(LHS);
  4839. FloatingRank RHSR = getFloatingRank(RHS);
  4840. if (LHSR == RHSR)
  4841. return 0;
  4842. if (LHSR > RHSR)
  4843. return 1;
  4844. return -1;
  4845. }
  4846. int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
  4847. if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
  4848. return 0;
  4849. return getFloatingTypeOrder(LHS, RHS);
  4850. }
  4851. /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
  4852. /// routine will assert if passed a built-in type that isn't an integer or enum,
  4853. /// or if it is not canonicalized.
  4854. unsigned ASTContext::getIntegerRank(const Type *T) const {
  4855. assert(T->isCanonicalUnqualified() && "T should be canonicalized");
  4856. switch (cast<BuiltinType>(T)->getKind()) {
  4857. default: llvm_unreachable("getIntegerRank(): not a built-in integer");
  4858. case BuiltinType::Bool:
  4859. return 1 + (getIntWidth(BoolTy) << 3);
  4860. case BuiltinType::Char_S:
  4861. case BuiltinType::Char_U:
  4862. case BuiltinType::SChar:
  4863. case BuiltinType::UChar:
  4864. return 2 + (getIntWidth(CharTy) << 3);
  4865. case BuiltinType::Short:
  4866. case BuiltinType::UShort:
  4867. return 3 + (getIntWidth(ShortTy) << 3);
  4868. case BuiltinType::Int:
  4869. case BuiltinType::UInt:
  4870. return 4 + (getIntWidth(IntTy) << 3);
  4871. case BuiltinType::Long:
  4872. case BuiltinType::ULong:
  4873. return 5 + (getIntWidth(LongTy) << 3);
  4874. case BuiltinType::LongLong:
  4875. case BuiltinType::ULongLong:
  4876. return 6 + (getIntWidth(LongLongTy) << 3);
  4877. case BuiltinType::Int128:
  4878. case BuiltinType::UInt128:
  4879. return 7 + (getIntWidth(Int128Ty) << 3);
  4880. }
  4881. }
  4882. /// Whether this is a promotable bitfield reference according
  4883. /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
  4884. ///
  4885. /// \returns the type this bit-field will promote to, or NULL if no
  4886. /// promotion occurs.
  4887. QualType ASTContext::isPromotableBitField(Expr *E) const {
  4888. if (E->isTypeDependent() || E->isValueDependent())
  4889. return {};
  4890. // C++ [conv.prom]p5:
  4891. // If the bit-field has an enumerated type, it is treated as any other
  4892. // value of that type for promotion purposes.
  4893. if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
  4894. return {};
  4895. // FIXME: We should not do this unless E->refersToBitField() is true. This
  4896. // matters in C where getSourceBitField() will find bit-fields for various
  4897. // cases where the source expression is not a bit-field designator.
  4898. FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
  4899. if (!Field)
  4900. return {};
  4901. QualType FT = Field->getType();
  4902. uint64_t BitWidth = Field->getBitWidthValue(*this);
  4903. uint64_t IntSize = getTypeSize(IntTy);
  4904. // C++ [conv.prom]p5:
  4905. // A prvalue for an integral bit-field can be converted to a prvalue of type
  4906. // int if int can represent all the values of the bit-field; otherwise, it
  4907. // can be converted to unsigned int if unsigned int can represent all the
  4908. // values of the bit-field. If the bit-field is larger yet, no integral
  4909. // promotion applies to it.
  4910. // C11 6.3.1.1/2:
  4911. // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
  4912. // If an int can represent all values of the original type (as restricted by
  4913. // the width, for a bit-field), the value is converted to an int; otherwise,
  4914. // it is converted to an unsigned int.
  4915. //
  4916. // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
  4917. // We perform that promotion here to match GCC and C++.
  4918. // FIXME: C does not permit promotion of an enum bit-field whose rank is
  4919. // greater than that of 'int'. We perform that promotion to match GCC.
  4920. if (BitWidth < IntSize)
  4921. return IntTy;
  4922. if (BitWidth == IntSize)
  4923. return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
  4924. // Bit-fields wider than int are not subject to promotions, and therefore act
  4925. // like the base type. GCC has some weird bugs in this area that we
  4926. // deliberately do not follow (GCC follows a pre-standard resolution to
  4927. // C's DR315 which treats bit-width as being part of the type, and this leaks
  4928. // into their semantics in some cases).
  4929. return {};
  4930. }
  4931. /// getPromotedIntegerType - Returns the type that Promotable will
  4932. /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
  4933. /// integer type.
  4934. QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
  4935. assert(!Promotable.isNull());
  4936. assert(Promotable->isPromotableIntegerType());
  4937. if (const auto *ET = Promotable->getAs<EnumType>())
  4938. return ET->getDecl()->getPromotionType();
  4939. if (const auto *BT = Promotable->getAs<BuiltinType>()) {
  4940. // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
  4941. // (3.9.1) can be converted to a prvalue of the first of the following
  4942. // types that can represent all the values of its underlying type:
  4943. // int, unsigned int, long int, unsigned long int, long long int, or
  4944. // unsigned long long int [...]
  4945. // FIXME: Is there some better way to compute this?
  4946. if (BT->getKind() == BuiltinType::WChar_S ||
  4947. BT->getKind() == BuiltinType::WChar_U ||
  4948. BT->getKind() == BuiltinType::Char8 ||
  4949. BT->getKind() == BuiltinType::Char16 ||
  4950. BT->getKind() == BuiltinType::Char32) {
  4951. bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
  4952. uint64_t FromSize = getTypeSize(BT);
  4953. QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
  4954. LongLongTy, UnsignedLongLongTy };
  4955. for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
  4956. uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
  4957. if (FromSize < ToSize ||
  4958. (FromSize == ToSize &&
  4959. FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
  4960. return PromoteTypes[Idx];
  4961. }
  4962. llvm_unreachable("char type should fit into long long");
  4963. }
  4964. }
  4965. // At this point, we should have a signed or unsigned integer type.
  4966. if (Promotable->isSignedIntegerType())
  4967. return IntTy;
  4968. uint64_t PromotableSize = getIntWidth(Promotable);
  4969. uint64_t IntSize = getIntWidth(IntTy);
  4970. assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
  4971. return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
  4972. }
  4973. /// Recurses in pointer/array types until it finds an objc retainable
  4974. /// type and returns its ownership.
  4975. Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
  4976. while (!T.isNull()) {
  4977. if (T.getObjCLifetime() != Qualifiers::OCL_None)
  4978. return T.getObjCLifetime();
  4979. if (T->isArrayType())
  4980. T = getBaseElementType(T);
  4981. else if (const auto *PT = T->getAs<PointerType>())
  4982. T = PT->getPointeeType();
  4983. else if (const auto *RT = T->getAs<ReferenceType>())
  4984. T = RT->getPointeeType();
  4985. else
  4986. break;
  4987. }
  4988. return Qualifiers::OCL_None;
  4989. }
  4990. static const Type *getIntegerTypeForEnum(const EnumType *ET) {
  4991. // Incomplete enum types are not treated as integer types.
  4992. // FIXME: In C++, enum types are never integer types.
  4993. if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
  4994. return ET->getDecl()->getIntegerType().getTypePtr();
  4995. return nullptr;
  4996. }
  4997. /// getIntegerTypeOrder - Returns the highest ranked integer type:
  4998. /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
  4999. /// LHS < RHS, return -1.
  5000. int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
  5001. const Type *LHSC = getCanonicalType(LHS).getTypePtr();
  5002. const Type *RHSC = getCanonicalType(RHS).getTypePtr();
  5003. // Unwrap enums to their underlying type.
  5004. if (const auto *ET = dyn_cast<EnumType>(LHSC))
  5005. LHSC = getIntegerTypeForEnum(ET);
  5006. if (const auto *ET = dyn_cast<EnumType>(RHSC))
  5007. RHSC = getIntegerTypeForEnum(ET);
  5008. if (LHSC == RHSC) return 0;
  5009. bool LHSUnsigned = LHSC->isUnsignedIntegerType();
  5010. bool RHSUnsigned = RHSC->isUnsignedIntegerType();
  5011. unsigned LHSRank = getIntegerRank(LHSC);
  5012. unsigned RHSRank = getIntegerRank(RHSC);
  5013. if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
  5014. if (LHSRank == RHSRank) return 0;
  5015. return LHSRank > RHSRank ? 1 : -1;
  5016. }
  5017. // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
  5018. if (LHSUnsigned) {
  5019. // If the unsigned [LHS] type is larger, return it.
  5020. if (LHSRank >= RHSRank)
  5021. return 1;
  5022. // If the signed type can represent all values of the unsigned type, it
  5023. // wins. Because we are dealing with 2's complement and types that are
  5024. // powers of two larger than each other, this is always safe.
  5025. return -1;
  5026. }
  5027. // If the unsigned [RHS] type is larger, return it.
  5028. if (RHSRank >= LHSRank)
  5029. return -1;
  5030. // If the signed type can represent all values of the unsigned type, it
  5031. // wins. Because we are dealing with 2's complement and types that are
  5032. // powers of two larger than each other, this is always safe.
  5033. return 1;
  5034. }
  5035. TypedefDecl *ASTContext::getCFConstantStringDecl() const {
  5036. if (CFConstantStringTypeDecl)
  5037. return CFConstantStringTypeDecl;
  5038. assert(!CFConstantStringTagDecl &&
  5039. "tag and typedef should be initialized together");
  5040. CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
  5041. CFConstantStringTagDecl->startDefinition();
  5042. struct {
  5043. QualType Type;
  5044. const char *Name;
  5045. } Fields[5];
  5046. unsigned Count = 0;
  5047. /// Objective-C ABI
  5048. ///
  5049. /// typedef struct __NSConstantString_tag {
  5050. /// const int *isa;
  5051. /// int flags;
  5052. /// const char *str;
  5053. /// long length;
  5054. /// } __NSConstantString;
  5055. ///
  5056. /// Swift ABI (4.1, 4.2)
  5057. ///
  5058. /// typedef struct __NSConstantString_tag {
  5059. /// uintptr_t _cfisa;
  5060. /// uintptr_t _swift_rc;
  5061. /// _Atomic(uint64_t) _cfinfoa;
  5062. /// const char *_ptr;
  5063. /// uint32_t _length;
  5064. /// } __NSConstantString;
  5065. ///
  5066. /// Swift ABI (5.0)
  5067. ///
  5068. /// typedef struct __NSConstantString_tag {
  5069. /// uintptr_t _cfisa;
  5070. /// uintptr_t _swift_rc;
  5071. /// _Atomic(uint64_t) _cfinfoa;
  5072. /// const char *_ptr;
  5073. /// uintptr_t _length;
  5074. /// } __NSConstantString;
  5075. const auto CFRuntime = getLangOpts().CFRuntime;
  5076. if (static_cast<unsigned>(CFRuntime) <
  5077. static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
  5078. Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
  5079. Fields[Count++] = { IntTy, "flags" };
  5080. Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
  5081. Fields[Count++] = { LongTy, "length" };
  5082. } else {
  5083. Fields[Count++] = { getUIntPtrType(), "_cfisa" };
  5084. Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
  5085. Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
  5086. Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
  5087. if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
  5088. CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
  5089. Fields[Count++] = { IntTy, "_ptr" };
  5090. else
  5091. Fields[Count++] = { getUIntPtrType(), "_ptr" };
  5092. }
  5093. // Create fields
  5094. for (unsigned i = 0; i < Count; ++i) {
  5095. FieldDecl *Field =
  5096. FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
  5097. SourceLocation(), &Idents.get(Fields[i].Name),
  5098. Fields[i].Type, /*TInfo=*/nullptr,
  5099. /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
  5100. Field->setAccess(AS_public);
  5101. CFConstantStringTagDecl->addDecl(Field);
  5102. }
  5103. CFConstantStringTagDecl->completeDefinition();
  5104. // This type is designed to be compatible with NSConstantString, but cannot
  5105. // use the same name, since NSConstantString is an interface.
  5106. auto tagType = getTagDeclType(CFConstantStringTagDecl);
  5107. CFConstantStringTypeDecl =
  5108. buildImplicitTypedef(tagType, "__NSConstantString");
  5109. return CFConstantStringTypeDecl;
  5110. }
  5111. RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
  5112. if (!CFConstantStringTagDecl)
  5113. getCFConstantStringDecl(); // Build the tag and the typedef.
  5114. return CFConstantStringTagDecl;
  5115. }
  5116. // getCFConstantStringType - Return the type used for constant CFStrings.
  5117. QualType ASTContext::getCFConstantStringType() const {
  5118. return getTypedefType(getCFConstantStringDecl());
  5119. }
  5120. QualType ASTContext::getObjCSuperType() const {
  5121. if (ObjCSuperType.isNull()) {
  5122. RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
  5123. TUDecl->addDecl(ObjCSuperTypeDecl);
  5124. ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
  5125. }
  5126. return ObjCSuperType;
  5127. }
  5128. void ASTContext::setCFConstantStringType(QualType T) {
  5129. const auto *TD = T->getAs<TypedefType>();
  5130. assert(TD && "Invalid CFConstantStringType");
  5131. CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
  5132. const auto *TagType =
  5133. CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
  5134. assert(TagType && "Invalid CFConstantStringType");
  5135. CFConstantStringTagDecl = TagType->getDecl();
  5136. }
  5137. QualType ASTContext::getBlockDescriptorType() const {
  5138. if (BlockDescriptorType)
  5139. return getTagDeclType(BlockDescriptorType);
  5140. RecordDecl *RD;
  5141. // FIXME: Needs the FlagAppleBlock bit.
  5142. RD = buildImplicitRecord("__block_descriptor");
  5143. RD->startDefinition();
  5144. QualType FieldTypes[] = {
  5145. UnsignedLongTy,
  5146. UnsignedLongTy,
  5147. };
  5148. static const char *const FieldNames[] = {
  5149. "reserved",
  5150. "Size"
  5151. };
  5152. for (size_t i = 0; i < 2; ++i) {
  5153. FieldDecl *Field = FieldDecl::Create(
  5154. *this, RD, SourceLocation(), SourceLocation(),
  5155. &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
  5156. /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
  5157. Field->setAccess(AS_public);
  5158. RD->addDecl(Field);
  5159. }
  5160. RD->completeDefinition();
  5161. BlockDescriptorType = RD;
  5162. return getTagDeclType(BlockDescriptorType);
  5163. }
  5164. QualType ASTContext::getBlockDescriptorExtendedType() const {
  5165. if (BlockDescriptorExtendedType)
  5166. return getTagDeclType(BlockDescriptorExtendedType);
  5167. RecordDecl *RD;
  5168. // FIXME: Needs the FlagAppleBlock bit.
  5169. RD = buildImplicitRecord("__block_descriptor_withcopydispose");
  5170. RD->startDefinition();
  5171. QualType FieldTypes[] = {
  5172. UnsignedLongTy,
  5173. UnsignedLongTy,
  5174. getPointerType(VoidPtrTy),
  5175. getPointerType(VoidPtrTy)
  5176. };
  5177. static const char *const FieldNames[] = {
  5178. "reserved",
  5179. "Size",
  5180. "CopyFuncPtr",
  5181. "DestroyFuncPtr"
  5182. };
  5183. for (size_t i = 0; i < 4; ++i) {
  5184. FieldDecl *Field = FieldDecl::Create(
  5185. *this, RD, SourceLocation(), SourceLocation(),
  5186. &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
  5187. /*BitWidth=*/nullptr,
  5188. /*Mutable=*/false, ICIS_NoInit);
  5189. Field->setAccess(AS_public);
  5190. RD->addDecl(Field);
  5191. }
  5192. RD->completeDefinition();
  5193. BlockDescriptorExtendedType = RD;
  5194. return getTagDeclType(BlockDescriptorExtendedType);
  5195. }
  5196. TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
  5197. const auto *BT = dyn_cast<BuiltinType>(T);
  5198. if (!BT) {
  5199. if (isa<PipeType>(T))
  5200. return TargetInfo::OCLTK_Pipe;
  5201. return TargetInfo::OCLTK_Default;
  5202. }
  5203. switch (BT->getKind()) {
  5204. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  5205. case BuiltinType::Id: \
  5206. return TargetInfo::OCLTK_Image;
  5207. #include "clang/Basic/OpenCLImageTypes.def"
  5208. case BuiltinType::OCLClkEvent:
  5209. return TargetInfo::OCLTK_ClkEvent;
  5210. case BuiltinType::OCLEvent:
  5211. return TargetInfo::OCLTK_Event;
  5212. case BuiltinType::OCLQueue:
  5213. return TargetInfo::OCLTK_Queue;
  5214. case BuiltinType::OCLReserveID:
  5215. return TargetInfo::OCLTK_ReserveID;
  5216. case BuiltinType::OCLSampler:
  5217. return TargetInfo::OCLTK_Sampler;
  5218. default:
  5219. return TargetInfo::OCLTK_Default;
  5220. }
  5221. }
  5222. LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
  5223. return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
  5224. }
  5225. /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
  5226. /// requires copy/dispose. Note that this must match the logic
  5227. /// in buildByrefHelpers.
  5228. bool ASTContext::BlockRequiresCopying(QualType Ty,
  5229. const VarDecl *D) {
  5230. if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
  5231. const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
  5232. if (!copyExpr && record->hasTrivialDestructor()) return false;
  5233. return true;
  5234. }
  5235. // The block needs copy/destroy helpers if Ty is non-trivial to destructively
  5236. // move or destroy.
  5237. if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
  5238. return true;
  5239. if (!Ty->isObjCRetainableType()) return false;
  5240. Qualifiers qs = Ty.getQualifiers();
  5241. // If we have lifetime, that dominates.
  5242. if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
  5243. switch (lifetime) {
  5244. case Qualifiers::OCL_None: llvm_unreachable("impossible");
  5245. // These are just bits as far as the runtime is concerned.
  5246. case Qualifiers::OCL_ExplicitNone:
  5247. case Qualifiers::OCL_Autoreleasing:
  5248. return false;
  5249. // These cases should have been taken care of when checking the type's
  5250. // non-triviality.
  5251. case Qualifiers::OCL_Weak:
  5252. case Qualifiers::OCL_Strong:
  5253. llvm_unreachable("impossible");
  5254. }
  5255. llvm_unreachable("fell out of lifetime switch!");
  5256. }
  5257. return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
  5258. Ty->isObjCObjectPointerType());
  5259. }
  5260. bool ASTContext::getByrefLifetime(QualType Ty,
  5261. Qualifiers::ObjCLifetime &LifeTime,
  5262. bool &HasByrefExtendedLayout) const {
  5263. if (!getLangOpts().ObjC ||
  5264. getLangOpts().getGC() != LangOptions::NonGC)
  5265. return false;
  5266. HasByrefExtendedLayout = false;
  5267. if (Ty->isRecordType()) {
  5268. HasByrefExtendedLayout = true;
  5269. LifeTime = Qualifiers::OCL_None;
  5270. } else if ((LifeTime = Ty.getObjCLifetime())) {
  5271. // Honor the ARC qualifiers.
  5272. } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
  5273. // The MRR rule.
  5274. LifeTime = Qualifiers::OCL_ExplicitNone;
  5275. } else {
  5276. LifeTime = Qualifiers::OCL_None;
  5277. }
  5278. return true;
  5279. }
  5280. TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
  5281. if (!ObjCInstanceTypeDecl)
  5282. ObjCInstanceTypeDecl =
  5283. buildImplicitTypedef(getObjCIdType(), "instancetype");
  5284. return ObjCInstanceTypeDecl;
  5285. }
  5286. // This returns true if a type has been typedefed to BOOL:
  5287. // typedef <type> BOOL;
  5288. static bool isTypeTypedefedAsBOOL(QualType T) {
  5289. if (const auto *TT = dyn_cast<TypedefType>(T))
  5290. if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
  5291. return II->isStr("BOOL");
  5292. return false;
  5293. }
  5294. /// getObjCEncodingTypeSize returns size of type for objective-c encoding
  5295. /// purpose.
  5296. CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
  5297. if (!type->isIncompleteArrayType() && type->isIncompleteType())
  5298. return CharUnits::Zero();
  5299. CharUnits sz = getTypeSizeInChars(type);
  5300. // Make all integer and enum types at least as large as an int
  5301. if (sz.isPositive() && type->isIntegralOrEnumerationType())
  5302. sz = std::max(sz, getTypeSizeInChars(IntTy));
  5303. // Treat arrays as pointers, since that's how they're passed in.
  5304. else if (type->isArrayType())
  5305. sz = getTypeSizeInChars(VoidPtrTy);
  5306. return sz;
  5307. }
  5308. bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
  5309. return getTargetInfo().getCXXABI().isMicrosoft() &&
  5310. VD->isStaticDataMember() &&
  5311. VD->getType()->isIntegralOrEnumerationType() &&
  5312. !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
  5313. }
  5314. ASTContext::InlineVariableDefinitionKind
  5315. ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
  5316. if (!VD->isInline())
  5317. return InlineVariableDefinitionKind::None;
  5318. // In almost all cases, it's a weak definition.
  5319. auto *First = VD->getFirstDecl();
  5320. if (First->isInlineSpecified() || !First->isStaticDataMember())
  5321. return InlineVariableDefinitionKind::Weak;
  5322. // If there's a file-context declaration in this translation unit, it's a
  5323. // non-discardable definition.
  5324. for (auto *D : VD->redecls())
  5325. if (D->getLexicalDeclContext()->isFileContext() &&
  5326. !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
  5327. return InlineVariableDefinitionKind::Strong;
  5328. // If we've not seen one yet, we don't know.
  5329. return InlineVariableDefinitionKind::WeakUnknown;
  5330. }
  5331. static std::string charUnitsToString(const CharUnits &CU) {
  5332. return llvm::itostr(CU.getQuantity());
  5333. }
  5334. /// getObjCEncodingForBlock - Return the encoded type for this block
  5335. /// declaration.
  5336. std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
  5337. std::string S;
  5338. const BlockDecl *Decl = Expr->getBlockDecl();
  5339. QualType BlockTy =
  5340. Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
  5341. // Encode result type.
  5342. if (getLangOpts().EncodeExtendedBlockSig)
  5343. getObjCEncodingForMethodParameter(
  5344. Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
  5345. true /*Extended*/);
  5346. else
  5347. getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
  5348. // Compute size of all parameters.
  5349. // Start with computing size of a pointer in number of bytes.
  5350. // FIXME: There might(should) be a better way of doing this computation!
  5351. CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
  5352. CharUnits ParmOffset = PtrSize;
  5353. for (auto PI : Decl->parameters()) {
  5354. QualType PType = PI->getType();
  5355. CharUnits sz = getObjCEncodingTypeSize(PType);
  5356. if (sz.isZero())
  5357. continue;
  5358. assert(sz.isPositive() && "BlockExpr - Incomplete param type");
  5359. ParmOffset += sz;
  5360. }
  5361. // Size of the argument frame
  5362. S += charUnitsToString(ParmOffset);
  5363. // Block pointer and offset.
  5364. S += "@?0";
  5365. // Argument types.
  5366. ParmOffset = PtrSize;
  5367. for (auto PVDecl : Decl->parameters()) {
  5368. QualType PType = PVDecl->getOriginalType();
  5369. if (const auto *AT =
  5370. dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
  5371. // Use array's original type only if it has known number of
  5372. // elements.
  5373. if (!isa<ConstantArrayType>(AT))
  5374. PType = PVDecl->getType();
  5375. } else if (PType->isFunctionType())
  5376. PType = PVDecl->getType();
  5377. if (getLangOpts().EncodeExtendedBlockSig)
  5378. getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
  5379. S, true /*Extended*/);
  5380. else
  5381. getObjCEncodingForType(PType, S);
  5382. S += charUnitsToString(ParmOffset);
  5383. ParmOffset += getObjCEncodingTypeSize(PType);
  5384. }
  5385. return S;
  5386. }
  5387. std::string
  5388. ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
  5389. std::string S;
  5390. // Encode result type.
  5391. getObjCEncodingForType(Decl->getReturnType(), S);
  5392. CharUnits ParmOffset;
  5393. // Compute size of all parameters.
  5394. for (auto PI : Decl->parameters()) {
  5395. QualType PType = PI->getType();
  5396. CharUnits sz = getObjCEncodingTypeSize(PType);
  5397. if (sz.isZero())
  5398. continue;
  5399. assert(sz.isPositive() &&
  5400. "getObjCEncodingForFunctionDecl - Incomplete param type");
  5401. ParmOffset += sz;
  5402. }
  5403. S += charUnitsToString(ParmOffset);
  5404. ParmOffset = CharUnits::Zero();
  5405. // Argument types.
  5406. for (auto PVDecl : Decl->parameters()) {
  5407. QualType PType = PVDecl->getOriginalType();
  5408. if (const auto *AT =
  5409. dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
  5410. // Use array's original type only if it has known number of
  5411. // elements.
  5412. if (!isa<ConstantArrayType>(AT))
  5413. PType = PVDecl->getType();
  5414. } else if (PType->isFunctionType())
  5415. PType = PVDecl->getType();
  5416. getObjCEncodingForType(PType, S);
  5417. S += charUnitsToString(ParmOffset);
  5418. ParmOffset += getObjCEncodingTypeSize(PType);
  5419. }
  5420. return S;
  5421. }
  5422. /// getObjCEncodingForMethodParameter - Return the encoded type for a single
  5423. /// method parameter or return type. If Extended, include class names and
  5424. /// block object types.
  5425. void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
  5426. QualType T, std::string& S,
  5427. bool Extended) const {
  5428. // Encode type qualifer, 'in', 'inout', etc. for the parameter.
  5429. getObjCEncodingForTypeQualifier(QT, S);
  5430. // Encode parameter type.
  5431. getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
  5432. true /*OutermostType*/,
  5433. false /*EncodingProperty*/,
  5434. false /*StructField*/,
  5435. Extended /*EncodeBlockParameters*/,
  5436. Extended /*EncodeClassNames*/);
  5437. }
  5438. /// getObjCEncodingForMethodDecl - Return the encoded type for this method
  5439. /// declaration.
  5440. std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
  5441. bool Extended) const {
  5442. // FIXME: This is not very efficient.
  5443. // Encode return type.
  5444. std::string S;
  5445. getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
  5446. Decl->getReturnType(), S, Extended);
  5447. // Compute size of all parameters.
  5448. // Start with computing size of a pointer in number of bytes.
  5449. // FIXME: There might(should) be a better way of doing this computation!
  5450. CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
  5451. // The first two arguments (self and _cmd) are pointers; account for
  5452. // their size.
  5453. CharUnits ParmOffset = 2 * PtrSize;
  5454. for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
  5455. E = Decl->sel_param_end(); PI != E; ++PI) {
  5456. QualType PType = (*PI)->getType();
  5457. CharUnits sz = getObjCEncodingTypeSize(PType);
  5458. if (sz.isZero())
  5459. continue;
  5460. assert(sz.isPositive() &&
  5461. "getObjCEncodingForMethodDecl - Incomplete param type");
  5462. ParmOffset += sz;
  5463. }
  5464. S += charUnitsToString(ParmOffset);
  5465. S += "@0:";
  5466. S += charUnitsToString(PtrSize);
  5467. // Argument types.
  5468. ParmOffset = 2 * PtrSize;
  5469. for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
  5470. E = Decl->sel_param_end(); PI != E; ++PI) {
  5471. const ParmVarDecl *PVDecl = *PI;
  5472. QualType PType = PVDecl->getOriginalType();
  5473. if (const auto *AT =
  5474. dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
  5475. // Use array's original type only if it has known number of
  5476. // elements.
  5477. if (!isa<ConstantArrayType>(AT))
  5478. PType = PVDecl->getType();
  5479. } else if (PType->isFunctionType())
  5480. PType = PVDecl->getType();
  5481. getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
  5482. PType, S, Extended);
  5483. S += charUnitsToString(ParmOffset);
  5484. ParmOffset += getObjCEncodingTypeSize(PType);
  5485. }
  5486. return S;
  5487. }
  5488. ObjCPropertyImplDecl *
  5489. ASTContext::getObjCPropertyImplDeclForPropertyDecl(
  5490. const ObjCPropertyDecl *PD,
  5491. const Decl *Container) const {
  5492. if (!Container)
  5493. return nullptr;
  5494. if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
  5495. for (auto *PID : CID->property_impls())
  5496. if (PID->getPropertyDecl() == PD)
  5497. return PID;
  5498. } else {
  5499. const auto *OID = cast<ObjCImplementationDecl>(Container);
  5500. for (auto *PID : OID->property_impls())
  5501. if (PID->getPropertyDecl() == PD)
  5502. return PID;
  5503. }
  5504. return nullptr;
  5505. }
  5506. /// getObjCEncodingForPropertyDecl - Return the encoded type for this
  5507. /// property declaration. If non-NULL, Container must be either an
  5508. /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
  5509. /// NULL when getting encodings for protocol properties.
  5510. /// Property attributes are stored as a comma-delimited C string. The simple
  5511. /// attributes readonly and bycopy are encoded as single characters. The
  5512. /// parametrized attributes, getter=name, setter=name, and ivar=name, are
  5513. /// encoded as single characters, followed by an identifier. Property types
  5514. /// are also encoded as a parametrized attribute. The characters used to encode
  5515. /// these attributes are defined by the following enumeration:
  5516. /// @code
  5517. /// enum PropertyAttributes {
  5518. /// kPropertyReadOnly = 'R', // property is read-only.
  5519. /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
  5520. /// kPropertyByref = '&', // property is a reference to the value last assigned
  5521. /// kPropertyDynamic = 'D', // property is dynamic
  5522. /// kPropertyGetter = 'G', // followed by getter selector name
  5523. /// kPropertySetter = 'S', // followed by setter selector name
  5524. /// kPropertyInstanceVariable = 'V' // followed by instance variable name
  5525. /// kPropertyType = 'T' // followed by old-style type encoding.
  5526. /// kPropertyWeak = 'W' // 'weak' property
  5527. /// kPropertyStrong = 'P' // property GC'able
  5528. /// kPropertyNonAtomic = 'N' // property non-atomic
  5529. /// };
  5530. /// @endcode
  5531. std::string
  5532. ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
  5533. const Decl *Container) const {
  5534. // Collect information from the property implementation decl(s).
  5535. bool Dynamic = false;
  5536. ObjCPropertyImplDecl *SynthesizePID = nullptr;
  5537. if (ObjCPropertyImplDecl *PropertyImpDecl =
  5538. getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
  5539. if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
  5540. Dynamic = true;
  5541. else
  5542. SynthesizePID = PropertyImpDecl;
  5543. }
  5544. // FIXME: This is not very efficient.
  5545. std::string S = "T";
  5546. // Encode result type.
  5547. // GCC has some special rules regarding encoding of properties which
  5548. // closely resembles encoding of ivars.
  5549. getObjCEncodingForPropertyType(PD->getType(), S);
  5550. if (PD->isReadOnly()) {
  5551. S += ",R";
  5552. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
  5553. S += ",C";
  5554. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
  5555. S += ",&";
  5556. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
  5557. S += ",W";
  5558. } else {
  5559. switch (PD->getSetterKind()) {
  5560. case ObjCPropertyDecl::Assign: break;
  5561. case ObjCPropertyDecl::Copy: S += ",C"; break;
  5562. case ObjCPropertyDecl::Retain: S += ",&"; break;
  5563. case ObjCPropertyDecl::Weak: S += ",W"; break;
  5564. }
  5565. }
  5566. // It really isn't clear at all what this means, since properties
  5567. // are "dynamic by default".
  5568. if (Dynamic)
  5569. S += ",D";
  5570. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
  5571. S += ",N";
  5572. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
  5573. S += ",G";
  5574. S += PD->getGetterName().getAsString();
  5575. }
  5576. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
  5577. S += ",S";
  5578. S += PD->getSetterName().getAsString();
  5579. }
  5580. if (SynthesizePID) {
  5581. const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
  5582. S += ",V";
  5583. S += OID->getNameAsString();
  5584. }
  5585. // FIXME: OBJCGC: weak & strong
  5586. return S;
  5587. }
  5588. /// getLegacyIntegralTypeEncoding -
  5589. /// Another legacy compatibility encoding: 32-bit longs are encoded as
  5590. /// 'l' or 'L' , but not always. For typedefs, we need to use
  5591. /// 'i' or 'I' instead if encoding a struct field, or a pointer!
  5592. void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
  5593. if (isa<TypedefType>(PointeeTy.getTypePtr())) {
  5594. if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
  5595. if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
  5596. PointeeTy = UnsignedIntTy;
  5597. else
  5598. if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
  5599. PointeeTy = IntTy;
  5600. }
  5601. }
  5602. }
  5603. void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
  5604. const FieldDecl *Field,
  5605. QualType *NotEncodedT) const {
  5606. // We follow the behavior of gcc, expanding structures which are
  5607. // directly pointed to, and expanding embedded structures. Note that
  5608. // these rules are sufficient to prevent recursive encoding of the
  5609. // same type.
  5610. getObjCEncodingForTypeImpl(T, S, true, true, Field,
  5611. true /* outermost type */, false, false,
  5612. false, false, false, NotEncodedT);
  5613. }
  5614. void ASTContext::getObjCEncodingForPropertyType(QualType T,
  5615. std::string& S) const {
  5616. // Encode result type.
  5617. // GCC has some special rules regarding encoding of properties which
  5618. // closely resembles encoding of ivars.
  5619. getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
  5620. true /* outermost type */,
  5621. true /* encoding property */);
  5622. }
  5623. static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
  5624. BuiltinType::Kind kind) {
  5625. switch (kind) {
  5626. case BuiltinType::Void: return 'v';
  5627. case BuiltinType::Bool: return 'B';
  5628. case BuiltinType::Char8:
  5629. case BuiltinType::Char_U:
  5630. case BuiltinType::UChar: return 'C';
  5631. case BuiltinType::Char16:
  5632. case BuiltinType::UShort: return 'S';
  5633. case BuiltinType::Char32:
  5634. case BuiltinType::UInt: return 'I';
  5635. case BuiltinType::ULong:
  5636. return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
  5637. case BuiltinType::UInt128: return 'T';
  5638. case BuiltinType::ULongLong: return 'Q';
  5639. case BuiltinType::Char_S:
  5640. case BuiltinType::SChar: return 'c';
  5641. case BuiltinType::Short: return 's';
  5642. case BuiltinType::WChar_S:
  5643. case BuiltinType::WChar_U:
  5644. case BuiltinType::Int: return 'i';
  5645. case BuiltinType::Long:
  5646. return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
  5647. case BuiltinType::LongLong: return 'q';
  5648. case BuiltinType::Int128: return 't';
  5649. case BuiltinType::Float: return 'f';
  5650. case BuiltinType::Double: return 'd';
  5651. case BuiltinType::LongDouble: return 'D';
  5652. case BuiltinType::NullPtr: return '*'; // like char*
  5653. case BuiltinType::Float16:
  5654. case BuiltinType::Float128:
  5655. case BuiltinType::Half:
  5656. case BuiltinType::ShortAccum:
  5657. case BuiltinType::Accum:
  5658. case BuiltinType::LongAccum:
  5659. case BuiltinType::UShortAccum:
  5660. case BuiltinType::UAccum:
  5661. case BuiltinType::ULongAccum:
  5662. case BuiltinType::ShortFract:
  5663. case BuiltinType::Fract:
  5664. case BuiltinType::LongFract:
  5665. case BuiltinType::UShortFract:
  5666. case BuiltinType::UFract:
  5667. case BuiltinType::ULongFract:
  5668. case BuiltinType::SatShortAccum:
  5669. case BuiltinType::SatAccum:
  5670. case BuiltinType::SatLongAccum:
  5671. case BuiltinType::SatUShortAccum:
  5672. case BuiltinType::SatUAccum:
  5673. case BuiltinType::SatULongAccum:
  5674. case BuiltinType::SatShortFract:
  5675. case BuiltinType::SatFract:
  5676. case BuiltinType::SatLongFract:
  5677. case BuiltinType::SatUShortFract:
  5678. case BuiltinType::SatUFract:
  5679. case BuiltinType::SatULongFract:
  5680. // FIXME: potentially need @encodes for these!
  5681. return ' ';
  5682. case BuiltinType::ObjCId:
  5683. case BuiltinType::ObjCClass:
  5684. case BuiltinType::ObjCSel:
  5685. llvm_unreachable("@encoding ObjC primitive type");
  5686. // OpenCL and placeholder types don't need @encodings.
  5687. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  5688. case BuiltinType::Id:
  5689. #include "clang/Basic/OpenCLImageTypes.def"
  5690. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  5691. case BuiltinType::Id:
  5692. #include "clang/Basic/OpenCLExtensionTypes.def"
  5693. case BuiltinType::OCLEvent:
  5694. case BuiltinType::OCLClkEvent:
  5695. case BuiltinType::OCLQueue:
  5696. case BuiltinType::OCLReserveID:
  5697. case BuiltinType::OCLSampler:
  5698. case BuiltinType::Dependent:
  5699. #define BUILTIN_TYPE(KIND, ID)
  5700. #define PLACEHOLDER_TYPE(KIND, ID) \
  5701. case BuiltinType::KIND:
  5702. #include "clang/AST/BuiltinTypes.def"
  5703. llvm_unreachable("invalid builtin type for @encode");
  5704. }
  5705. llvm_unreachable("invalid BuiltinType::Kind value");
  5706. }
  5707. static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
  5708. EnumDecl *Enum = ET->getDecl();
  5709. // The encoding of an non-fixed enum type is always 'i', regardless of size.
  5710. if (!Enum->isFixed())
  5711. return 'i';
  5712. // The encoding of a fixed enum type matches its fixed underlying type.
  5713. const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
  5714. return getObjCEncodingForPrimitiveKind(C, BT->getKind());
  5715. }
  5716. static void EncodeBitField(const ASTContext *Ctx, std::string& S,
  5717. QualType T, const FieldDecl *FD) {
  5718. assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
  5719. S += 'b';
  5720. // The NeXT runtime encodes bit fields as b followed by the number of bits.
  5721. // The GNU runtime requires more information; bitfields are encoded as b,
  5722. // then the offset (in bits) of the first element, then the type of the
  5723. // bitfield, then the size in bits. For example, in this structure:
  5724. //
  5725. // struct
  5726. // {
  5727. // int integer;
  5728. // int flags:2;
  5729. // };
  5730. // On a 32-bit system, the encoding for flags would be b2 for the NeXT
  5731. // runtime, but b32i2 for the GNU runtime. The reason for this extra
  5732. // information is not especially sensible, but we're stuck with it for
  5733. // compatibility with GCC, although providing it breaks anything that
  5734. // actually uses runtime introspection and wants to work on both runtimes...
  5735. if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
  5736. uint64_t Offset;
  5737. if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
  5738. Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
  5739. IVD);
  5740. } else {
  5741. const RecordDecl *RD = FD->getParent();
  5742. const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
  5743. Offset = RL.getFieldOffset(FD->getFieldIndex());
  5744. }
  5745. S += llvm::utostr(Offset);
  5746. if (const auto *ET = T->getAs<EnumType>())
  5747. S += ObjCEncodingForEnumType(Ctx, ET);
  5748. else {
  5749. const auto *BT = T->castAs<BuiltinType>();
  5750. S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
  5751. }
  5752. }
  5753. S += llvm::utostr(FD->getBitWidthValue(*Ctx));
  5754. }
  5755. // FIXME: Use SmallString for accumulating string.
  5756. void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
  5757. bool ExpandPointedToStructures,
  5758. bool ExpandStructures,
  5759. const FieldDecl *FD,
  5760. bool OutermostType,
  5761. bool EncodingProperty,
  5762. bool StructField,
  5763. bool EncodeBlockParameters,
  5764. bool EncodeClassNames,
  5765. bool EncodePointerToObjCTypedef,
  5766. QualType *NotEncodedT) const {
  5767. CanQualType CT = getCanonicalType(T);
  5768. switch (CT->getTypeClass()) {
  5769. case Type::Builtin:
  5770. case Type::Enum:
  5771. if (FD && FD->isBitField())
  5772. return EncodeBitField(this, S, T, FD);
  5773. if (const auto *BT = dyn_cast<BuiltinType>(CT))
  5774. S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
  5775. else
  5776. S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
  5777. return;
  5778. case Type::Complex: {
  5779. const auto *CT = T->castAs<ComplexType>();
  5780. S += 'j';
  5781. getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
  5782. return;
  5783. }
  5784. case Type::Atomic: {
  5785. const auto *AT = T->castAs<AtomicType>();
  5786. S += 'A';
  5787. getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
  5788. return;
  5789. }
  5790. // encoding for pointer or reference types.
  5791. case Type::Pointer:
  5792. case Type::LValueReference:
  5793. case Type::RValueReference: {
  5794. QualType PointeeTy;
  5795. if (isa<PointerType>(CT)) {
  5796. const auto *PT = T->castAs<PointerType>();
  5797. if (PT->isObjCSelType()) {
  5798. S += ':';
  5799. return;
  5800. }
  5801. PointeeTy = PT->getPointeeType();
  5802. } else {
  5803. PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
  5804. }
  5805. bool isReadOnly = false;
  5806. // For historical/compatibility reasons, the read-only qualifier of the
  5807. // pointee gets emitted _before_ the '^'. The read-only qualifier of
  5808. // the pointer itself gets ignored, _unless_ we are looking at a typedef!
  5809. // Also, do not emit the 'r' for anything but the outermost type!
  5810. if (isa<TypedefType>(T.getTypePtr())) {
  5811. if (OutermostType && T.isConstQualified()) {
  5812. isReadOnly = true;
  5813. S += 'r';
  5814. }
  5815. } else if (OutermostType) {
  5816. QualType P = PointeeTy;
  5817. while (P->getAs<PointerType>())
  5818. P = P->getAs<PointerType>()->getPointeeType();
  5819. if (P.isConstQualified()) {
  5820. isReadOnly = true;
  5821. S += 'r';
  5822. }
  5823. }
  5824. if (isReadOnly) {
  5825. // Another legacy compatibility encoding. Some ObjC qualifier and type
  5826. // combinations need to be rearranged.
  5827. // Rewrite "in const" from "nr" to "rn"
  5828. if (StringRef(S).endswith("nr"))
  5829. S.replace(S.end()-2, S.end(), "rn");
  5830. }
  5831. if (PointeeTy->isCharType()) {
  5832. // char pointer types should be encoded as '*' unless it is a
  5833. // type that has been typedef'd to 'BOOL'.
  5834. if (!isTypeTypedefedAsBOOL(PointeeTy)) {
  5835. S += '*';
  5836. return;
  5837. }
  5838. } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
  5839. // GCC binary compat: Need to convert "struct objc_class *" to "#".
  5840. if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
  5841. S += '#';
  5842. return;
  5843. }
  5844. // GCC binary compat: Need to convert "struct objc_object *" to "@".
  5845. if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
  5846. S += '@';
  5847. return;
  5848. }
  5849. // fall through...
  5850. }
  5851. S += '^';
  5852. getLegacyIntegralTypeEncoding(PointeeTy);
  5853. getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
  5854. nullptr, false, false, false, false, false, false,
  5855. NotEncodedT);
  5856. return;
  5857. }
  5858. case Type::ConstantArray:
  5859. case Type::IncompleteArray:
  5860. case Type::VariableArray: {
  5861. const auto *AT = cast<ArrayType>(CT);
  5862. if (isa<IncompleteArrayType>(AT) && !StructField) {
  5863. // Incomplete arrays are encoded as a pointer to the array element.
  5864. S += '^';
  5865. getObjCEncodingForTypeImpl(AT->getElementType(), S,
  5866. false, ExpandStructures, FD);
  5867. } else {
  5868. S += '[';
  5869. if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
  5870. S += llvm::utostr(CAT->getSize().getZExtValue());
  5871. else {
  5872. //Variable length arrays are encoded as a regular array with 0 elements.
  5873. assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
  5874. "Unknown array type!");
  5875. S += '0';
  5876. }
  5877. getObjCEncodingForTypeImpl(AT->getElementType(), S,
  5878. false, ExpandStructures, FD,
  5879. false, false, false, false, false, false,
  5880. NotEncodedT);
  5881. S += ']';
  5882. }
  5883. return;
  5884. }
  5885. case Type::FunctionNoProto:
  5886. case Type::FunctionProto:
  5887. S += '?';
  5888. return;
  5889. case Type::Record: {
  5890. RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
  5891. S += RDecl->isUnion() ? '(' : '{';
  5892. // Anonymous structures print as '?'
  5893. if (const IdentifierInfo *II = RDecl->getIdentifier()) {
  5894. S += II->getName();
  5895. if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
  5896. const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
  5897. llvm::raw_string_ostream OS(S);
  5898. printTemplateArgumentList(OS, TemplateArgs.asArray(),
  5899. getPrintingPolicy());
  5900. }
  5901. } else {
  5902. S += '?';
  5903. }
  5904. if (ExpandStructures) {
  5905. S += '=';
  5906. if (!RDecl->isUnion()) {
  5907. getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
  5908. } else {
  5909. for (const auto *Field : RDecl->fields()) {
  5910. if (FD) {
  5911. S += '"';
  5912. S += Field->getNameAsString();
  5913. S += '"';
  5914. }
  5915. // Special case bit-fields.
  5916. if (Field->isBitField()) {
  5917. getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
  5918. Field);
  5919. } else {
  5920. QualType qt = Field->getType();
  5921. getLegacyIntegralTypeEncoding(qt);
  5922. getObjCEncodingForTypeImpl(qt, S, false, true,
  5923. FD, /*OutermostType*/false,
  5924. /*EncodingProperty*/false,
  5925. /*StructField*/true,
  5926. false, false, false, NotEncodedT);
  5927. }
  5928. }
  5929. }
  5930. }
  5931. S += RDecl->isUnion() ? ')' : '}';
  5932. return;
  5933. }
  5934. case Type::BlockPointer: {
  5935. const auto *BT = T->castAs<BlockPointerType>();
  5936. S += "@?"; // Unlike a pointer-to-function, which is "^?".
  5937. if (EncodeBlockParameters) {
  5938. const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
  5939. S += '<';
  5940. // Block return type
  5941. getObjCEncodingForTypeImpl(
  5942. FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
  5943. FD, false /* OutermostType */, EncodingProperty,
  5944. false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
  5945. NotEncodedT);
  5946. // Block self
  5947. S += "@?";
  5948. // Block parameters
  5949. if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
  5950. for (const auto &I : FPT->param_types())
  5951. getObjCEncodingForTypeImpl(
  5952. I, S, ExpandPointedToStructures, ExpandStructures, FD,
  5953. false /* OutermostType */, EncodingProperty,
  5954. false /* StructField */, EncodeBlockParameters, EncodeClassNames,
  5955. false, NotEncodedT);
  5956. }
  5957. S += '>';
  5958. }
  5959. return;
  5960. }
  5961. case Type::ObjCObject: {
  5962. // hack to match legacy encoding of *id and *Class
  5963. QualType Ty = getObjCObjectPointerType(CT);
  5964. if (Ty->isObjCIdType()) {
  5965. S += "{objc_object=}";
  5966. return;
  5967. }
  5968. else if (Ty->isObjCClassType()) {
  5969. S += "{objc_class=}";
  5970. return;
  5971. }
  5972. // TODO: Double check to make sure this intentionally falls through.
  5973. LLVM_FALLTHROUGH;
  5974. }
  5975. case Type::ObjCInterface: {
  5976. // Ignore protocol qualifiers when mangling at this level.
  5977. // @encode(class_name)
  5978. ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
  5979. S += '{';
  5980. S += OI->getObjCRuntimeNameAsString();
  5981. if (ExpandStructures) {
  5982. S += '=';
  5983. SmallVector<const ObjCIvarDecl*, 32> Ivars;
  5984. DeepCollectObjCIvars(OI, true, Ivars);
  5985. for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
  5986. const FieldDecl *Field = Ivars[i];
  5987. if (Field->isBitField())
  5988. getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
  5989. else
  5990. getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
  5991. false, false, false, false, false,
  5992. EncodePointerToObjCTypedef,
  5993. NotEncodedT);
  5994. }
  5995. }
  5996. S += '}';
  5997. return;
  5998. }
  5999. case Type::ObjCObjectPointer: {
  6000. const auto *OPT = T->castAs<ObjCObjectPointerType>();
  6001. if (OPT->isObjCIdType()) {
  6002. S += '@';
  6003. return;
  6004. }
  6005. if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
  6006. // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
  6007. // Since this is a binary compatibility issue, need to consult with runtime
  6008. // folks. Fortunately, this is a *very* obscure construct.
  6009. S += '#';
  6010. return;
  6011. }
  6012. if (OPT->isObjCQualifiedIdType()) {
  6013. getObjCEncodingForTypeImpl(getObjCIdType(), S,
  6014. ExpandPointedToStructures,
  6015. ExpandStructures, FD);
  6016. if (FD || EncodingProperty || EncodeClassNames) {
  6017. // Note that we do extended encoding of protocol qualifer list
  6018. // Only when doing ivar or property encoding.
  6019. S += '"';
  6020. for (const auto *I : OPT->quals()) {
  6021. S += '<';
  6022. S += I->getObjCRuntimeNameAsString();
  6023. S += '>';
  6024. }
  6025. S += '"';
  6026. }
  6027. return;
  6028. }
  6029. QualType PointeeTy = OPT->getPointeeType();
  6030. if (!EncodingProperty &&
  6031. isa<TypedefType>(PointeeTy.getTypePtr()) &&
  6032. !EncodePointerToObjCTypedef) {
  6033. // Another historical/compatibility reason.
  6034. // We encode the underlying type which comes out as
  6035. // {...};
  6036. S += '^';
  6037. if (FD && OPT->getInterfaceDecl()) {
  6038. // Prevent recursive encoding of fields in some rare cases.
  6039. ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
  6040. SmallVector<const ObjCIvarDecl*, 32> Ivars;
  6041. DeepCollectObjCIvars(OI, true, Ivars);
  6042. for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
  6043. if (Ivars[i] == FD) {
  6044. S += '{';
  6045. S += OI->getObjCRuntimeNameAsString();
  6046. S += '}';
  6047. return;
  6048. }
  6049. }
  6050. }
  6051. getObjCEncodingForTypeImpl(PointeeTy, S,
  6052. false, ExpandPointedToStructures,
  6053. nullptr,
  6054. false, false, false, false, false,
  6055. /*EncodePointerToObjCTypedef*/true);
  6056. return;
  6057. }
  6058. S += '@';
  6059. if (OPT->getInterfaceDecl() &&
  6060. (FD || EncodingProperty || EncodeClassNames)) {
  6061. S += '"';
  6062. S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
  6063. for (const auto *I : OPT->quals()) {
  6064. S += '<';
  6065. S += I->getObjCRuntimeNameAsString();
  6066. S += '>';
  6067. }
  6068. S += '"';
  6069. }
  6070. return;
  6071. }
  6072. // gcc just blithely ignores member pointers.
  6073. // FIXME: we shoul do better than that. 'M' is available.
  6074. case Type::MemberPointer:
  6075. // This matches gcc's encoding, even though technically it is insufficient.
  6076. //FIXME. We should do a better job than gcc.
  6077. case Type::Vector:
  6078. case Type::ExtVector:
  6079. // Until we have a coherent encoding of these three types, issue warning.
  6080. if (NotEncodedT)
  6081. *NotEncodedT = T;
  6082. return;
  6083. // We could see an undeduced auto type here during error recovery.
  6084. // Just ignore it.
  6085. case Type::Auto:
  6086. case Type::DeducedTemplateSpecialization:
  6087. return;
  6088. case Type::Pipe:
  6089. #define ABSTRACT_TYPE(KIND, BASE)
  6090. #define TYPE(KIND, BASE)
  6091. #define DEPENDENT_TYPE(KIND, BASE) \
  6092. case Type::KIND:
  6093. #define NON_CANONICAL_TYPE(KIND, BASE) \
  6094. case Type::KIND:
  6095. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
  6096. case Type::KIND:
  6097. #include "clang/AST/TypeNodes.def"
  6098. llvm_unreachable("@encode for dependent type!");
  6099. }
  6100. llvm_unreachable("bad type kind!");
  6101. }
  6102. void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
  6103. std::string &S,
  6104. const FieldDecl *FD,
  6105. bool includeVBases,
  6106. QualType *NotEncodedT) const {
  6107. assert(RDecl && "Expected non-null RecordDecl");
  6108. assert(!RDecl->isUnion() && "Should not be called for unions");
  6109. if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
  6110. return;
  6111. const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
  6112. std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
  6113. const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
  6114. if (CXXRec) {
  6115. for (const auto &BI : CXXRec->bases()) {
  6116. if (!BI.isVirtual()) {
  6117. CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
  6118. if (base->isEmpty())
  6119. continue;
  6120. uint64_t offs = toBits(layout.getBaseClassOffset(base));
  6121. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
  6122. std::make_pair(offs, base));
  6123. }
  6124. }
  6125. }
  6126. unsigned i = 0;
  6127. for (auto *Field : RDecl->fields()) {
  6128. uint64_t offs = layout.getFieldOffset(i);
  6129. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
  6130. std::make_pair(offs, Field));
  6131. ++i;
  6132. }
  6133. if (CXXRec && includeVBases) {
  6134. for (const auto &BI : CXXRec->vbases()) {
  6135. CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
  6136. if (base->isEmpty())
  6137. continue;
  6138. uint64_t offs = toBits(layout.getVBaseClassOffset(base));
  6139. if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
  6140. FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
  6141. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
  6142. std::make_pair(offs, base));
  6143. }
  6144. }
  6145. CharUnits size;
  6146. if (CXXRec) {
  6147. size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
  6148. } else {
  6149. size = layout.getSize();
  6150. }
  6151. #ifndef NDEBUG
  6152. uint64_t CurOffs = 0;
  6153. #endif
  6154. std::multimap<uint64_t, NamedDecl *>::iterator
  6155. CurLayObj = FieldOrBaseOffsets.begin();
  6156. if (CXXRec && CXXRec->isDynamicClass() &&
  6157. (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
  6158. if (FD) {
  6159. S += "\"_vptr$";
  6160. std::string recname = CXXRec->getNameAsString();
  6161. if (recname.empty()) recname = "?";
  6162. S += recname;
  6163. S += '"';
  6164. }
  6165. S += "^^?";
  6166. #ifndef NDEBUG
  6167. CurOffs += getTypeSize(VoidPtrTy);
  6168. #endif
  6169. }
  6170. if (!RDecl->hasFlexibleArrayMember()) {
  6171. // Mark the end of the structure.
  6172. uint64_t offs = toBits(size);
  6173. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
  6174. std::make_pair(offs, nullptr));
  6175. }
  6176. for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
  6177. #ifndef NDEBUG
  6178. assert(CurOffs <= CurLayObj->first);
  6179. if (CurOffs < CurLayObj->first) {
  6180. uint64_t padding = CurLayObj->first - CurOffs;
  6181. // FIXME: There doesn't seem to be a way to indicate in the encoding that
  6182. // packing/alignment of members is different that normal, in which case
  6183. // the encoding will be out-of-sync with the real layout.
  6184. // If the runtime switches to just consider the size of types without
  6185. // taking into account alignment, we could make padding explicit in the
  6186. // encoding (e.g. using arrays of chars). The encoding strings would be
  6187. // longer then though.
  6188. CurOffs += padding;
  6189. }
  6190. #endif
  6191. NamedDecl *dcl = CurLayObj->second;
  6192. if (!dcl)
  6193. break; // reached end of structure.
  6194. if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
  6195. // We expand the bases without their virtual bases since those are going
  6196. // in the initial structure. Note that this differs from gcc which
  6197. // expands virtual bases each time one is encountered in the hierarchy,
  6198. // making the encoding type bigger than it really is.
  6199. getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
  6200. NotEncodedT);
  6201. assert(!base->isEmpty());
  6202. #ifndef NDEBUG
  6203. CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
  6204. #endif
  6205. } else {
  6206. const auto *field = cast<FieldDecl>(dcl);
  6207. if (FD) {
  6208. S += '"';
  6209. S += field->getNameAsString();
  6210. S += '"';
  6211. }
  6212. if (field->isBitField()) {
  6213. EncodeBitField(this, S, field->getType(), field);
  6214. #ifndef NDEBUG
  6215. CurOffs += field->getBitWidthValue(*this);
  6216. #endif
  6217. } else {
  6218. QualType qt = field->getType();
  6219. getLegacyIntegralTypeEncoding(qt);
  6220. getObjCEncodingForTypeImpl(qt, S, false, true, FD,
  6221. /*OutermostType*/false,
  6222. /*EncodingProperty*/false,
  6223. /*StructField*/true,
  6224. false, false, false, NotEncodedT);
  6225. #ifndef NDEBUG
  6226. CurOffs += getTypeSize(field->getType());
  6227. #endif
  6228. }
  6229. }
  6230. }
  6231. }
  6232. void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
  6233. std::string& S) const {
  6234. if (QT & Decl::OBJC_TQ_In)
  6235. S += 'n';
  6236. if (QT & Decl::OBJC_TQ_Inout)
  6237. S += 'N';
  6238. if (QT & Decl::OBJC_TQ_Out)
  6239. S += 'o';
  6240. if (QT & Decl::OBJC_TQ_Bycopy)
  6241. S += 'O';
  6242. if (QT & Decl::OBJC_TQ_Byref)
  6243. S += 'R';
  6244. if (QT & Decl::OBJC_TQ_Oneway)
  6245. S += 'V';
  6246. }
  6247. TypedefDecl *ASTContext::getObjCIdDecl() const {
  6248. if (!ObjCIdDecl) {
  6249. QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
  6250. T = getObjCObjectPointerType(T);
  6251. ObjCIdDecl = buildImplicitTypedef(T, "id");
  6252. }
  6253. return ObjCIdDecl;
  6254. }
  6255. TypedefDecl *ASTContext::getObjCSelDecl() const {
  6256. if (!ObjCSelDecl) {
  6257. QualType T = getPointerType(ObjCBuiltinSelTy);
  6258. ObjCSelDecl = buildImplicitTypedef(T, "SEL");
  6259. }
  6260. return ObjCSelDecl;
  6261. }
  6262. TypedefDecl *ASTContext::getObjCClassDecl() const {
  6263. if (!ObjCClassDecl) {
  6264. QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
  6265. T = getObjCObjectPointerType(T);
  6266. ObjCClassDecl = buildImplicitTypedef(T, "Class");
  6267. }
  6268. return ObjCClassDecl;
  6269. }
  6270. ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
  6271. if (!ObjCProtocolClassDecl) {
  6272. ObjCProtocolClassDecl
  6273. = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
  6274. SourceLocation(),
  6275. &Idents.get("Protocol"),
  6276. /*typeParamList=*/nullptr,
  6277. /*PrevDecl=*/nullptr,
  6278. SourceLocation(), true);
  6279. }
  6280. return ObjCProtocolClassDecl;
  6281. }
  6282. //===----------------------------------------------------------------------===//
  6283. // __builtin_va_list Construction Functions
  6284. //===----------------------------------------------------------------------===//
  6285. static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
  6286. StringRef Name) {
  6287. // typedef char* __builtin[_ms]_va_list;
  6288. QualType T = Context->getPointerType(Context->CharTy);
  6289. return Context->buildImplicitTypedef(T, Name);
  6290. }
  6291. static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
  6292. return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
  6293. }
  6294. static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
  6295. return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
  6296. }
  6297. static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
  6298. // typedef void* __builtin_va_list;
  6299. QualType T = Context->getPointerType(Context->VoidTy);
  6300. return Context->buildImplicitTypedef(T, "__builtin_va_list");
  6301. }
  6302. static TypedefDecl *
  6303. CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
  6304. // struct __va_list
  6305. RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
  6306. if (Context->getLangOpts().CPlusPlus) {
  6307. // namespace std { struct __va_list {
  6308. NamespaceDecl *NS;
  6309. NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
  6310. Context->getTranslationUnitDecl(),
  6311. /*Inline*/ false, SourceLocation(),
  6312. SourceLocation(), &Context->Idents.get("std"),
  6313. /*PrevDecl*/ nullptr);
  6314. NS->setImplicit();
  6315. VaListTagDecl->setDeclContext(NS);
  6316. }
  6317. VaListTagDecl->startDefinition();
  6318. const size_t NumFields = 5;
  6319. QualType FieldTypes[NumFields];
  6320. const char *FieldNames[NumFields];
  6321. // void *__stack;
  6322. FieldTypes[0] = Context->getPointerType(Context->VoidTy);
  6323. FieldNames[0] = "__stack";
  6324. // void *__gr_top;
  6325. FieldTypes[1] = Context->getPointerType(Context->VoidTy);
  6326. FieldNames[1] = "__gr_top";
  6327. // void *__vr_top;
  6328. FieldTypes[2] = Context->getPointerType(Context->VoidTy);
  6329. FieldNames[2] = "__vr_top";
  6330. // int __gr_offs;
  6331. FieldTypes[3] = Context->IntTy;
  6332. FieldNames[3] = "__gr_offs";
  6333. // int __vr_offs;
  6334. FieldTypes[4] = Context->IntTy;
  6335. FieldNames[4] = "__vr_offs";
  6336. // Create fields
  6337. for (unsigned i = 0; i < NumFields; ++i) {
  6338. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  6339. VaListTagDecl,
  6340. SourceLocation(),
  6341. SourceLocation(),
  6342. &Context->Idents.get(FieldNames[i]),
  6343. FieldTypes[i], /*TInfo=*/nullptr,
  6344. /*BitWidth=*/nullptr,
  6345. /*Mutable=*/false,
  6346. ICIS_NoInit);
  6347. Field->setAccess(AS_public);
  6348. VaListTagDecl->addDecl(Field);
  6349. }
  6350. VaListTagDecl->completeDefinition();
  6351. Context->VaListTagDecl = VaListTagDecl;
  6352. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  6353. // } __builtin_va_list;
  6354. return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
  6355. }
  6356. static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
  6357. // typedef struct __va_list_tag {
  6358. RecordDecl *VaListTagDecl;
  6359. VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
  6360. VaListTagDecl->startDefinition();
  6361. const size_t NumFields = 5;
  6362. QualType FieldTypes[NumFields];
  6363. const char *FieldNames[NumFields];
  6364. // unsigned char gpr;
  6365. FieldTypes[0] = Context->UnsignedCharTy;
  6366. FieldNames[0] = "gpr";
  6367. // unsigned char fpr;
  6368. FieldTypes[1] = Context->UnsignedCharTy;
  6369. FieldNames[1] = "fpr";
  6370. // unsigned short reserved;
  6371. FieldTypes[2] = Context->UnsignedShortTy;
  6372. FieldNames[2] = "reserved";
  6373. // void* overflow_arg_area;
  6374. FieldTypes[3] = Context->getPointerType(Context->VoidTy);
  6375. FieldNames[3] = "overflow_arg_area";
  6376. // void* reg_save_area;
  6377. FieldTypes[4] = Context->getPointerType(Context->VoidTy);
  6378. FieldNames[4] = "reg_save_area";
  6379. // Create fields
  6380. for (unsigned i = 0; i < NumFields; ++i) {
  6381. FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
  6382. SourceLocation(),
  6383. SourceLocation(),
  6384. &Context->Idents.get(FieldNames[i]),
  6385. FieldTypes[i], /*TInfo=*/nullptr,
  6386. /*BitWidth=*/nullptr,
  6387. /*Mutable=*/false,
  6388. ICIS_NoInit);
  6389. Field->setAccess(AS_public);
  6390. VaListTagDecl->addDecl(Field);
  6391. }
  6392. VaListTagDecl->completeDefinition();
  6393. Context->VaListTagDecl = VaListTagDecl;
  6394. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  6395. // } __va_list_tag;
  6396. TypedefDecl *VaListTagTypedefDecl =
  6397. Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
  6398. QualType VaListTagTypedefType =
  6399. Context->getTypedefType(VaListTagTypedefDecl);
  6400. // typedef __va_list_tag __builtin_va_list[1];
  6401. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
  6402. QualType VaListTagArrayType
  6403. = Context->getConstantArrayType(VaListTagTypedefType,
  6404. Size, ArrayType::Normal, 0);
  6405. return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
  6406. }
  6407. static TypedefDecl *
  6408. CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
  6409. // struct __va_list_tag {
  6410. RecordDecl *VaListTagDecl;
  6411. VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
  6412. VaListTagDecl->startDefinition();
  6413. const size_t NumFields = 4;
  6414. QualType FieldTypes[NumFields];
  6415. const char *FieldNames[NumFields];
  6416. // unsigned gp_offset;
  6417. FieldTypes[0] = Context->UnsignedIntTy;
  6418. FieldNames[0] = "gp_offset";
  6419. // unsigned fp_offset;
  6420. FieldTypes[1] = Context->UnsignedIntTy;
  6421. FieldNames[1] = "fp_offset";
  6422. // void* overflow_arg_area;
  6423. FieldTypes[2] = Context->getPointerType(Context->VoidTy);
  6424. FieldNames[2] = "overflow_arg_area";
  6425. // void* reg_save_area;
  6426. FieldTypes[3] = Context->getPointerType(Context->VoidTy);
  6427. FieldNames[3] = "reg_save_area";
  6428. // Create fields
  6429. for (unsigned i = 0; i < NumFields; ++i) {
  6430. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  6431. VaListTagDecl,
  6432. SourceLocation(),
  6433. SourceLocation(),
  6434. &Context->Idents.get(FieldNames[i]),
  6435. FieldTypes[i], /*TInfo=*/nullptr,
  6436. /*BitWidth=*/nullptr,
  6437. /*Mutable=*/false,
  6438. ICIS_NoInit);
  6439. Field->setAccess(AS_public);
  6440. VaListTagDecl->addDecl(Field);
  6441. }
  6442. VaListTagDecl->completeDefinition();
  6443. Context->VaListTagDecl = VaListTagDecl;
  6444. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  6445. // };
  6446. // typedef struct __va_list_tag __builtin_va_list[1];
  6447. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
  6448. QualType VaListTagArrayType =
  6449. Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
  6450. return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
  6451. }
  6452. static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
  6453. // typedef int __builtin_va_list[4];
  6454. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
  6455. QualType IntArrayType =
  6456. Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
  6457. return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
  6458. }
  6459. static TypedefDecl *
  6460. CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
  6461. // struct __va_list
  6462. RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
  6463. if (Context->getLangOpts().CPlusPlus) {
  6464. // namespace std { struct __va_list {
  6465. NamespaceDecl *NS;
  6466. NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
  6467. Context->getTranslationUnitDecl(),
  6468. /*Inline*/false, SourceLocation(),
  6469. SourceLocation(), &Context->Idents.get("std"),
  6470. /*PrevDecl*/ nullptr);
  6471. NS->setImplicit();
  6472. VaListDecl->setDeclContext(NS);
  6473. }
  6474. VaListDecl->startDefinition();
  6475. // void * __ap;
  6476. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  6477. VaListDecl,
  6478. SourceLocation(),
  6479. SourceLocation(),
  6480. &Context->Idents.get("__ap"),
  6481. Context->getPointerType(Context->VoidTy),
  6482. /*TInfo=*/nullptr,
  6483. /*BitWidth=*/nullptr,
  6484. /*Mutable=*/false,
  6485. ICIS_NoInit);
  6486. Field->setAccess(AS_public);
  6487. VaListDecl->addDecl(Field);
  6488. // };
  6489. VaListDecl->completeDefinition();
  6490. Context->VaListTagDecl = VaListDecl;
  6491. // typedef struct __va_list __builtin_va_list;
  6492. QualType T = Context->getRecordType(VaListDecl);
  6493. return Context->buildImplicitTypedef(T, "__builtin_va_list");
  6494. }
  6495. static TypedefDecl *
  6496. CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
  6497. // struct __va_list_tag {
  6498. RecordDecl *VaListTagDecl;
  6499. VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
  6500. VaListTagDecl->startDefinition();
  6501. const size_t NumFields = 4;
  6502. QualType FieldTypes[NumFields];
  6503. const char *FieldNames[NumFields];
  6504. // long __gpr;
  6505. FieldTypes[0] = Context->LongTy;
  6506. FieldNames[0] = "__gpr";
  6507. // long __fpr;
  6508. FieldTypes[1] = Context->LongTy;
  6509. FieldNames[1] = "__fpr";
  6510. // void *__overflow_arg_area;
  6511. FieldTypes[2] = Context->getPointerType(Context->VoidTy);
  6512. FieldNames[2] = "__overflow_arg_area";
  6513. // void *__reg_save_area;
  6514. FieldTypes[3] = Context->getPointerType(Context->VoidTy);
  6515. FieldNames[3] = "__reg_save_area";
  6516. // Create fields
  6517. for (unsigned i = 0; i < NumFields; ++i) {
  6518. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  6519. VaListTagDecl,
  6520. SourceLocation(),
  6521. SourceLocation(),
  6522. &Context->Idents.get(FieldNames[i]),
  6523. FieldTypes[i], /*TInfo=*/nullptr,
  6524. /*BitWidth=*/nullptr,
  6525. /*Mutable=*/false,
  6526. ICIS_NoInit);
  6527. Field->setAccess(AS_public);
  6528. VaListTagDecl->addDecl(Field);
  6529. }
  6530. VaListTagDecl->completeDefinition();
  6531. Context->VaListTagDecl = VaListTagDecl;
  6532. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  6533. // };
  6534. // typedef __va_list_tag __builtin_va_list[1];
  6535. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
  6536. QualType VaListTagArrayType =
  6537. Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
  6538. return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
  6539. }
  6540. static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
  6541. TargetInfo::BuiltinVaListKind Kind) {
  6542. switch (Kind) {
  6543. case TargetInfo::CharPtrBuiltinVaList:
  6544. return CreateCharPtrBuiltinVaListDecl(Context);
  6545. case TargetInfo::VoidPtrBuiltinVaList:
  6546. return CreateVoidPtrBuiltinVaListDecl(Context);
  6547. case TargetInfo::AArch64ABIBuiltinVaList:
  6548. return CreateAArch64ABIBuiltinVaListDecl(Context);
  6549. case TargetInfo::PowerABIBuiltinVaList:
  6550. return CreatePowerABIBuiltinVaListDecl(Context);
  6551. case TargetInfo::X86_64ABIBuiltinVaList:
  6552. return CreateX86_64ABIBuiltinVaListDecl(Context);
  6553. case TargetInfo::PNaClABIBuiltinVaList:
  6554. return CreatePNaClABIBuiltinVaListDecl(Context);
  6555. case TargetInfo::AAPCSABIBuiltinVaList:
  6556. return CreateAAPCSABIBuiltinVaListDecl(Context);
  6557. case TargetInfo::SystemZBuiltinVaList:
  6558. return CreateSystemZBuiltinVaListDecl(Context);
  6559. }
  6560. llvm_unreachable("Unhandled __builtin_va_list type kind");
  6561. }
  6562. TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
  6563. if (!BuiltinVaListDecl) {
  6564. BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
  6565. assert(BuiltinVaListDecl->isImplicit());
  6566. }
  6567. return BuiltinVaListDecl;
  6568. }
  6569. Decl *ASTContext::getVaListTagDecl() const {
  6570. // Force the creation of VaListTagDecl by building the __builtin_va_list
  6571. // declaration.
  6572. if (!VaListTagDecl)
  6573. (void)getBuiltinVaListDecl();
  6574. return VaListTagDecl;
  6575. }
  6576. TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
  6577. if (!BuiltinMSVaListDecl)
  6578. BuiltinMSVaListDecl = CreateMSVaListDecl(this);
  6579. return BuiltinMSVaListDecl;
  6580. }
  6581. bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
  6582. return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
  6583. }
  6584. void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
  6585. assert(ObjCConstantStringType.isNull() &&
  6586. "'NSConstantString' type already set!");
  6587. ObjCConstantStringType = getObjCInterfaceType(Decl);
  6588. }
  6589. /// Retrieve the template name that corresponds to a non-empty
  6590. /// lookup.
  6591. TemplateName
  6592. ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
  6593. UnresolvedSetIterator End) const {
  6594. unsigned size = End - Begin;
  6595. assert(size > 1 && "set is not overloaded!");
  6596. void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
  6597. size * sizeof(FunctionTemplateDecl*));
  6598. auto *OT = new (memory) OverloadedTemplateStorage(size);
  6599. NamedDecl **Storage = OT->getStorage();
  6600. for (UnresolvedSetIterator I = Begin; I != End; ++I) {
  6601. NamedDecl *D = *I;
  6602. assert(isa<FunctionTemplateDecl>(D) ||
  6603. isa<UnresolvedUsingValueDecl>(D) ||
  6604. (isa<UsingShadowDecl>(D) &&
  6605. isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
  6606. *Storage++ = D;
  6607. }
  6608. return TemplateName(OT);
  6609. }
  6610. /// Retrieve the template name that represents a qualified
  6611. /// template name such as \c std::vector.
  6612. TemplateName
  6613. ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
  6614. bool TemplateKeyword,
  6615. TemplateDecl *Template) const {
  6616. assert(NNS && "Missing nested-name-specifier in qualified template name");
  6617. // FIXME: Canonicalization?
  6618. llvm::FoldingSetNodeID ID;
  6619. QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
  6620. void *InsertPos = nullptr;
  6621. QualifiedTemplateName *QTN =
  6622. QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  6623. if (!QTN) {
  6624. QTN = new (*this, alignof(QualifiedTemplateName))
  6625. QualifiedTemplateName(NNS, TemplateKeyword, Template);
  6626. QualifiedTemplateNames.InsertNode(QTN, InsertPos);
  6627. }
  6628. return TemplateName(QTN);
  6629. }
  6630. /// Retrieve the template name that represents a dependent
  6631. /// template name such as \c MetaFun::template apply.
  6632. TemplateName
  6633. ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
  6634. const IdentifierInfo *Name) const {
  6635. assert((!NNS || NNS->isDependent()) &&
  6636. "Nested name specifier must be dependent");
  6637. llvm::FoldingSetNodeID ID;
  6638. DependentTemplateName::Profile(ID, NNS, Name);
  6639. void *InsertPos = nullptr;
  6640. DependentTemplateName *QTN =
  6641. DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  6642. if (QTN)
  6643. return TemplateName(QTN);
  6644. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  6645. if (CanonNNS == NNS) {
  6646. QTN = new (*this, alignof(DependentTemplateName))
  6647. DependentTemplateName(NNS, Name);
  6648. } else {
  6649. TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
  6650. QTN = new (*this, alignof(DependentTemplateName))
  6651. DependentTemplateName(NNS, Name, Canon);
  6652. DependentTemplateName *CheckQTN =
  6653. DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  6654. assert(!CheckQTN && "Dependent type name canonicalization broken");
  6655. (void)CheckQTN;
  6656. }
  6657. DependentTemplateNames.InsertNode(QTN, InsertPos);
  6658. return TemplateName(QTN);
  6659. }
  6660. /// Retrieve the template name that represents a dependent
  6661. /// template name such as \c MetaFun::template operator+.
  6662. TemplateName
  6663. ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
  6664. OverloadedOperatorKind Operator) const {
  6665. assert((!NNS || NNS->isDependent()) &&
  6666. "Nested name specifier must be dependent");
  6667. llvm::FoldingSetNodeID ID;
  6668. DependentTemplateName::Profile(ID, NNS, Operator);
  6669. void *InsertPos = nullptr;
  6670. DependentTemplateName *QTN
  6671. = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  6672. if (QTN)
  6673. return TemplateName(QTN);
  6674. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  6675. if (CanonNNS == NNS) {
  6676. QTN = new (*this, alignof(DependentTemplateName))
  6677. DependentTemplateName(NNS, Operator);
  6678. } else {
  6679. TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
  6680. QTN = new (*this, alignof(DependentTemplateName))
  6681. DependentTemplateName(NNS, Operator, Canon);
  6682. DependentTemplateName *CheckQTN
  6683. = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  6684. assert(!CheckQTN && "Dependent template name canonicalization broken");
  6685. (void)CheckQTN;
  6686. }
  6687. DependentTemplateNames.InsertNode(QTN, InsertPos);
  6688. return TemplateName(QTN);
  6689. }
  6690. TemplateName
  6691. ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
  6692. TemplateName replacement) const {
  6693. llvm::FoldingSetNodeID ID;
  6694. SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
  6695. void *insertPos = nullptr;
  6696. SubstTemplateTemplateParmStorage *subst
  6697. = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
  6698. if (!subst) {
  6699. subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
  6700. SubstTemplateTemplateParms.InsertNode(subst, insertPos);
  6701. }
  6702. return TemplateName(subst);
  6703. }
  6704. TemplateName
  6705. ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
  6706. const TemplateArgument &ArgPack) const {
  6707. auto &Self = const_cast<ASTContext &>(*this);
  6708. llvm::FoldingSetNodeID ID;
  6709. SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
  6710. void *InsertPos = nullptr;
  6711. SubstTemplateTemplateParmPackStorage *Subst
  6712. = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
  6713. if (!Subst) {
  6714. Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
  6715. ArgPack.pack_size(),
  6716. ArgPack.pack_begin());
  6717. SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
  6718. }
  6719. return TemplateName(Subst);
  6720. }
  6721. /// getFromTargetType - Given one of the integer types provided by
  6722. /// TargetInfo, produce the corresponding type. The unsigned @p Type
  6723. /// is actually a value of type @c TargetInfo::IntType.
  6724. CanQualType ASTContext::getFromTargetType(unsigned Type) const {
  6725. switch (Type) {
  6726. case TargetInfo::NoInt: return {};
  6727. case TargetInfo::SignedChar: return SignedCharTy;
  6728. case TargetInfo::UnsignedChar: return UnsignedCharTy;
  6729. case TargetInfo::SignedShort: return ShortTy;
  6730. case TargetInfo::UnsignedShort: return UnsignedShortTy;
  6731. case TargetInfo::SignedInt: return IntTy;
  6732. case TargetInfo::UnsignedInt: return UnsignedIntTy;
  6733. case TargetInfo::SignedLong: return LongTy;
  6734. case TargetInfo::UnsignedLong: return UnsignedLongTy;
  6735. case TargetInfo::SignedLongLong: return LongLongTy;
  6736. case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
  6737. }
  6738. llvm_unreachable("Unhandled TargetInfo::IntType value");
  6739. }
  6740. //===----------------------------------------------------------------------===//
  6741. // Type Predicates.
  6742. //===----------------------------------------------------------------------===//
  6743. /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
  6744. /// garbage collection attribute.
  6745. ///
  6746. Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
  6747. if (getLangOpts().getGC() == LangOptions::NonGC)
  6748. return Qualifiers::GCNone;
  6749. assert(getLangOpts().ObjC);
  6750. Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
  6751. // Default behaviour under objective-C's gc is for ObjC pointers
  6752. // (or pointers to them) be treated as though they were declared
  6753. // as __strong.
  6754. if (GCAttrs == Qualifiers::GCNone) {
  6755. if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
  6756. return Qualifiers::Strong;
  6757. else if (Ty->isPointerType())
  6758. return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
  6759. } else {
  6760. // It's not valid to set GC attributes on anything that isn't a
  6761. // pointer.
  6762. #ifndef NDEBUG
  6763. QualType CT = Ty->getCanonicalTypeInternal();
  6764. while (const auto *AT = dyn_cast<ArrayType>(CT))
  6765. CT = AT->getElementType();
  6766. assert(CT->isAnyPointerType() || CT->isBlockPointerType());
  6767. #endif
  6768. }
  6769. return GCAttrs;
  6770. }
  6771. //===----------------------------------------------------------------------===//
  6772. // Type Compatibility Testing
  6773. //===----------------------------------------------------------------------===//
  6774. /// areCompatVectorTypes - Return true if the two specified vector types are
  6775. /// compatible.
  6776. static bool areCompatVectorTypes(const VectorType *LHS,
  6777. const VectorType *RHS) {
  6778. assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
  6779. return LHS->getElementType() == RHS->getElementType() &&
  6780. LHS->getNumElements() == RHS->getNumElements();
  6781. }
  6782. bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
  6783. QualType SecondVec) {
  6784. assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
  6785. assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
  6786. if (hasSameUnqualifiedType(FirstVec, SecondVec))
  6787. return true;
  6788. // Treat Neon vector types and most AltiVec vector types as if they are the
  6789. // equivalent GCC vector types.
  6790. const auto *First = FirstVec->getAs<VectorType>();
  6791. const auto *Second = SecondVec->getAs<VectorType>();
  6792. if (First->getNumElements() == Second->getNumElements() &&
  6793. hasSameType(First->getElementType(), Second->getElementType()) &&
  6794. First->getVectorKind() != VectorType::AltiVecPixel &&
  6795. First->getVectorKind() != VectorType::AltiVecBool &&
  6796. Second->getVectorKind() != VectorType::AltiVecPixel &&
  6797. Second->getVectorKind() != VectorType::AltiVecBool)
  6798. return true;
  6799. return false;
  6800. }
  6801. //===----------------------------------------------------------------------===//
  6802. // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
  6803. //===----------------------------------------------------------------------===//
  6804. /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
  6805. /// inheritance hierarchy of 'rProto'.
  6806. bool
  6807. ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
  6808. ObjCProtocolDecl *rProto) const {
  6809. if (declaresSameEntity(lProto, rProto))
  6810. return true;
  6811. for (auto *PI : rProto->protocols())
  6812. if (ProtocolCompatibleWithProtocol(lProto, PI))
  6813. return true;
  6814. return false;
  6815. }
  6816. /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
  6817. /// Class<pr1, ...>.
  6818. bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
  6819. QualType rhs) {
  6820. const auto *lhsQID = lhs->getAs<ObjCObjectPointerType>();
  6821. const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
  6822. assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
  6823. for (auto *lhsProto : lhsQID->quals()) {
  6824. bool match = false;
  6825. for (auto *rhsProto : rhsOPT->quals()) {
  6826. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
  6827. match = true;
  6828. break;
  6829. }
  6830. }
  6831. if (!match)
  6832. return false;
  6833. }
  6834. return true;
  6835. }
  6836. /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
  6837. /// ObjCQualifiedIDType.
  6838. bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
  6839. bool compare) {
  6840. // Allow id<P..> and an 'id' or void* type in all cases.
  6841. if (lhs->isVoidPointerType() ||
  6842. lhs->isObjCIdType() || lhs->isObjCClassType())
  6843. return true;
  6844. else if (rhs->isVoidPointerType() ||
  6845. rhs->isObjCIdType() || rhs->isObjCClassType())
  6846. return true;
  6847. if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
  6848. const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
  6849. if (!rhsOPT) return false;
  6850. if (rhsOPT->qual_empty()) {
  6851. // If the RHS is a unqualified interface pointer "NSString*",
  6852. // make sure we check the class hierarchy.
  6853. if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
  6854. for (auto *I : lhsQID->quals()) {
  6855. // when comparing an id<P> on lhs with a static type on rhs,
  6856. // see if static class implements all of id's protocols, directly or
  6857. // through its super class and categories.
  6858. if (!rhsID->ClassImplementsProtocol(I, true))
  6859. return false;
  6860. }
  6861. }
  6862. // If there are no qualifiers and no interface, we have an 'id'.
  6863. return true;
  6864. }
  6865. // Both the right and left sides have qualifiers.
  6866. for (auto *lhsProto : lhsQID->quals()) {
  6867. bool match = false;
  6868. // when comparing an id<P> on lhs with a static type on rhs,
  6869. // see if static class implements all of id's protocols, directly or
  6870. // through its super class and categories.
  6871. for (auto *rhsProto : rhsOPT->quals()) {
  6872. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
  6873. (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
  6874. match = true;
  6875. break;
  6876. }
  6877. }
  6878. // If the RHS is a qualified interface pointer "NSString<P>*",
  6879. // make sure we check the class hierarchy.
  6880. if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
  6881. for (auto *I : lhsQID->quals()) {
  6882. // when comparing an id<P> on lhs with a static type on rhs,
  6883. // see if static class implements all of id's protocols, directly or
  6884. // through its super class and categories.
  6885. if (rhsID->ClassImplementsProtocol(I, true)) {
  6886. match = true;
  6887. break;
  6888. }
  6889. }
  6890. }
  6891. if (!match)
  6892. return false;
  6893. }
  6894. return true;
  6895. }
  6896. const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
  6897. assert(rhsQID && "One of the LHS/RHS should be id<x>");
  6898. if (const ObjCObjectPointerType *lhsOPT =
  6899. lhs->getAsObjCInterfacePointerType()) {
  6900. // If both the right and left sides have qualifiers.
  6901. for (auto *lhsProto : lhsOPT->quals()) {
  6902. bool match = false;
  6903. // when comparing an id<P> on rhs with a static type on lhs,
  6904. // see if static class implements all of id's protocols, directly or
  6905. // through its super class and categories.
  6906. // First, lhs protocols in the qualifier list must be found, direct
  6907. // or indirect in rhs's qualifier list or it is a mismatch.
  6908. for (auto *rhsProto : rhsQID->quals()) {
  6909. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
  6910. (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
  6911. match = true;
  6912. break;
  6913. }
  6914. }
  6915. if (!match)
  6916. return false;
  6917. }
  6918. // Static class's protocols, or its super class or category protocols
  6919. // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
  6920. if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
  6921. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
  6922. CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
  6923. // This is rather dubious but matches gcc's behavior. If lhs has
  6924. // no type qualifier and its class has no static protocol(s)
  6925. // assume that it is mismatch.
  6926. if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
  6927. return false;
  6928. for (auto *lhsProto : LHSInheritedProtocols) {
  6929. bool match = false;
  6930. for (auto *rhsProto : rhsQID->quals()) {
  6931. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
  6932. (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
  6933. match = true;
  6934. break;
  6935. }
  6936. }
  6937. if (!match)
  6938. return false;
  6939. }
  6940. }
  6941. return true;
  6942. }
  6943. return false;
  6944. }
  6945. /// canAssignObjCInterfaces - Return true if the two interface types are
  6946. /// compatible for assignment from RHS to LHS. This handles validation of any
  6947. /// protocol qualifiers on the LHS or RHS.
  6948. bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
  6949. const ObjCObjectPointerType *RHSOPT) {
  6950. const ObjCObjectType* LHS = LHSOPT->getObjectType();
  6951. const ObjCObjectType* RHS = RHSOPT->getObjectType();
  6952. // If either type represents the built-in 'id' or 'Class' types, return true.
  6953. if (LHS->isObjCUnqualifiedIdOrClass() ||
  6954. RHS->isObjCUnqualifiedIdOrClass())
  6955. return true;
  6956. // Function object that propagates a successful result or handles
  6957. // __kindof types.
  6958. auto finish = [&](bool succeeded) -> bool {
  6959. if (succeeded)
  6960. return true;
  6961. if (!RHS->isKindOfType())
  6962. return false;
  6963. // Strip off __kindof and protocol qualifiers, then check whether
  6964. // we can assign the other way.
  6965. return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
  6966. LHSOPT->stripObjCKindOfTypeAndQuals(*this));
  6967. };
  6968. if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
  6969. return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
  6970. QualType(RHSOPT,0),
  6971. false));
  6972. }
  6973. if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
  6974. return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
  6975. QualType(RHSOPT,0)));
  6976. }
  6977. // If we have 2 user-defined types, fall into that path.
  6978. if (LHS->getInterface() && RHS->getInterface()) {
  6979. return finish(canAssignObjCInterfaces(LHS, RHS));
  6980. }
  6981. return false;
  6982. }
  6983. /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
  6984. /// for providing type-safety for objective-c pointers used to pass/return
  6985. /// arguments in block literals. When passed as arguments, passing 'A*' where
  6986. /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
  6987. /// not OK. For the return type, the opposite is not OK.
  6988. bool ASTContext::canAssignObjCInterfacesInBlockPointer(
  6989. const ObjCObjectPointerType *LHSOPT,
  6990. const ObjCObjectPointerType *RHSOPT,
  6991. bool BlockReturnType) {
  6992. // Function object that propagates a successful result or handles
  6993. // __kindof types.
  6994. auto finish = [&](bool succeeded) -> bool {
  6995. if (succeeded)
  6996. return true;
  6997. const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
  6998. if (!Expected->isKindOfType())
  6999. return false;
  7000. // Strip off __kindof and protocol qualifiers, then check whether
  7001. // we can assign the other way.
  7002. return canAssignObjCInterfacesInBlockPointer(
  7003. RHSOPT->stripObjCKindOfTypeAndQuals(*this),
  7004. LHSOPT->stripObjCKindOfTypeAndQuals(*this),
  7005. BlockReturnType);
  7006. };
  7007. if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
  7008. return true;
  7009. if (LHSOPT->isObjCBuiltinType()) {
  7010. return finish(RHSOPT->isObjCBuiltinType() ||
  7011. RHSOPT->isObjCQualifiedIdType());
  7012. }
  7013. if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
  7014. return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
  7015. QualType(RHSOPT,0),
  7016. false));
  7017. const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
  7018. const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
  7019. if (LHS && RHS) { // We have 2 user-defined types.
  7020. if (LHS != RHS) {
  7021. if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
  7022. return finish(BlockReturnType);
  7023. if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
  7024. return finish(!BlockReturnType);
  7025. }
  7026. else
  7027. return true;
  7028. }
  7029. return false;
  7030. }
  7031. /// Comparison routine for Objective-C protocols to be used with
  7032. /// llvm::array_pod_sort.
  7033. static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
  7034. ObjCProtocolDecl * const *rhs) {
  7035. return (*lhs)->getName().compare((*rhs)->getName());
  7036. }
  7037. /// getIntersectionOfProtocols - This routine finds the intersection of set
  7038. /// of protocols inherited from two distinct objective-c pointer objects with
  7039. /// the given common base.
  7040. /// It is used to build composite qualifier list of the composite type of
  7041. /// the conditional expression involving two objective-c pointer objects.
  7042. static
  7043. void getIntersectionOfProtocols(ASTContext &Context,
  7044. const ObjCInterfaceDecl *CommonBase,
  7045. const ObjCObjectPointerType *LHSOPT,
  7046. const ObjCObjectPointerType *RHSOPT,
  7047. SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
  7048. const ObjCObjectType* LHS = LHSOPT->getObjectType();
  7049. const ObjCObjectType* RHS = RHSOPT->getObjectType();
  7050. assert(LHS->getInterface() && "LHS must have an interface base");
  7051. assert(RHS->getInterface() && "RHS must have an interface base");
  7052. // Add all of the protocols for the LHS.
  7053. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
  7054. // Start with the protocol qualifiers.
  7055. for (auto proto : LHS->quals()) {
  7056. Context.CollectInheritedProtocols(proto, LHSProtocolSet);
  7057. }
  7058. // Also add the protocols associated with the LHS interface.
  7059. Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
  7060. // Add all of the protocols for the RHS.
  7061. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
  7062. // Start with the protocol qualifiers.
  7063. for (auto proto : RHS->quals()) {
  7064. Context.CollectInheritedProtocols(proto, RHSProtocolSet);
  7065. }
  7066. // Also add the protocols associated with the RHS interface.
  7067. Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
  7068. // Compute the intersection of the collected protocol sets.
  7069. for (auto proto : LHSProtocolSet) {
  7070. if (RHSProtocolSet.count(proto))
  7071. IntersectionSet.push_back(proto);
  7072. }
  7073. // Compute the set of protocols that is implied by either the common type or
  7074. // the protocols within the intersection.
  7075. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
  7076. Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
  7077. // Remove any implied protocols from the list of inherited protocols.
  7078. if (!ImpliedProtocols.empty()) {
  7079. IntersectionSet.erase(
  7080. std::remove_if(IntersectionSet.begin(),
  7081. IntersectionSet.end(),
  7082. [&](ObjCProtocolDecl *proto) -> bool {
  7083. return ImpliedProtocols.count(proto) > 0;
  7084. }),
  7085. IntersectionSet.end());
  7086. }
  7087. // Sort the remaining protocols by name.
  7088. llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
  7089. compareObjCProtocolsByName);
  7090. }
  7091. /// Determine whether the first type is a subtype of the second.
  7092. static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
  7093. QualType rhs) {
  7094. // Common case: two object pointers.
  7095. const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
  7096. const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
  7097. if (lhsOPT && rhsOPT)
  7098. return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
  7099. // Two block pointers.
  7100. const auto *lhsBlock = lhs->getAs<BlockPointerType>();
  7101. const auto *rhsBlock = rhs->getAs<BlockPointerType>();
  7102. if (lhsBlock && rhsBlock)
  7103. return ctx.typesAreBlockPointerCompatible(lhs, rhs);
  7104. // If either is an unqualified 'id' and the other is a block, it's
  7105. // acceptable.
  7106. if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
  7107. (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
  7108. return true;
  7109. return false;
  7110. }
  7111. // Check that the given Objective-C type argument lists are equivalent.
  7112. static bool sameObjCTypeArgs(ASTContext &ctx,
  7113. const ObjCInterfaceDecl *iface,
  7114. ArrayRef<QualType> lhsArgs,
  7115. ArrayRef<QualType> rhsArgs,
  7116. bool stripKindOf) {
  7117. if (lhsArgs.size() != rhsArgs.size())
  7118. return false;
  7119. ObjCTypeParamList *typeParams = iface->getTypeParamList();
  7120. for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
  7121. if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
  7122. continue;
  7123. switch (typeParams->begin()[i]->getVariance()) {
  7124. case ObjCTypeParamVariance::Invariant:
  7125. if (!stripKindOf ||
  7126. !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
  7127. rhsArgs[i].stripObjCKindOfType(ctx))) {
  7128. return false;
  7129. }
  7130. break;
  7131. case ObjCTypeParamVariance::Covariant:
  7132. if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
  7133. return false;
  7134. break;
  7135. case ObjCTypeParamVariance::Contravariant:
  7136. if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
  7137. return false;
  7138. break;
  7139. }
  7140. }
  7141. return true;
  7142. }
  7143. QualType ASTContext::areCommonBaseCompatible(
  7144. const ObjCObjectPointerType *Lptr,
  7145. const ObjCObjectPointerType *Rptr) {
  7146. const ObjCObjectType *LHS = Lptr->getObjectType();
  7147. const ObjCObjectType *RHS = Rptr->getObjectType();
  7148. const ObjCInterfaceDecl* LDecl = LHS->getInterface();
  7149. const ObjCInterfaceDecl* RDecl = RHS->getInterface();
  7150. if (!LDecl || !RDecl)
  7151. return {};
  7152. // When either LHS or RHS is a kindof type, we should return a kindof type.
  7153. // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
  7154. // kindof(A).
  7155. bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
  7156. // Follow the left-hand side up the class hierarchy until we either hit a
  7157. // root or find the RHS. Record the ancestors in case we don't find it.
  7158. llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
  7159. LHSAncestors;
  7160. while (true) {
  7161. // Record this ancestor. We'll need this if the common type isn't in the
  7162. // path from the LHS to the root.
  7163. LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
  7164. if (declaresSameEntity(LHS->getInterface(), RDecl)) {
  7165. // Get the type arguments.
  7166. ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
  7167. bool anyChanges = false;
  7168. if (LHS->isSpecialized() && RHS->isSpecialized()) {
  7169. // Both have type arguments, compare them.
  7170. if (!sameObjCTypeArgs(*this, LHS->getInterface(),
  7171. LHS->getTypeArgs(), RHS->getTypeArgs(),
  7172. /*stripKindOf=*/true))
  7173. return {};
  7174. } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
  7175. // If only one has type arguments, the result will not have type
  7176. // arguments.
  7177. LHSTypeArgs = {};
  7178. anyChanges = true;
  7179. }
  7180. // Compute the intersection of protocols.
  7181. SmallVector<ObjCProtocolDecl *, 8> Protocols;
  7182. getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
  7183. Protocols);
  7184. if (!Protocols.empty())
  7185. anyChanges = true;
  7186. // If anything in the LHS will have changed, build a new result type.
  7187. // If we need to return a kindof type but LHS is not a kindof type, we
  7188. // build a new result type.
  7189. if (anyChanges || LHS->isKindOfType() != anyKindOf) {
  7190. QualType Result = getObjCInterfaceType(LHS->getInterface());
  7191. Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
  7192. anyKindOf || LHS->isKindOfType());
  7193. return getObjCObjectPointerType(Result);
  7194. }
  7195. return getObjCObjectPointerType(QualType(LHS, 0));
  7196. }
  7197. // Find the superclass.
  7198. QualType LHSSuperType = LHS->getSuperClassType();
  7199. if (LHSSuperType.isNull())
  7200. break;
  7201. LHS = LHSSuperType->castAs<ObjCObjectType>();
  7202. }
  7203. // We didn't find anything by following the LHS to its root; now check
  7204. // the RHS against the cached set of ancestors.
  7205. while (true) {
  7206. auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
  7207. if (KnownLHS != LHSAncestors.end()) {
  7208. LHS = KnownLHS->second;
  7209. // Get the type arguments.
  7210. ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
  7211. bool anyChanges = false;
  7212. if (LHS->isSpecialized() && RHS->isSpecialized()) {
  7213. // Both have type arguments, compare them.
  7214. if (!sameObjCTypeArgs(*this, LHS->getInterface(),
  7215. LHS->getTypeArgs(), RHS->getTypeArgs(),
  7216. /*stripKindOf=*/true))
  7217. return {};
  7218. } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
  7219. // If only one has type arguments, the result will not have type
  7220. // arguments.
  7221. RHSTypeArgs = {};
  7222. anyChanges = true;
  7223. }
  7224. // Compute the intersection of protocols.
  7225. SmallVector<ObjCProtocolDecl *, 8> Protocols;
  7226. getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
  7227. Protocols);
  7228. if (!Protocols.empty())
  7229. anyChanges = true;
  7230. // If we need to return a kindof type but RHS is not a kindof type, we
  7231. // build a new result type.
  7232. if (anyChanges || RHS->isKindOfType() != anyKindOf) {
  7233. QualType Result = getObjCInterfaceType(RHS->getInterface());
  7234. Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
  7235. anyKindOf || RHS->isKindOfType());
  7236. return getObjCObjectPointerType(Result);
  7237. }
  7238. return getObjCObjectPointerType(QualType(RHS, 0));
  7239. }
  7240. // Find the superclass of the RHS.
  7241. QualType RHSSuperType = RHS->getSuperClassType();
  7242. if (RHSSuperType.isNull())
  7243. break;
  7244. RHS = RHSSuperType->castAs<ObjCObjectType>();
  7245. }
  7246. return {};
  7247. }
  7248. bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
  7249. const ObjCObjectType *RHS) {
  7250. assert(LHS->getInterface() && "LHS is not an interface type");
  7251. assert(RHS->getInterface() && "RHS is not an interface type");
  7252. // Verify that the base decls are compatible: the RHS must be a subclass of
  7253. // the LHS.
  7254. ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
  7255. bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
  7256. if (!IsSuperClass)
  7257. return false;
  7258. // If the LHS has protocol qualifiers, determine whether all of them are
  7259. // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
  7260. // LHS).
  7261. if (LHS->getNumProtocols() > 0) {
  7262. // OK if conversion of LHS to SuperClass results in narrowing of types
  7263. // ; i.e., SuperClass may implement at least one of the protocols
  7264. // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
  7265. // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
  7266. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
  7267. CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
  7268. // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
  7269. // qualifiers.
  7270. for (auto *RHSPI : RHS->quals())
  7271. CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
  7272. // If there is no protocols associated with RHS, it is not a match.
  7273. if (SuperClassInheritedProtocols.empty())
  7274. return false;
  7275. for (const auto *LHSProto : LHS->quals()) {
  7276. bool SuperImplementsProtocol = false;
  7277. for (auto *SuperClassProto : SuperClassInheritedProtocols)
  7278. if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
  7279. SuperImplementsProtocol = true;
  7280. break;
  7281. }
  7282. if (!SuperImplementsProtocol)
  7283. return false;
  7284. }
  7285. }
  7286. // If the LHS is specialized, we may need to check type arguments.
  7287. if (LHS->isSpecialized()) {
  7288. // Follow the superclass chain until we've matched the LHS class in the
  7289. // hierarchy. This substitutes type arguments through.
  7290. const ObjCObjectType *RHSSuper = RHS;
  7291. while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
  7292. RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
  7293. // If the RHS is specializd, compare type arguments.
  7294. if (RHSSuper->isSpecialized() &&
  7295. !sameObjCTypeArgs(*this, LHS->getInterface(),
  7296. LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
  7297. /*stripKindOf=*/true)) {
  7298. return false;
  7299. }
  7300. }
  7301. return true;
  7302. }
  7303. bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
  7304. // get the "pointed to" types
  7305. const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
  7306. const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
  7307. if (!LHSOPT || !RHSOPT)
  7308. return false;
  7309. return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
  7310. canAssignObjCInterfaces(RHSOPT, LHSOPT);
  7311. }
  7312. bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
  7313. return canAssignObjCInterfaces(
  7314. getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
  7315. getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
  7316. }
  7317. /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
  7318. /// both shall have the identically qualified version of a compatible type.
  7319. /// C99 6.2.7p1: Two types have compatible types if their types are the
  7320. /// same. See 6.7.[2,3,5] for additional rules.
  7321. bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
  7322. bool CompareUnqualified) {
  7323. if (getLangOpts().CPlusPlus)
  7324. return hasSameType(LHS, RHS);
  7325. return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
  7326. }
  7327. bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
  7328. return typesAreCompatible(LHS, RHS);
  7329. }
  7330. bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
  7331. return !mergeTypes(LHS, RHS, true).isNull();
  7332. }
  7333. /// mergeTransparentUnionType - if T is a transparent union type and a member
  7334. /// of T is compatible with SubType, return the merged type, else return
  7335. /// QualType()
  7336. QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
  7337. bool OfBlockPointer,
  7338. bool Unqualified) {
  7339. if (const RecordType *UT = T->getAsUnionType()) {
  7340. RecordDecl *UD = UT->getDecl();
  7341. if (UD->hasAttr<TransparentUnionAttr>()) {
  7342. for (const auto *I : UD->fields()) {
  7343. QualType ET = I->getType().getUnqualifiedType();
  7344. QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
  7345. if (!MT.isNull())
  7346. return MT;
  7347. }
  7348. }
  7349. }
  7350. return {};
  7351. }
  7352. /// mergeFunctionParameterTypes - merge two types which appear as function
  7353. /// parameter types
  7354. QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
  7355. bool OfBlockPointer,
  7356. bool Unqualified) {
  7357. // GNU extension: two types are compatible if they appear as a function
  7358. // argument, one of the types is a transparent union type and the other
  7359. // type is compatible with a union member
  7360. QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
  7361. Unqualified);
  7362. if (!lmerge.isNull())
  7363. return lmerge;
  7364. QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
  7365. Unqualified);
  7366. if (!rmerge.isNull())
  7367. return rmerge;
  7368. return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
  7369. }
  7370. QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
  7371. bool OfBlockPointer,
  7372. bool Unqualified) {
  7373. const auto *lbase = lhs->getAs<FunctionType>();
  7374. const auto *rbase = rhs->getAs<FunctionType>();
  7375. const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
  7376. const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
  7377. bool allLTypes = true;
  7378. bool allRTypes = true;
  7379. // Check return type
  7380. QualType retType;
  7381. if (OfBlockPointer) {
  7382. QualType RHS = rbase->getReturnType();
  7383. QualType LHS = lbase->getReturnType();
  7384. bool UnqualifiedResult = Unqualified;
  7385. if (!UnqualifiedResult)
  7386. UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
  7387. retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
  7388. }
  7389. else
  7390. retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
  7391. Unqualified);
  7392. if (retType.isNull())
  7393. return {};
  7394. if (Unqualified)
  7395. retType = retType.getUnqualifiedType();
  7396. CanQualType LRetType = getCanonicalType(lbase->getReturnType());
  7397. CanQualType RRetType = getCanonicalType(rbase->getReturnType());
  7398. if (Unqualified) {
  7399. LRetType = LRetType.getUnqualifiedType();
  7400. RRetType = RRetType.getUnqualifiedType();
  7401. }
  7402. if (getCanonicalType(retType) != LRetType)
  7403. allLTypes = false;
  7404. if (getCanonicalType(retType) != RRetType)
  7405. allRTypes = false;
  7406. // FIXME: double check this
  7407. // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
  7408. // rbase->getRegParmAttr() != 0 &&
  7409. // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
  7410. FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
  7411. FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
  7412. // Compatible functions must have compatible calling conventions
  7413. if (lbaseInfo.getCC() != rbaseInfo.getCC())
  7414. return {};
  7415. // Regparm is part of the calling convention.
  7416. if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
  7417. return {};
  7418. if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
  7419. return {};
  7420. if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
  7421. return {};
  7422. if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
  7423. return {};
  7424. if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
  7425. return {};
  7426. // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
  7427. bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
  7428. if (lbaseInfo.getNoReturn() != NoReturn)
  7429. allLTypes = false;
  7430. if (rbaseInfo.getNoReturn() != NoReturn)
  7431. allRTypes = false;
  7432. FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
  7433. if (lproto && rproto) { // two C99 style function prototypes
  7434. assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
  7435. "C++ shouldn't be here");
  7436. // Compatible functions must have the same number of parameters
  7437. if (lproto->getNumParams() != rproto->getNumParams())
  7438. return {};
  7439. // Variadic and non-variadic functions aren't compatible
  7440. if (lproto->isVariadic() != rproto->isVariadic())
  7441. return {};
  7442. if (lproto->getMethodQuals() != rproto->getMethodQuals())
  7443. return {};
  7444. SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
  7445. bool canUseLeft, canUseRight;
  7446. if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
  7447. newParamInfos))
  7448. return {};
  7449. if (!canUseLeft)
  7450. allLTypes = false;
  7451. if (!canUseRight)
  7452. allRTypes = false;
  7453. // Check parameter type compatibility
  7454. SmallVector<QualType, 10> types;
  7455. for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
  7456. QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
  7457. QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
  7458. QualType paramType = mergeFunctionParameterTypes(
  7459. lParamType, rParamType, OfBlockPointer, Unqualified);
  7460. if (paramType.isNull())
  7461. return {};
  7462. if (Unqualified)
  7463. paramType = paramType.getUnqualifiedType();
  7464. types.push_back(paramType);
  7465. if (Unqualified) {
  7466. lParamType = lParamType.getUnqualifiedType();
  7467. rParamType = rParamType.getUnqualifiedType();
  7468. }
  7469. if (getCanonicalType(paramType) != getCanonicalType(lParamType))
  7470. allLTypes = false;
  7471. if (getCanonicalType(paramType) != getCanonicalType(rParamType))
  7472. allRTypes = false;
  7473. }
  7474. if (allLTypes) return lhs;
  7475. if (allRTypes) return rhs;
  7476. FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
  7477. EPI.ExtInfo = einfo;
  7478. EPI.ExtParameterInfos =
  7479. newParamInfos.empty() ? nullptr : newParamInfos.data();
  7480. return getFunctionType(retType, types, EPI);
  7481. }
  7482. if (lproto) allRTypes = false;
  7483. if (rproto) allLTypes = false;
  7484. const FunctionProtoType *proto = lproto ? lproto : rproto;
  7485. if (proto) {
  7486. assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
  7487. if (proto->isVariadic())
  7488. return {};
  7489. // Check that the types are compatible with the types that
  7490. // would result from default argument promotions (C99 6.7.5.3p15).
  7491. // The only types actually affected are promotable integer
  7492. // types and floats, which would be passed as a different
  7493. // type depending on whether the prototype is visible.
  7494. for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
  7495. QualType paramTy = proto->getParamType(i);
  7496. // Look at the converted type of enum types, since that is the type used
  7497. // to pass enum values.
  7498. if (const auto *Enum = paramTy->getAs<EnumType>()) {
  7499. paramTy = Enum->getDecl()->getIntegerType();
  7500. if (paramTy.isNull())
  7501. return {};
  7502. }
  7503. if (paramTy->isPromotableIntegerType() ||
  7504. getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
  7505. return {};
  7506. }
  7507. if (allLTypes) return lhs;
  7508. if (allRTypes) return rhs;
  7509. FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
  7510. EPI.ExtInfo = einfo;
  7511. return getFunctionType(retType, proto->getParamTypes(), EPI);
  7512. }
  7513. if (allLTypes) return lhs;
  7514. if (allRTypes) return rhs;
  7515. return getFunctionNoProtoType(retType, einfo);
  7516. }
  7517. /// Given that we have an enum type and a non-enum type, try to merge them.
  7518. static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
  7519. QualType other, bool isBlockReturnType) {
  7520. // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
  7521. // a signed integer type, or an unsigned integer type.
  7522. // Compatibility is based on the underlying type, not the promotion
  7523. // type.
  7524. QualType underlyingType = ET->getDecl()->getIntegerType();
  7525. if (underlyingType.isNull())
  7526. return {};
  7527. if (Context.hasSameType(underlyingType, other))
  7528. return other;
  7529. // In block return types, we're more permissive and accept any
  7530. // integral type of the same size.
  7531. if (isBlockReturnType && other->isIntegerType() &&
  7532. Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
  7533. return other;
  7534. return {};
  7535. }
  7536. QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
  7537. bool OfBlockPointer,
  7538. bool Unqualified, bool BlockReturnType) {
  7539. // C++ [expr]: If an expression initially has the type "reference to T", the
  7540. // type is adjusted to "T" prior to any further analysis, the expression
  7541. // designates the object or function denoted by the reference, and the
  7542. // expression is an lvalue unless the reference is an rvalue reference and
  7543. // the expression is a function call (possibly inside parentheses).
  7544. assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
  7545. assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
  7546. if (Unqualified) {
  7547. LHS = LHS.getUnqualifiedType();
  7548. RHS = RHS.getUnqualifiedType();
  7549. }
  7550. QualType LHSCan = getCanonicalType(LHS),
  7551. RHSCan = getCanonicalType(RHS);
  7552. // If two types are identical, they are compatible.
  7553. if (LHSCan == RHSCan)
  7554. return LHS;
  7555. // If the qualifiers are different, the types aren't compatible... mostly.
  7556. Qualifiers LQuals = LHSCan.getLocalQualifiers();
  7557. Qualifiers RQuals = RHSCan.getLocalQualifiers();
  7558. if (LQuals != RQuals) {
  7559. // If any of these qualifiers are different, we have a type
  7560. // mismatch.
  7561. if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
  7562. LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
  7563. LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
  7564. LQuals.hasUnaligned() != RQuals.hasUnaligned())
  7565. return {};
  7566. // Exactly one GC qualifier difference is allowed: __strong is
  7567. // okay if the other type has no GC qualifier but is an Objective
  7568. // C object pointer (i.e. implicitly strong by default). We fix
  7569. // this by pretending that the unqualified type was actually
  7570. // qualified __strong.
  7571. Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
  7572. Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
  7573. assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
  7574. if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
  7575. return {};
  7576. if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
  7577. return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
  7578. }
  7579. if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
  7580. return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
  7581. }
  7582. return {};
  7583. }
  7584. // Okay, qualifiers are equal.
  7585. Type::TypeClass LHSClass = LHSCan->getTypeClass();
  7586. Type::TypeClass RHSClass = RHSCan->getTypeClass();
  7587. // We want to consider the two function types to be the same for these
  7588. // comparisons, just force one to the other.
  7589. if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
  7590. if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
  7591. // Same as above for arrays
  7592. if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
  7593. LHSClass = Type::ConstantArray;
  7594. if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
  7595. RHSClass = Type::ConstantArray;
  7596. // ObjCInterfaces are just specialized ObjCObjects.
  7597. if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
  7598. if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
  7599. // Canonicalize ExtVector -> Vector.
  7600. if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
  7601. if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
  7602. // If the canonical type classes don't match.
  7603. if (LHSClass != RHSClass) {
  7604. // Note that we only have special rules for turning block enum
  7605. // returns into block int returns, not vice-versa.
  7606. if (const auto *ETy = LHS->getAs<EnumType>()) {
  7607. return mergeEnumWithInteger(*this, ETy, RHS, false);
  7608. }
  7609. if (const EnumType* ETy = RHS->getAs<EnumType>()) {
  7610. return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
  7611. }
  7612. // allow block pointer type to match an 'id' type.
  7613. if (OfBlockPointer && !BlockReturnType) {
  7614. if (LHS->isObjCIdType() && RHS->isBlockPointerType())
  7615. return LHS;
  7616. if (RHS->isObjCIdType() && LHS->isBlockPointerType())
  7617. return RHS;
  7618. }
  7619. return {};
  7620. }
  7621. // The canonical type classes match.
  7622. switch (LHSClass) {
  7623. #define TYPE(Class, Base)
  7624. #define ABSTRACT_TYPE(Class, Base)
  7625. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
  7626. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  7627. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  7628. #include "clang/AST/TypeNodes.def"
  7629. llvm_unreachable("Non-canonical and dependent types shouldn't get here");
  7630. case Type::Auto:
  7631. case Type::DeducedTemplateSpecialization:
  7632. case Type::LValueReference:
  7633. case Type::RValueReference:
  7634. case Type::MemberPointer:
  7635. llvm_unreachable("C++ should never be in mergeTypes");
  7636. case Type::ObjCInterface:
  7637. case Type::IncompleteArray:
  7638. case Type::VariableArray:
  7639. case Type::FunctionProto:
  7640. case Type::ExtVector:
  7641. llvm_unreachable("Types are eliminated above");
  7642. case Type::Pointer:
  7643. {
  7644. // Merge two pointer types, while trying to preserve typedef info
  7645. QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
  7646. QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
  7647. if (Unqualified) {
  7648. LHSPointee = LHSPointee.getUnqualifiedType();
  7649. RHSPointee = RHSPointee.getUnqualifiedType();
  7650. }
  7651. QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
  7652. Unqualified);
  7653. if (ResultType.isNull())
  7654. return {};
  7655. if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
  7656. return LHS;
  7657. if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
  7658. return RHS;
  7659. return getPointerType(ResultType);
  7660. }
  7661. case Type::BlockPointer:
  7662. {
  7663. // Merge two block pointer types, while trying to preserve typedef info
  7664. QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
  7665. QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
  7666. if (Unqualified) {
  7667. LHSPointee = LHSPointee.getUnqualifiedType();
  7668. RHSPointee = RHSPointee.getUnqualifiedType();
  7669. }
  7670. if (getLangOpts().OpenCL) {
  7671. Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
  7672. Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
  7673. // Blocks can't be an expression in a ternary operator (OpenCL v2.0
  7674. // 6.12.5) thus the following check is asymmetric.
  7675. if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
  7676. return {};
  7677. LHSPteeQual.removeAddressSpace();
  7678. RHSPteeQual.removeAddressSpace();
  7679. LHSPointee =
  7680. QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
  7681. RHSPointee =
  7682. QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
  7683. }
  7684. QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
  7685. Unqualified);
  7686. if (ResultType.isNull())
  7687. return {};
  7688. if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
  7689. return LHS;
  7690. if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
  7691. return RHS;
  7692. return getBlockPointerType(ResultType);
  7693. }
  7694. case Type::Atomic:
  7695. {
  7696. // Merge two pointer types, while trying to preserve typedef info
  7697. QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
  7698. QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
  7699. if (Unqualified) {
  7700. LHSValue = LHSValue.getUnqualifiedType();
  7701. RHSValue = RHSValue.getUnqualifiedType();
  7702. }
  7703. QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
  7704. Unqualified);
  7705. if (ResultType.isNull())
  7706. return {};
  7707. if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
  7708. return LHS;
  7709. if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
  7710. return RHS;
  7711. return getAtomicType(ResultType);
  7712. }
  7713. case Type::ConstantArray:
  7714. {
  7715. const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
  7716. const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
  7717. if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
  7718. return {};
  7719. QualType LHSElem = getAsArrayType(LHS)->getElementType();
  7720. QualType RHSElem = getAsArrayType(RHS)->getElementType();
  7721. if (Unqualified) {
  7722. LHSElem = LHSElem.getUnqualifiedType();
  7723. RHSElem = RHSElem.getUnqualifiedType();
  7724. }
  7725. QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
  7726. if (ResultType.isNull())
  7727. return {};
  7728. const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
  7729. const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
  7730. // If either side is a variable array, and both are complete, check whether
  7731. // the current dimension is definite.
  7732. if (LVAT || RVAT) {
  7733. auto SizeFetch = [this](const VariableArrayType* VAT,
  7734. const ConstantArrayType* CAT)
  7735. -> std::pair<bool,llvm::APInt> {
  7736. if (VAT) {
  7737. llvm::APSInt TheInt;
  7738. Expr *E = VAT->getSizeExpr();
  7739. if (E && E->isIntegerConstantExpr(TheInt, *this))
  7740. return std::make_pair(true, TheInt);
  7741. else
  7742. return std::make_pair(false, TheInt);
  7743. } else if (CAT) {
  7744. return std::make_pair(true, CAT->getSize());
  7745. } else {
  7746. return std::make_pair(false, llvm::APInt());
  7747. }
  7748. };
  7749. bool HaveLSize, HaveRSize;
  7750. llvm::APInt LSize, RSize;
  7751. std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
  7752. std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
  7753. if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
  7754. return {}; // Definite, but unequal, array dimension
  7755. }
  7756. if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
  7757. return LHS;
  7758. if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
  7759. return RHS;
  7760. if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
  7761. ArrayType::ArraySizeModifier(), 0);
  7762. if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
  7763. ArrayType::ArraySizeModifier(), 0);
  7764. if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
  7765. return LHS;
  7766. if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
  7767. return RHS;
  7768. if (LVAT) {
  7769. // FIXME: This isn't correct! But tricky to implement because
  7770. // the array's size has to be the size of LHS, but the type
  7771. // has to be different.
  7772. return LHS;
  7773. }
  7774. if (RVAT) {
  7775. // FIXME: This isn't correct! But tricky to implement because
  7776. // the array's size has to be the size of RHS, but the type
  7777. // has to be different.
  7778. return RHS;
  7779. }
  7780. if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
  7781. if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
  7782. return getIncompleteArrayType(ResultType,
  7783. ArrayType::ArraySizeModifier(), 0);
  7784. }
  7785. case Type::FunctionNoProto:
  7786. return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
  7787. case Type::Record:
  7788. case Type::Enum:
  7789. return {};
  7790. case Type::Builtin:
  7791. // Only exactly equal builtin types are compatible, which is tested above.
  7792. return {};
  7793. case Type::Complex:
  7794. // Distinct complex types are incompatible.
  7795. return {};
  7796. case Type::Vector:
  7797. // FIXME: The merged type should be an ExtVector!
  7798. if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
  7799. RHSCan->getAs<VectorType>()))
  7800. return LHS;
  7801. return {};
  7802. case Type::ObjCObject: {
  7803. // Check if the types are assignment compatible.
  7804. // FIXME: This should be type compatibility, e.g. whether
  7805. // "LHS x; RHS x;" at global scope is legal.
  7806. const auto *LHSIface = LHS->getAs<ObjCObjectType>();
  7807. const auto *RHSIface = RHS->getAs<ObjCObjectType>();
  7808. if (canAssignObjCInterfaces(LHSIface, RHSIface))
  7809. return LHS;
  7810. return {};
  7811. }
  7812. case Type::ObjCObjectPointer:
  7813. if (OfBlockPointer) {
  7814. if (canAssignObjCInterfacesInBlockPointer(
  7815. LHS->getAs<ObjCObjectPointerType>(),
  7816. RHS->getAs<ObjCObjectPointerType>(),
  7817. BlockReturnType))
  7818. return LHS;
  7819. return {};
  7820. }
  7821. if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
  7822. RHS->getAs<ObjCObjectPointerType>()))
  7823. return LHS;
  7824. return {};
  7825. case Type::Pipe:
  7826. assert(LHS != RHS &&
  7827. "Equivalent pipe types should have already been handled!");
  7828. return {};
  7829. }
  7830. llvm_unreachable("Invalid Type::Class!");
  7831. }
  7832. bool ASTContext::mergeExtParameterInfo(
  7833. const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
  7834. bool &CanUseFirst, bool &CanUseSecond,
  7835. SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
  7836. assert(NewParamInfos.empty() && "param info list not empty");
  7837. CanUseFirst = CanUseSecond = true;
  7838. bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
  7839. bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
  7840. // Fast path: if the first type doesn't have ext parameter infos,
  7841. // we match if and only if the second type also doesn't have them.
  7842. if (!FirstHasInfo && !SecondHasInfo)
  7843. return true;
  7844. bool NeedParamInfo = false;
  7845. size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
  7846. : SecondFnType->getExtParameterInfos().size();
  7847. for (size_t I = 0; I < E; ++I) {
  7848. FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
  7849. if (FirstHasInfo)
  7850. FirstParam = FirstFnType->getExtParameterInfo(I);
  7851. if (SecondHasInfo)
  7852. SecondParam = SecondFnType->getExtParameterInfo(I);
  7853. // Cannot merge unless everything except the noescape flag matches.
  7854. if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
  7855. return false;
  7856. bool FirstNoEscape = FirstParam.isNoEscape();
  7857. bool SecondNoEscape = SecondParam.isNoEscape();
  7858. bool IsNoEscape = FirstNoEscape && SecondNoEscape;
  7859. NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
  7860. if (NewParamInfos.back().getOpaqueValue())
  7861. NeedParamInfo = true;
  7862. if (FirstNoEscape != IsNoEscape)
  7863. CanUseFirst = false;
  7864. if (SecondNoEscape != IsNoEscape)
  7865. CanUseSecond = false;
  7866. }
  7867. if (!NeedParamInfo)
  7868. NewParamInfos.clear();
  7869. return true;
  7870. }
  7871. void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
  7872. ObjCLayouts[CD] = nullptr;
  7873. }
  7874. /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
  7875. /// 'RHS' attributes and returns the merged version; including for function
  7876. /// return types.
  7877. QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
  7878. QualType LHSCan = getCanonicalType(LHS),
  7879. RHSCan = getCanonicalType(RHS);
  7880. // If two types are identical, they are compatible.
  7881. if (LHSCan == RHSCan)
  7882. return LHS;
  7883. if (RHSCan->isFunctionType()) {
  7884. if (!LHSCan->isFunctionType())
  7885. return {};
  7886. QualType OldReturnType =
  7887. cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
  7888. QualType NewReturnType =
  7889. cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
  7890. QualType ResReturnType =
  7891. mergeObjCGCQualifiers(NewReturnType, OldReturnType);
  7892. if (ResReturnType.isNull())
  7893. return {};
  7894. if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
  7895. // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
  7896. // In either case, use OldReturnType to build the new function type.
  7897. const auto *F = LHS->getAs<FunctionType>();
  7898. if (const auto *FPT = cast<FunctionProtoType>(F)) {
  7899. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  7900. EPI.ExtInfo = getFunctionExtInfo(LHS);
  7901. QualType ResultType =
  7902. getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
  7903. return ResultType;
  7904. }
  7905. }
  7906. return {};
  7907. }
  7908. // If the qualifiers are different, the types can still be merged.
  7909. Qualifiers LQuals = LHSCan.getLocalQualifiers();
  7910. Qualifiers RQuals = RHSCan.getLocalQualifiers();
  7911. if (LQuals != RQuals) {
  7912. // If any of these qualifiers are different, we have a type mismatch.
  7913. if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
  7914. LQuals.getAddressSpace() != RQuals.getAddressSpace())
  7915. return {};
  7916. // Exactly one GC qualifier difference is allowed: __strong is
  7917. // okay if the other type has no GC qualifier but is an Objective
  7918. // C object pointer (i.e. implicitly strong by default). We fix
  7919. // this by pretending that the unqualified type was actually
  7920. // qualified __strong.
  7921. Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
  7922. Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
  7923. assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
  7924. if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
  7925. return {};
  7926. if (GC_L == Qualifiers::Strong)
  7927. return LHS;
  7928. if (GC_R == Qualifiers::Strong)
  7929. return RHS;
  7930. return {};
  7931. }
  7932. if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
  7933. QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
  7934. QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
  7935. QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
  7936. if (ResQT == LHSBaseQT)
  7937. return LHS;
  7938. if (ResQT == RHSBaseQT)
  7939. return RHS;
  7940. }
  7941. return {};
  7942. }
  7943. //===----------------------------------------------------------------------===//
  7944. // Integer Predicates
  7945. //===----------------------------------------------------------------------===//
  7946. unsigned ASTContext::getIntWidth(QualType T) const {
  7947. if (const auto *ET = T->getAs<EnumType>())
  7948. T = ET->getDecl()->getIntegerType();
  7949. if (T->isBooleanType())
  7950. return 1;
  7951. // For builtin types, just use the standard type sizing method
  7952. return (unsigned)getTypeSize(T);
  7953. }
  7954. QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
  7955. assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
  7956. "Unexpected type");
  7957. // Turn <4 x signed int> -> <4 x unsigned int>
  7958. if (const auto *VTy = T->getAs<VectorType>())
  7959. return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
  7960. VTy->getNumElements(), VTy->getVectorKind());
  7961. // For enums, we return the unsigned version of the base type.
  7962. if (const auto *ETy = T->getAs<EnumType>())
  7963. T = ETy->getDecl()->getIntegerType();
  7964. const auto *BTy = T->getAs<BuiltinType>();
  7965. assert(BTy && "Unexpected signed integer or fixed point type");
  7966. switch (BTy->getKind()) {
  7967. case BuiltinType::Char_S:
  7968. case BuiltinType::SChar:
  7969. return UnsignedCharTy;
  7970. case BuiltinType::Short:
  7971. return UnsignedShortTy;
  7972. case BuiltinType::Int:
  7973. return UnsignedIntTy;
  7974. case BuiltinType::Long:
  7975. return UnsignedLongTy;
  7976. case BuiltinType::LongLong:
  7977. return UnsignedLongLongTy;
  7978. case BuiltinType::Int128:
  7979. return UnsignedInt128Ty;
  7980. case BuiltinType::ShortAccum:
  7981. return UnsignedShortAccumTy;
  7982. case BuiltinType::Accum:
  7983. return UnsignedAccumTy;
  7984. case BuiltinType::LongAccum:
  7985. return UnsignedLongAccumTy;
  7986. case BuiltinType::SatShortAccum:
  7987. return SatUnsignedShortAccumTy;
  7988. case BuiltinType::SatAccum:
  7989. return SatUnsignedAccumTy;
  7990. case BuiltinType::SatLongAccum:
  7991. return SatUnsignedLongAccumTy;
  7992. case BuiltinType::ShortFract:
  7993. return UnsignedShortFractTy;
  7994. case BuiltinType::Fract:
  7995. return UnsignedFractTy;
  7996. case BuiltinType::LongFract:
  7997. return UnsignedLongFractTy;
  7998. case BuiltinType::SatShortFract:
  7999. return SatUnsignedShortFractTy;
  8000. case BuiltinType::SatFract:
  8001. return SatUnsignedFractTy;
  8002. case BuiltinType::SatLongFract:
  8003. return SatUnsignedLongFractTy;
  8004. default:
  8005. llvm_unreachable("Unexpected signed integer or fixed point type");
  8006. }
  8007. }
  8008. ASTMutationListener::~ASTMutationListener() = default;
  8009. void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
  8010. QualType ReturnType) {}
  8011. //===----------------------------------------------------------------------===//
  8012. // Builtin Type Computation
  8013. //===----------------------------------------------------------------------===//
  8014. /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
  8015. /// pointer over the consumed characters. This returns the resultant type. If
  8016. /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
  8017. /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
  8018. /// a vector of "i*".
  8019. ///
  8020. /// RequiresICE is filled in on return to indicate whether the value is required
  8021. /// to be an Integer Constant Expression.
  8022. static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
  8023. ASTContext::GetBuiltinTypeError &Error,
  8024. bool &RequiresICE,
  8025. bool AllowTypeModifiers) {
  8026. // Modifiers.
  8027. int HowLong = 0;
  8028. bool Signed = false, Unsigned = false;
  8029. RequiresICE = false;
  8030. // Read the prefixed modifiers first.
  8031. bool Done = false;
  8032. #ifndef NDEBUG
  8033. bool IsSpecialLong = false;
  8034. #endif
  8035. while (!Done) {
  8036. switch (*Str++) {
  8037. default: Done = true; --Str; break;
  8038. case 'I':
  8039. RequiresICE = true;
  8040. break;
  8041. case 'S':
  8042. assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
  8043. assert(!Signed && "Can't use 'S' modifier multiple times!");
  8044. Signed = true;
  8045. break;
  8046. case 'U':
  8047. assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
  8048. assert(!Unsigned && "Can't use 'U' modifier multiple times!");
  8049. Unsigned = true;
  8050. break;
  8051. case 'L':
  8052. assert(!IsSpecialLong && "Can't use 'L' with 'W' or 'N' modifiers");
  8053. assert(HowLong <= 2 && "Can't have LLLL modifier");
  8054. ++HowLong;
  8055. break;
  8056. case 'N':
  8057. // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
  8058. assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
  8059. assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
  8060. #ifndef NDEBUG
  8061. IsSpecialLong = true;
  8062. #endif
  8063. if (Context.getTargetInfo().getLongWidth() == 32)
  8064. ++HowLong;
  8065. break;
  8066. case 'W':
  8067. // This modifier represents int64 type.
  8068. assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
  8069. assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
  8070. #ifndef NDEBUG
  8071. IsSpecialLong = true;
  8072. #endif
  8073. switch (Context.getTargetInfo().getInt64Type()) {
  8074. default:
  8075. llvm_unreachable("Unexpected integer type");
  8076. case TargetInfo::SignedLong:
  8077. HowLong = 1;
  8078. break;
  8079. case TargetInfo::SignedLongLong:
  8080. HowLong = 2;
  8081. break;
  8082. }
  8083. break;
  8084. }
  8085. }
  8086. QualType Type;
  8087. // Read the base type.
  8088. switch (*Str++) {
  8089. default: llvm_unreachable("Unknown builtin type letter!");
  8090. case 'v':
  8091. assert(HowLong == 0 && !Signed && !Unsigned &&
  8092. "Bad modifiers used with 'v'!");
  8093. Type = Context.VoidTy;
  8094. break;
  8095. case 'h':
  8096. assert(HowLong == 0 && !Signed && !Unsigned &&
  8097. "Bad modifiers used with 'h'!");
  8098. Type = Context.HalfTy;
  8099. break;
  8100. case 'f':
  8101. assert(HowLong == 0 && !Signed && !Unsigned &&
  8102. "Bad modifiers used with 'f'!");
  8103. Type = Context.FloatTy;
  8104. break;
  8105. case 'd':
  8106. assert(HowLong < 3 && !Signed && !Unsigned &&
  8107. "Bad modifiers used with 'd'!");
  8108. if (HowLong == 1)
  8109. Type = Context.LongDoubleTy;
  8110. else if (HowLong == 2)
  8111. Type = Context.Float128Ty;
  8112. else
  8113. Type = Context.DoubleTy;
  8114. break;
  8115. case 's':
  8116. assert(HowLong == 0 && "Bad modifiers used with 's'!");
  8117. if (Unsigned)
  8118. Type = Context.UnsignedShortTy;
  8119. else
  8120. Type = Context.ShortTy;
  8121. break;
  8122. case 'i':
  8123. if (HowLong == 3)
  8124. Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
  8125. else if (HowLong == 2)
  8126. Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
  8127. else if (HowLong == 1)
  8128. Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
  8129. else
  8130. Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
  8131. break;
  8132. case 'c':
  8133. assert(HowLong == 0 && "Bad modifiers used with 'c'!");
  8134. if (Signed)
  8135. Type = Context.SignedCharTy;
  8136. else if (Unsigned)
  8137. Type = Context.UnsignedCharTy;
  8138. else
  8139. Type = Context.CharTy;
  8140. break;
  8141. case 'b': // boolean
  8142. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
  8143. Type = Context.BoolTy;
  8144. break;
  8145. case 'z': // size_t.
  8146. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
  8147. Type = Context.getSizeType();
  8148. break;
  8149. case 'w': // wchar_t.
  8150. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
  8151. Type = Context.getWideCharType();
  8152. break;
  8153. case 'F':
  8154. Type = Context.getCFConstantStringType();
  8155. break;
  8156. case 'G':
  8157. Type = Context.getObjCIdType();
  8158. break;
  8159. case 'H':
  8160. Type = Context.getObjCSelType();
  8161. break;
  8162. case 'M':
  8163. Type = Context.getObjCSuperType();
  8164. break;
  8165. case 'a':
  8166. Type = Context.getBuiltinVaListType();
  8167. assert(!Type.isNull() && "builtin va list type not initialized!");
  8168. break;
  8169. case 'A':
  8170. // This is a "reference" to a va_list; however, what exactly
  8171. // this means depends on how va_list is defined. There are two
  8172. // different kinds of va_list: ones passed by value, and ones
  8173. // passed by reference. An example of a by-value va_list is
  8174. // x86, where va_list is a char*. An example of by-ref va_list
  8175. // is x86-64, where va_list is a __va_list_tag[1]. For x86,
  8176. // we want this argument to be a char*&; for x86-64, we want
  8177. // it to be a __va_list_tag*.
  8178. Type = Context.getBuiltinVaListType();
  8179. assert(!Type.isNull() && "builtin va list type not initialized!");
  8180. if (Type->isArrayType())
  8181. Type = Context.getArrayDecayedType(Type);
  8182. else
  8183. Type = Context.getLValueReferenceType(Type);
  8184. break;
  8185. case 'V': {
  8186. char *End;
  8187. unsigned NumElements = strtoul(Str, &End, 10);
  8188. assert(End != Str && "Missing vector size");
  8189. Str = End;
  8190. QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
  8191. RequiresICE, false);
  8192. assert(!RequiresICE && "Can't require vector ICE");
  8193. // TODO: No way to make AltiVec vectors in builtins yet.
  8194. Type = Context.getVectorType(ElementType, NumElements,
  8195. VectorType::GenericVector);
  8196. break;
  8197. }
  8198. case 'E': {
  8199. char *End;
  8200. unsigned NumElements = strtoul(Str, &End, 10);
  8201. assert(End != Str && "Missing vector size");
  8202. Str = End;
  8203. QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
  8204. false);
  8205. Type = Context.getExtVectorType(ElementType, NumElements);
  8206. break;
  8207. }
  8208. case 'X': {
  8209. QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
  8210. false);
  8211. assert(!RequiresICE && "Can't require complex ICE");
  8212. Type = Context.getComplexType(ElementType);
  8213. break;
  8214. }
  8215. case 'Y':
  8216. Type = Context.getPointerDiffType();
  8217. break;
  8218. case 'P':
  8219. Type = Context.getFILEType();
  8220. if (Type.isNull()) {
  8221. Error = ASTContext::GE_Missing_stdio;
  8222. return {};
  8223. }
  8224. break;
  8225. case 'J':
  8226. if (Signed)
  8227. Type = Context.getsigjmp_bufType();
  8228. else
  8229. Type = Context.getjmp_bufType();
  8230. if (Type.isNull()) {
  8231. Error = ASTContext::GE_Missing_setjmp;
  8232. return {};
  8233. }
  8234. break;
  8235. case 'K':
  8236. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
  8237. Type = Context.getucontext_tType();
  8238. if (Type.isNull()) {
  8239. Error = ASTContext::GE_Missing_ucontext;
  8240. return {};
  8241. }
  8242. break;
  8243. case 'p':
  8244. Type = Context.getProcessIDType();
  8245. break;
  8246. }
  8247. // If there are modifiers and if we're allowed to parse them, go for it.
  8248. Done = !AllowTypeModifiers;
  8249. while (!Done) {
  8250. switch (char c = *Str++) {
  8251. default: Done = true; --Str; break;
  8252. case '*':
  8253. case '&': {
  8254. // Both pointers and references can have their pointee types
  8255. // qualified with an address space.
  8256. char *End;
  8257. unsigned AddrSpace = strtoul(Str, &End, 10);
  8258. if (End != Str) {
  8259. // Note AddrSpace == 0 is not the same as an unspecified address space.
  8260. Type = Context.getAddrSpaceQualType(
  8261. Type,
  8262. Context.getLangASForBuiltinAddressSpace(AddrSpace));
  8263. Str = End;
  8264. }
  8265. if (c == '*')
  8266. Type = Context.getPointerType(Type);
  8267. else
  8268. Type = Context.getLValueReferenceType(Type);
  8269. break;
  8270. }
  8271. // FIXME: There's no way to have a built-in with an rvalue ref arg.
  8272. case 'C':
  8273. Type = Type.withConst();
  8274. break;
  8275. case 'D':
  8276. Type = Context.getVolatileType(Type);
  8277. break;
  8278. case 'R':
  8279. Type = Type.withRestrict();
  8280. break;
  8281. }
  8282. }
  8283. assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
  8284. "Integer constant 'I' type must be an integer");
  8285. return Type;
  8286. }
  8287. /// GetBuiltinType - Return the type for the specified builtin.
  8288. QualType ASTContext::GetBuiltinType(unsigned Id,
  8289. GetBuiltinTypeError &Error,
  8290. unsigned *IntegerConstantArgs) const {
  8291. const char *TypeStr = BuiltinInfo.getTypeString(Id);
  8292. if (TypeStr[0] == '\0') {
  8293. Error = GE_Missing_type;
  8294. return {};
  8295. }
  8296. SmallVector<QualType, 8> ArgTypes;
  8297. bool RequiresICE = false;
  8298. Error = GE_None;
  8299. QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
  8300. RequiresICE, true);
  8301. if (Error != GE_None)
  8302. return {};
  8303. assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
  8304. while (TypeStr[0] && TypeStr[0] != '.') {
  8305. QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
  8306. if (Error != GE_None)
  8307. return {};
  8308. // If this argument is required to be an IntegerConstantExpression and the
  8309. // caller cares, fill in the bitmask we return.
  8310. if (RequiresICE && IntegerConstantArgs)
  8311. *IntegerConstantArgs |= 1 << ArgTypes.size();
  8312. // Do array -> pointer decay. The builtin should use the decayed type.
  8313. if (Ty->isArrayType())
  8314. Ty = getArrayDecayedType(Ty);
  8315. ArgTypes.push_back(Ty);
  8316. }
  8317. if (Id == Builtin::BI__GetExceptionInfo)
  8318. return {};
  8319. assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
  8320. "'.' should only occur at end of builtin type list!");
  8321. bool Variadic = (TypeStr[0] == '.');
  8322. FunctionType::ExtInfo EI(
  8323. getDefaultCallingConvention(Variadic, /*IsCXXMethod=*/false));
  8324. if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
  8325. // We really shouldn't be making a no-proto type here.
  8326. if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
  8327. return getFunctionNoProtoType(ResType, EI);
  8328. FunctionProtoType::ExtProtoInfo EPI;
  8329. EPI.ExtInfo = EI;
  8330. EPI.Variadic = Variadic;
  8331. if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
  8332. EPI.ExceptionSpec.Type =
  8333. getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
  8334. return getFunctionType(ResType, ArgTypes, EPI);
  8335. }
  8336. static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
  8337. const FunctionDecl *FD) {
  8338. if (!FD->isExternallyVisible())
  8339. return GVA_Internal;
  8340. // Non-user-provided functions get emitted as weak definitions with every
  8341. // use, no matter whether they've been explicitly instantiated etc.
  8342. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  8343. if (!MD->isUserProvided())
  8344. return GVA_DiscardableODR;
  8345. GVALinkage External;
  8346. switch (FD->getTemplateSpecializationKind()) {
  8347. case TSK_Undeclared:
  8348. case TSK_ExplicitSpecialization:
  8349. External = GVA_StrongExternal;
  8350. break;
  8351. case TSK_ExplicitInstantiationDefinition:
  8352. return GVA_StrongODR;
  8353. // C++11 [temp.explicit]p10:
  8354. // [ Note: The intent is that an inline function that is the subject of
  8355. // an explicit instantiation declaration will still be implicitly
  8356. // instantiated when used so that the body can be considered for
  8357. // inlining, but that no out-of-line copy of the inline function would be
  8358. // generated in the translation unit. -- end note ]
  8359. case TSK_ExplicitInstantiationDeclaration:
  8360. return GVA_AvailableExternally;
  8361. case TSK_ImplicitInstantiation:
  8362. External = GVA_DiscardableODR;
  8363. break;
  8364. }
  8365. if (!FD->isInlined())
  8366. return External;
  8367. if ((!Context.getLangOpts().CPlusPlus &&
  8368. !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  8369. !FD->hasAttr<DLLExportAttr>()) ||
  8370. FD->hasAttr<GNUInlineAttr>()) {
  8371. // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
  8372. // GNU or C99 inline semantics. Determine whether this symbol should be
  8373. // externally visible.
  8374. if (FD->isInlineDefinitionExternallyVisible())
  8375. return External;
  8376. // C99 inline semantics, where the symbol is not externally visible.
  8377. return GVA_AvailableExternally;
  8378. }
  8379. // Functions specified with extern and inline in -fms-compatibility mode
  8380. // forcibly get emitted. While the body of the function cannot be later
  8381. // replaced, the function definition cannot be discarded.
  8382. if (FD->isMSExternInline())
  8383. return GVA_StrongODR;
  8384. return GVA_DiscardableODR;
  8385. }
  8386. static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
  8387. const Decl *D, GVALinkage L) {
  8388. // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
  8389. // dllexport/dllimport on inline functions.
  8390. if (D->hasAttr<DLLImportAttr>()) {
  8391. if (L == GVA_DiscardableODR || L == GVA_StrongODR)
  8392. return GVA_AvailableExternally;
  8393. } else if (D->hasAttr<DLLExportAttr>()) {
  8394. if (L == GVA_DiscardableODR)
  8395. return GVA_StrongODR;
  8396. } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
  8397. D->hasAttr<CUDAGlobalAttr>()) {
  8398. // Device-side functions with __global__ attribute must always be
  8399. // visible externally so they can be launched from host.
  8400. if (L == GVA_DiscardableODR || L == GVA_Internal)
  8401. return GVA_StrongODR;
  8402. }
  8403. return L;
  8404. }
  8405. /// Adjust the GVALinkage for a declaration based on what an external AST source
  8406. /// knows about whether there can be other definitions of this declaration.
  8407. static GVALinkage
  8408. adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
  8409. GVALinkage L) {
  8410. ExternalASTSource *Source = Ctx.getExternalSource();
  8411. if (!Source)
  8412. return L;
  8413. switch (Source->hasExternalDefinitions(D)) {
  8414. case ExternalASTSource::EK_Never:
  8415. // Other translation units rely on us to provide the definition.
  8416. if (L == GVA_DiscardableODR)
  8417. return GVA_StrongODR;
  8418. break;
  8419. case ExternalASTSource::EK_Always:
  8420. return GVA_AvailableExternally;
  8421. case ExternalASTSource::EK_ReplyHazy:
  8422. break;
  8423. }
  8424. return L;
  8425. }
  8426. GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
  8427. return adjustGVALinkageForExternalDefinitionKind(*this, FD,
  8428. adjustGVALinkageForAttributes(*this, FD,
  8429. basicGVALinkageForFunction(*this, FD)));
  8430. }
  8431. static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
  8432. const VarDecl *VD) {
  8433. if (!VD->isExternallyVisible())
  8434. return GVA_Internal;
  8435. if (VD->isStaticLocal()) {
  8436. const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
  8437. while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
  8438. LexicalContext = LexicalContext->getLexicalParent();
  8439. // ObjC Blocks can create local variables that don't have a FunctionDecl
  8440. // LexicalContext.
  8441. if (!LexicalContext)
  8442. return GVA_DiscardableODR;
  8443. // Otherwise, let the static local variable inherit its linkage from the
  8444. // nearest enclosing function.
  8445. auto StaticLocalLinkage =
  8446. Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
  8447. // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
  8448. // be emitted in any object with references to the symbol for the object it
  8449. // contains, whether inline or out-of-line."
  8450. // Similar behavior is observed with MSVC. An alternative ABI could use
  8451. // StrongODR/AvailableExternally to match the function, but none are
  8452. // known/supported currently.
  8453. if (StaticLocalLinkage == GVA_StrongODR ||
  8454. StaticLocalLinkage == GVA_AvailableExternally)
  8455. return GVA_DiscardableODR;
  8456. return StaticLocalLinkage;
  8457. }
  8458. // MSVC treats in-class initialized static data members as definitions.
  8459. // By giving them non-strong linkage, out-of-line definitions won't
  8460. // cause link errors.
  8461. if (Context.isMSStaticDataMemberInlineDefinition(VD))
  8462. return GVA_DiscardableODR;
  8463. // Most non-template variables have strong linkage; inline variables are
  8464. // linkonce_odr or (occasionally, for compatibility) weak_odr.
  8465. GVALinkage StrongLinkage;
  8466. switch (Context.getInlineVariableDefinitionKind(VD)) {
  8467. case ASTContext::InlineVariableDefinitionKind::None:
  8468. StrongLinkage = GVA_StrongExternal;
  8469. break;
  8470. case ASTContext::InlineVariableDefinitionKind::Weak:
  8471. case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
  8472. StrongLinkage = GVA_DiscardableODR;
  8473. break;
  8474. case ASTContext::InlineVariableDefinitionKind::Strong:
  8475. StrongLinkage = GVA_StrongODR;
  8476. break;
  8477. }
  8478. switch (VD->getTemplateSpecializationKind()) {
  8479. case TSK_Undeclared:
  8480. return StrongLinkage;
  8481. case TSK_ExplicitSpecialization:
  8482. return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  8483. VD->isStaticDataMember()
  8484. ? GVA_StrongODR
  8485. : StrongLinkage;
  8486. case TSK_ExplicitInstantiationDefinition:
  8487. return GVA_StrongODR;
  8488. case TSK_ExplicitInstantiationDeclaration:
  8489. return GVA_AvailableExternally;
  8490. case TSK_ImplicitInstantiation:
  8491. return GVA_DiscardableODR;
  8492. }
  8493. llvm_unreachable("Invalid Linkage!");
  8494. }
  8495. GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
  8496. return adjustGVALinkageForExternalDefinitionKind(*this, VD,
  8497. adjustGVALinkageForAttributes(*this, VD,
  8498. basicGVALinkageForVariable(*this, VD)));
  8499. }
  8500. bool ASTContext::DeclMustBeEmitted(const Decl *D) {
  8501. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  8502. if (!VD->isFileVarDecl())
  8503. return false;
  8504. // Global named register variables (GNU extension) are never emitted.
  8505. if (VD->getStorageClass() == SC_Register)
  8506. return false;
  8507. if (VD->getDescribedVarTemplate() ||
  8508. isa<VarTemplatePartialSpecializationDecl>(VD))
  8509. return false;
  8510. } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  8511. // We never need to emit an uninstantiated function template.
  8512. if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  8513. return false;
  8514. } else if (isa<PragmaCommentDecl>(D))
  8515. return true;
  8516. else if (isa<PragmaDetectMismatchDecl>(D))
  8517. return true;
  8518. else if (isa<OMPThreadPrivateDecl>(D))
  8519. return !D->getDeclContext()->isDependentContext();
  8520. else if (isa<OMPAllocateDecl>(D))
  8521. return !D->getDeclContext()->isDependentContext();
  8522. else if (isa<OMPDeclareReductionDecl>(D))
  8523. return !D->getDeclContext()->isDependentContext();
  8524. else if (isa<ImportDecl>(D))
  8525. return true;
  8526. else
  8527. return false;
  8528. if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
  8529. assert(getExternalSource() && "It's from an AST file; must have a source.");
  8530. // On Windows, PCH files are built together with an object file. If this
  8531. // declaration comes from such a PCH and DeclMustBeEmitted would return
  8532. // true, it would have returned true and the decl would have been emitted
  8533. // into that object file, so it doesn't need to be emitted here.
  8534. // Note that decls are still emitted if they're referenced, as usual;
  8535. // DeclMustBeEmitted is used to decide whether a decl must be emitted even
  8536. // if it's not referenced.
  8537. //
  8538. // Explicit template instantiation definitions are tricky. If there was an
  8539. // explicit template instantiation decl in the PCH before, it will look like
  8540. // the definition comes from there, even if that was just the declaration.
  8541. // (Explicit instantiation defs of variable templates always get emitted.)
  8542. bool IsExpInstDef =
  8543. isa<FunctionDecl>(D) &&
  8544. cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
  8545. TSK_ExplicitInstantiationDefinition;
  8546. // Implicit member function definitions, such as operator= might not be
  8547. // marked as template specializations, since they're not coming from a
  8548. // template but synthesized directly on the class.
  8549. IsExpInstDef |=
  8550. isa<CXXMethodDecl>(D) &&
  8551. cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() ==
  8552. TSK_ExplicitInstantiationDefinition;
  8553. if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
  8554. return false;
  8555. }
  8556. // If this is a member of a class template, we do not need to emit it.
  8557. if (D->getDeclContext()->isDependentContext())
  8558. return false;
  8559. // Weak references don't produce any output by themselves.
  8560. if (D->hasAttr<WeakRefAttr>())
  8561. return false;
  8562. // Aliases and used decls are required.
  8563. if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
  8564. return true;
  8565. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  8566. // Forward declarations aren't required.
  8567. if (!FD->doesThisDeclarationHaveABody())
  8568. return FD->doesDeclarationForceExternallyVisibleDefinition();
  8569. // Constructors and destructors are required.
  8570. if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
  8571. return true;
  8572. // The key function for a class is required. This rule only comes
  8573. // into play when inline functions can be key functions, though.
  8574. if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  8575. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  8576. const CXXRecordDecl *RD = MD->getParent();
  8577. if (MD->isOutOfLine() && RD->isDynamicClass()) {
  8578. const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
  8579. if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
  8580. return true;
  8581. }
  8582. }
  8583. }
  8584. GVALinkage Linkage = GetGVALinkageForFunction(FD);
  8585. // static, static inline, always_inline, and extern inline functions can
  8586. // always be deferred. Normal inline functions can be deferred in C99/C++.
  8587. // Implicit template instantiations can also be deferred in C++.
  8588. return !isDiscardableGVALinkage(Linkage);
  8589. }
  8590. const auto *VD = cast<VarDecl>(D);
  8591. assert(VD->isFileVarDecl() && "Expected file scoped var");
  8592. // If the decl is marked as `declare target to`, it should be emitted for the
  8593. // host and for the device.
  8594. if (LangOpts.OpenMP &&
  8595. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  8596. return true;
  8597. if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
  8598. !isMSStaticDataMemberInlineDefinition(VD))
  8599. return false;
  8600. // Variables that can be needed in other TUs are required.
  8601. auto Linkage = GetGVALinkageForVariable(VD);
  8602. if (!isDiscardableGVALinkage(Linkage))
  8603. return true;
  8604. // We never need to emit a variable that is available in another TU.
  8605. if (Linkage == GVA_AvailableExternally)
  8606. return false;
  8607. // Variables that have destruction with side-effects are required.
  8608. if (VD->getType().isDestructedType())
  8609. return true;
  8610. // Variables that have initialization with side-effects are required.
  8611. if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
  8612. // We can get a value-dependent initializer during error recovery.
  8613. (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
  8614. return true;
  8615. // Likewise, variables with tuple-like bindings are required if their
  8616. // bindings have side-effects.
  8617. if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
  8618. for (const auto *BD : DD->bindings())
  8619. if (const auto *BindingVD = BD->getHoldingVar())
  8620. if (DeclMustBeEmitted(BindingVD))
  8621. return true;
  8622. return false;
  8623. }
  8624. void ASTContext::forEachMultiversionedFunctionVersion(
  8625. const FunctionDecl *FD,
  8626. llvm::function_ref<void(FunctionDecl *)> Pred) const {
  8627. assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
  8628. llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
  8629. FD = FD->getMostRecentDecl();
  8630. for (auto *CurDecl :
  8631. FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
  8632. FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
  8633. if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
  8634. std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
  8635. SeenDecls.insert(CurFD);
  8636. Pred(CurFD);
  8637. }
  8638. }
  8639. }
  8640. CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
  8641. bool IsCXXMethod) const {
  8642. // Pass through to the C++ ABI object
  8643. if (IsCXXMethod)
  8644. return ABI->getDefaultMethodCallConv(IsVariadic);
  8645. switch (LangOpts.getDefaultCallingConv()) {
  8646. case LangOptions::DCC_None:
  8647. break;
  8648. case LangOptions::DCC_CDecl:
  8649. return CC_C;
  8650. case LangOptions::DCC_FastCall:
  8651. if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
  8652. return CC_X86FastCall;
  8653. break;
  8654. case LangOptions::DCC_StdCall:
  8655. if (!IsVariadic)
  8656. return CC_X86StdCall;
  8657. break;
  8658. case LangOptions::DCC_VectorCall:
  8659. // __vectorcall cannot be applied to variadic functions.
  8660. if (!IsVariadic)
  8661. return CC_X86VectorCall;
  8662. break;
  8663. case LangOptions::DCC_RegCall:
  8664. // __regcall cannot be applied to variadic functions.
  8665. if (!IsVariadic)
  8666. return CC_X86RegCall;
  8667. break;
  8668. }
  8669. return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
  8670. }
  8671. bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
  8672. // Pass through to the C++ ABI object
  8673. return ABI->isNearlyEmpty(RD);
  8674. }
  8675. VTableContextBase *ASTContext::getVTableContext() {
  8676. if (!VTContext.get()) {
  8677. if (Target->getCXXABI().isMicrosoft())
  8678. VTContext.reset(new MicrosoftVTableContext(*this));
  8679. else
  8680. VTContext.reset(new ItaniumVTableContext(*this));
  8681. }
  8682. return VTContext.get();
  8683. }
  8684. MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
  8685. if (!T)
  8686. T = Target;
  8687. switch (T->getCXXABI().getKind()) {
  8688. case TargetCXXABI::GenericAArch64:
  8689. case TargetCXXABI::GenericItanium:
  8690. case TargetCXXABI::GenericARM:
  8691. case TargetCXXABI::GenericMIPS:
  8692. case TargetCXXABI::iOS:
  8693. case TargetCXXABI::iOS64:
  8694. case TargetCXXABI::WebAssembly:
  8695. case TargetCXXABI::WatchOS:
  8696. return ItaniumMangleContext::create(*this, getDiagnostics());
  8697. case TargetCXXABI::Microsoft:
  8698. return MicrosoftMangleContext::create(*this, getDiagnostics());
  8699. }
  8700. llvm_unreachable("Unsupported ABI");
  8701. }
  8702. CXXABI::~CXXABI() = default;
  8703. size_t ASTContext::getSideTableAllocatedMemory() const {
  8704. return ASTRecordLayouts.getMemorySize() +
  8705. llvm::capacity_in_bytes(ObjCLayouts) +
  8706. llvm::capacity_in_bytes(KeyFunctions) +
  8707. llvm::capacity_in_bytes(ObjCImpls) +
  8708. llvm::capacity_in_bytes(BlockVarCopyInits) +
  8709. llvm::capacity_in_bytes(DeclAttrs) +
  8710. llvm::capacity_in_bytes(TemplateOrInstantiation) +
  8711. llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
  8712. llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
  8713. llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
  8714. llvm::capacity_in_bytes(OverriddenMethods) +
  8715. llvm::capacity_in_bytes(Types) +
  8716. llvm::capacity_in_bytes(VariableArrayTypes);
  8717. }
  8718. /// getIntTypeForBitwidth -
  8719. /// sets integer QualTy according to specified details:
  8720. /// bitwidth, signed/unsigned.
  8721. /// Returns empty type if there is no appropriate target types.
  8722. QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
  8723. unsigned Signed) const {
  8724. TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
  8725. CanQualType QualTy = getFromTargetType(Ty);
  8726. if (!QualTy && DestWidth == 128)
  8727. return Signed ? Int128Ty : UnsignedInt128Ty;
  8728. return QualTy;
  8729. }
  8730. /// getRealTypeForBitwidth -
  8731. /// sets floating point QualTy according to specified bitwidth.
  8732. /// Returns empty type if there is no appropriate target types.
  8733. QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
  8734. TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
  8735. switch (Ty) {
  8736. case TargetInfo::Float:
  8737. return FloatTy;
  8738. case TargetInfo::Double:
  8739. return DoubleTy;
  8740. case TargetInfo::LongDouble:
  8741. return LongDoubleTy;
  8742. case TargetInfo::Float128:
  8743. return Float128Ty;
  8744. case TargetInfo::NoFloat:
  8745. return {};
  8746. }
  8747. llvm_unreachable("Unhandled TargetInfo::RealType value");
  8748. }
  8749. void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
  8750. if (Number > 1)
  8751. MangleNumbers[ND] = Number;
  8752. }
  8753. unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
  8754. auto I = MangleNumbers.find(ND);
  8755. return I != MangleNumbers.end() ? I->second : 1;
  8756. }
  8757. void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
  8758. if (Number > 1)
  8759. StaticLocalNumbers[VD] = Number;
  8760. }
  8761. unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
  8762. auto I = StaticLocalNumbers.find(VD);
  8763. return I != StaticLocalNumbers.end() ? I->second : 1;
  8764. }
  8765. MangleNumberingContext &
  8766. ASTContext::getManglingNumberContext(const DeclContext *DC) {
  8767. assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
  8768. std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
  8769. if (!MCtx)
  8770. MCtx = createMangleNumberingContext();
  8771. return *MCtx;
  8772. }
  8773. std::unique_ptr<MangleNumberingContext>
  8774. ASTContext::createMangleNumberingContext() const {
  8775. return ABI->createMangleNumberingContext();
  8776. }
  8777. const CXXConstructorDecl *
  8778. ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
  8779. return ABI->getCopyConstructorForExceptionObject(
  8780. cast<CXXRecordDecl>(RD->getFirstDecl()));
  8781. }
  8782. void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
  8783. CXXConstructorDecl *CD) {
  8784. return ABI->addCopyConstructorForExceptionObject(
  8785. cast<CXXRecordDecl>(RD->getFirstDecl()),
  8786. cast<CXXConstructorDecl>(CD->getFirstDecl()));
  8787. }
  8788. void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
  8789. TypedefNameDecl *DD) {
  8790. return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
  8791. }
  8792. TypedefNameDecl *
  8793. ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
  8794. return ABI->getTypedefNameForUnnamedTagDecl(TD);
  8795. }
  8796. void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
  8797. DeclaratorDecl *DD) {
  8798. return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
  8799. }
  8800. DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
  8801. return ABI->getDeclaratorForUnnamedTagDecl(TD);
  8802. }
  8803. void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
  8804. ParamIndices[D] = index;
  8805. }
  8806. unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
  8807. ParameterIndexTable::const_iterator I = ParamIndices.find(D);
  8808. assert(I != ParamIndices.end() &&
  8809. "ParmIndices lacks entry set by ParmVarDecl");
  8810. return I->second;
  8811. }
  8812. APValue *
  8813. ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
  8814. bool MayCreate) {
  8815. assert(E && E->getStorageDuration() == SD_Static &&
  8816. "don't need to cache the computed value for this temporary");
  8817. if (MayCreate) {
  8818. APValue *&MTVI = MaterializedTemporaryValues[E];
  8819. if (!MTVI)
  8820. MTVI = new (*this) APValue;
  8821. return MTVI;
  8822. }
  8823. return MaterializedTemporaryValues.lookup(E);
  8824. }
  8825. bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
  8826. const llvm::Triple &T = getTargetInfo().getTriple();
  8827. if (!T.isOSDarwin())
  8828. return false;
  8829. if (!(T.isiOS() && T.isOSVersionLT(7)) &&
  8830. !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
  8831. return false;
  8832. QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
  8833. CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
  8834. uint64_t Size = sizeChars.getQuantity();
  8835. CharUnits alignChars = getTypeAlignInChars(AtomicTy);
  8836. unsigned Align = alignChars.getQuantity();
  8837. unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
  8838. return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
  8839. }
  8840. /// Template specializations to abstract away from pointers and TypeLocs.
  8841. /// @{
  8842. template <typename T>
  8843. static ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
  8844. return ast_type_traits::DynTypedNode::create(*Node);
  8845. }
  8846. template <>
  8847. ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
  8848. return ast_type_traits::DynTypedNode::create(Node);
  8849. }
  8850. template <>
  8851. ast_type_traits::DynTypedNode
  8852. createDynTypedNode(const NestedNameSpecifierLoc &Node) {
  8853. return ast_type_traits::DynTypedNode::create(Node);
  8854. }
  8855. /// @}
  8856. /// A \c RecursiveASTVisitor that builds a map from nodes to their
  8857. /// parents as defined by the \c RecursiveASTVisitor.
  8858. ///
  8859. /// Note that the relationship described here is purely in terms of AST
  8860. /// traversal - there are other relationships (for example declaration context)
  8861. /// in the AST that are better modeled by special matchers.
  8862. ///
  8863. /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
  8864. class ASTContext::ParentMap::ASTVisitor
  8865. : public RecursiveASTVisitor<ASTVisitor> {
  8866. public:
  8867. ASTVisitor(ParentMap &Map) : Map(Map) {}
  8868. private:
  8869. friend class RecursiveASTVisitor<ASTVisitor>;
  8870. using VisitorBase = RecursiveASTVisitor<ASTVisitor>;
  8871. bool shouldVisitTemplateInstantiations() const { return true; }
  8872. bool shouldVisitImplicitCode() const { return true; }
  8873. template <typename T, typename MapNodeTy, typename BaseTraverseFn,
  8874. typename MapTy>
  8875. bool TraverseNode(T Node, MapNodeTy MapNode, BaseTraverseFn BaseTraverse,
  8876. MapTy *Parents) {
  8877. if (!Node)
  8878. return true;
  8879. if (ParentStack.size() > 0) {
  8880. // FIXME: Currently we add the same parent multiple times, but only
  8881. // when no memoization data is available for the type.
  8882. // For example when we visit all subexpressions of template
  8883. // instantiations; this is suboptimal, but benign: the only way to
  8884. // visit those is with hasAncestor / hasParent, and those do not create
  8885. // new matches.
  8886. // The plan is to enable DynTypedNode to be storable in a map or hash
  8887. // map. The main problem there is to implement hash functions /
  8888. // comparison operators for all types that DynTypedNode supports that
  8889. // do not have pointer identity.
  8890. auto &NodeOrVector = (*Parents)[MapNode];
  8891. if (NodeOrVector.isNull()) {
  8892. if (const auto *D = ParentStack.back().get<Decl>())
  8893. NodeOrVector = D;
  8894. else if (const auto *S = ParentStack.back().get<Stmt>())
  8895. NodeOrVector = S;
  8896. else
  8897. NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
  8898. } else {
  8899. if (!NodeOrVector.template is<ParentVector *>()) {
  8900. auto *Vector = new ParentVector(
  8901. 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
  8902. delete NodeOrVector
  8903. .template dyn_cast<ast_type_traits::DynTypedNode *>();
  8904. NodeOrVector = Vector;
  8905. }
  8906. auto *Vector = NodeOrVector.template get<ParentVector *>();
  8907. // Skip duplicates for types that have memoization data.
  8908. // We must check that the type has memoization data before calling
  8909. // std::find() because DynTypedNode::operator== can't compare all
  8910. // types.
  8911. bool Found = ParentStack.back().getMemoizationData() &&
  8912. std::find(Vector->begin(), Vector->end(),
  8913. ParentStack.back()) != Vector->end();
  8914. if (!Found)
  8915. Vector->push_back(ParentStack.back());
  8916. }
  8917. }
  8918. ParentStack.push_back(createDynTypedNode(Node));
  8919. bool Result = BaseTraverse();
  8920. ParentStack.pop_back();
  8921. return Result;
  8922. }
  8923. bool TraverseDecl(Decl *DeclNode) {
  8924. return TraverseNode(
  8925. DeclNode, DeclNode, [&] { return VisitorBase::TraverseDecl(DeclNode); },
  8926. &Map.PointerParents);
  8927. }
  8928. bool TraverseStmt(Stmt *StmtNode) {
  8929. return TraverseNode(
  8930. StmtNode, StmtNode, [&] { return VisitorBase::TraverseStmt(StmtNode); },
  8931. &Map.PointerParents);
  8932. }
  8933. bool TraverseTypeLoc(TypeLoc TypeLocNode) {
  8934. return TraverseNode(
  8935. TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
  8936. [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
  8937. &Map.OtherParents);
  8938. }
  8939. bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
  8940. return TraverseNode(
  8941. NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
  8942. [&] { return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode); },
  8943. &Map.OtherParents);
  8944. }
  8945. ParentMap &Map;
  8946. llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
  8947. };
  8948. ASTContext::ParentMap::ParentMap(ASTContext &Ctx) {
  8949. ASTVisitor(*this).TraverseAST(Ctx);
  8950. }
  8951. ASTContext::DynTypedNodeList
  8952. ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
  8953. if (!Parents)
  8954. // We build the parent map for the traversal scope (usually whole TU), as
  8955. // hasAncestor can escape any subtree.
  8956. Parents = llvm::make_unique<ParentMap>(*this);
  8957. return Parents->getParents(Node);
  8958. }
  8959. bool
  8960. ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
  8961. const ObjCMethodDecl *MethodImpl) {
  8962. // No point trying to match an unavailable/deprecated mothod.
  8963. if (MethodDecl->hasAttr<UnavailableAttr>()
  8964. || MethodDecl->hasAttr<DeprecatedAttr>())
  8965. return false;
  8966. if (MethodDecl->getObjCDeclQualifier() !=
  8967. MethodImpl->getObjCDeclQualifier())
  8968. return false;
  8969. if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
  8970. return false;
  8971. if (MethodDecl->param_size() != MethodImpl->param_size())
  8972. return false;
  8973. for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
  8974. IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
  8975. EF = MethodDecl->param_end();
  8976. IM != EM && IF != EF; ++IM, ++IF) {
  8977. const ParmVarDecl *DeclVar = (*IF);
  8978. const ParmVarDecl *ImplVar = (*IM);
  8979. if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
  8980. return false;
  8981. if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
  8982. return false;
  8983. }
  8984. return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
  8985. }
  8986. uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
  8987. LangAS AS;
  8988. if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
  8989. AS = LangAS::Default;
  8990. else
  8991. AS = QT->getPointeeType().getAddressSpace();
  8992. return getTargetInfo().getNullPointerValue(AS);
  8993. }
  8994. unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
  8995. if (isTargetAddressSpace(AS))
  8996. return toTargetAddressSpace(AS);
  8997. else
  8998. return (*AddrSpaceMap)[(unsigned)AS];
  8999. }
  9000. QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
  9001. assert(Ty->isFixedPointType());
  9002. if (Ty->isSaturatedFixedPointType()) return Ty;
  9003. const auto &BT = Ty->getAs<BuiltinType>();
  9004. switch (BT->getKind()) {
  9005. default:
  9006. llvm_unreachable("Not a fixed point type!");
  9007. case BuiltinType::ShortAccum:
  9008. return SatShortAccumTy;
  9009. case BuiltinType::Accum:
  9010. return SatAccumTy;
  9011. case BuiltinType::LongAccum:
  9012. return SatLongAccumTy;
  9013. case BuiltinType::UShortAccum:
  9014. return SatUnsignedShortAccumTy;
  9015. case BuiltinType::UAccum:
  9016. return SatUnsignedAccumTy;
  9017. case BuiltinType::ULongAccum:
  9018. return SatUnsignedLongAccumTy;
  9019. case BuiltinType::ShortFract:
  9020. return SatShortFractTy;
  9021. case BuiltinType::Fract:
  9022. return SatFractTy;
  9023. case BuiltinType::LongFract:
  9024. return SatLongFractTy;
  9025. case BuiltinType::UShortFract:
  9026. return SatUnsignedShortFractTy;
  9027. case BuiltinType::UFract:
  9028. return SatUnsignedFractTy;
  9029. case BuiltinType::ULongFract:
  9030. return SatUnsignedLongFractTy;
  9031. }
  9032. }
  9033. LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
  9034. if (LangOpts.OpenCL)
  9035. return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
  9036. if (LangOpts.CUDA)
  9037. return getTargetInfo().getCUDABuiltinAddressSpace(AS);
  9038. return getLangASFromTargetAS(AS);
  9039. }
  9040. // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
  9041. // doesn't include ASTContext.h
  9042. template
  9043. clang::LazyGenerationalUpdatePtr<
  9044. const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
  9045. clang::LazyGenerationalUpdatePtr<
  9046. const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
  9047. const clang::ASTContext &Ctx, Decl *Value);
  9048. unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
  9049. assert(Ty->isFixedPointType());
  9050. const auto *BT = Ty->getAs<BuiltinType>();
  9051. const TargetInfo &Target = getTargetInfo();
  9052. switch (BT->getKind()) {
  9053. default:
  9054. llvm_unreachable("Not a fixed point type!");
  9055. case BuiltinType::ShortAccum:
  9056. case BuiltinType::SatShortAccum:
  9057. return Target.getShortAccumScale();
  9058. case BuiltinType::Accum:
  9059. case BuiltinType::SatAccum:
  9060. return Target.getAccumScale();
  9061. case BuiltinType::LongAccum:
  9062. case BuiltinType::SatLongAccum:
  9063. return Target.getLongAccumScale();
  9064. case BuiltinType::UShortAccum:
  9065. case BuiltinType::SatUShortAccum:
  9066. return Target.getUnsignedShortAccumScale();
  9067. case BuiltinType::UAccum:
  9068. case BuiltinType::SatUAccum:
  9069. return Target.getUnsignedAccumScale();
  9070. case BuiltinType::ULongAccum:
  9071. case BuiltinType::SatULongAccum:
  9072. return Target.getUnsignedLongAccumScale();
  9073. case BuiltinType::ShortFract:
  9074. case BuiltinType::SatShortFract:
  9075. return Target.getShortFractScale();
  9076. case BuiltinType::Fract:
  9077. case BuiltinType::SatFract:
  9078. return Target.getFractScale();
  9079. case BuiltinType::LongFract:
  9080. case BuiltinType::SatLongFract:
  9081. return Target.getLongFractScale();
  9082. case BuiltinType::UShortFract:
  9083. case BuiltinType::SatUShortFract:
  9084. return Target.getUnsignedShortFractScale();
  9085. case BuiltinType::UFract:
  9086. case BuiltinType::SatUFract:
  9087. return Target.getUnsignedFractScale();
  9088. case BuiltinType::ULongFract:
  9089. case BuiltinType::SatULongFract:
  9090. return Target.getUnsignedLongFractScale();
  9091. }
  9092. }
  9093. unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
  9094. assert(Ty->isFixedPointType());
  9095. const auto *BT = Ty->getAs<BuiltinType>();
  9096. const TargetInfo &Target = getTargetInfo();
  9097. switch (BT->getKind()) {
  9098. default:
  9099. llvm_unreachable("Not a fixed point type!");
  9100. case BuiltinType::ShortAccum:
  9101. case BuiltinType::SatShortAccum:
  9102. return Target.getShortAccumIBits();
  9103. case BuiltinType::Accum:
  9104. case BuiltinType::SatAccum:
  9105. return Target.getAccumIBits();
  9106. case BuiltinType::LongAccum:
  9107. case BuiltinType::SatLongAccum:
  9108. return Target.getLongAccumIBits();
  9109. case BuiltinType::UShortAccum:
  9110. case BuiltinType::SatUShortAccum:
  9111. return Target.getUnsignedShortAccumIBits();
  9112. case BuiltinType::UAccum:
  9113. case BuiltinType::SatUAccum:
  9114. return Target.getUnsignedAccumIBits();
  9115. case BuiltinType::ULongAccum:
  9116. case BuiltinType::SatULongAccum:
  9117. return Target.getUnsignedLongAccumIBits();
  9118. case BuiltinType::ShortFract:
  9119. case BuiltinType::SatShortFract:
  9120. case BuiltinType::Fract:
  9121. case BuiltinType::SatFract:
  9122. case BuiltinType::LongFract:
  9123. case BuiltinType::SatLongFract:
  9124. case BuiltinType::UShortFract:
  9125. case BuiltinType::SatUShortFract:
  9126. case BuiltinType::UFract:
  9127. case BuiltinType::SatUFract:
  9128. case BuiltinType::ULongFract:
  9129. case BuiltinType::SatULongFract:
  9130. return 0;
  9131. }
  9132. }
  9133. FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const {
  9134. assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
  9135. "Can only get the fixed point semantics for a "
  9136. "fixed point or integer type.");
  9137. if (Ty->isIntegerType())
  9138. return FixedPointSemantics::GetIntegerSemantics(getIntWidth(Ty),
  9139. Ty->isSignedIntegerType());
  9140. bool isSigned = Ty->isSignedFixedPointType();
  9141. return FixedPointSemantics(
  9142. static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
  9143. Ty->isSaturatedFixedPointType(),
  9144. !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
  9145. }
  9146. APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
  9147. assert(Ty->isFixedPointType());
  9148. return APFixedPoint::getMax(getFixedPointSemantics(Ty));
  9149. }
  9150. APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
  9151. assert(Ty->isFixedPointType());
  9152. return APFixedPoint::getMin(getFixedPointSemantics(Ty));
  9153. }
  9154. QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
  9155. assert(Ty->isUnsignedFixedPointType() &&
  9156. "Expected unsigned fixed point type");
  9157. const auto *BTy = Ty->getAs<BuiltinType>();
  9158. switch (BTy->getKind()) {
  9159. case BuiltinType::UShortAccum:
  9160. return ShortAccumTy;
  9161. case BuiltinType::UAccum:
  9162. return AccumTy;
  9163. case BuiltinType::ULongAccum:
  9164. return LongAccumTy;
  9165. case BuiltinType::SatUShortAccum:
  9166. return SatShortAccumTy;
  9167. case BuiltinType::SatUAccum:
  9168. return SatAccumTy;
  9169. case BuiltinType::SatULongAccum:
  9170. return SatLongAccumTy;
  9171. case BuiltinType::UShortFract:
  9172. return ShortFractTy;
  9173. case BuiltinType::UFract:
  9174. return FractTy;
  9175. case BuiltinType::ULongFract:
  9176. return LongFractTy;
  9177. case BuiltinType::SatUShortFract:
  9178. return SatShortFractTy;
  9179. case BuiltinType::SatUFract:
  9180. return SatFractTy;
  9181. case BuiltinType::SatULongFract:
  9182. return SatLongFractTy;
  9183. default:
  9184. llvm_unreachable("Unexpected unsigned fixed point type");
  9185. }
  9186. }