ASTContext.cpp 326 KB

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